Skip to content

For packages built on the engine

extend

For packages built on the engine.

A dimension package -- a calendar, a geography -- subclasses NestedScale, registers methods on the hooks and reuses pieces of the recast engine. This module is the one place such a package imports from besides the package itself: every name here is public and stable, and nothing a subclassing package needs has to be taken from a module or a method whose name starts with an underscore.

Defining a subclass scale_init() sets the fields of an object under construction (a scale is frozen, so a subclass __init__ cannot assign them); scale_construct() then normalises and validates it; register_scale_validator() adds the checks of the subclass; set_scale_package() names the package in messages and in definition files; scale_errors() lists what is wrong with an object without raising; register_scale_class() lets read_scale() give the class back; scale_alias_property() names an inherited field in the words of the dimension.

Hooks (each a functools.singledispatch function; register a method with hook.register(TheClass)) scale_vocab, scale_payload_slice, scale_payload_collapse, scale_payload_parts, scale_write_payload, scale_read_payload, scale_leaf_pairs; recast.register for the bare recast() verb. Inside a hook, scale_set_props() makes the changed copy and scale_validate() checks one.

Data backends backend_of, backend_is_lazy, backend_schema, backend_scan, backend_pull, backend_restore, backend_bind_rows, backend_distinct and the Backend they pass around: accept the inputs the core verbs accept and return the caller's type.

Engine pieces join_na() (a join in which missing keys match), recast_complete() (a result completed to the full target vocabulary, in the contract's row order), group_parts() and group_result() (the aggregates of one value column under one rule).

Member tables ATTR_SCHEMA, ALIAS_SCHEMA, LABEL_SCHEMA and empty_attributes(), empty_aliases(), empty_labels().

Example: a subclass with a field of its own, a validator and a package name.

import pyarrow as pa import nestedscales as ns from nestedscales import extend class Ledger(ns.NestedScale): ... def init(self, leaftable, frames, members, currency="EUR"): ... extend.scale_init(self, leaftable=leaftable, frames=frames, ... members=members, leaf=frames[-1], ... meta={"name": "ledger"}, currency=currency) ... extend.scale_construct(self) _ = extend.set_scale_package(Ledger, "ledgers") @extend.register_scale_validator(Ledger) ... def _ledger_errors(x): ... ok = isinstance(x.currency, str) and len(x.currency) == 3 ... return [] if ok else ["currency must be a 3-letter code"] lt = pa.table({"book": ["a", "a", "b"], "account": ["a1", "a2", "b1"]}) members = {"book": ["a", "b"], "account": ["a1", "a2", "b1"]} led = Ledger(lt, ["book", "account"], members) led.currency, ns.scale_members(led, "book") ('EUR', ['a', 'b']) try: ... Ledger(lt, ["book", "account"], members, currency="euro") ... except ns.NestedScalesError as e: ... print(e) object is invalid: - currency must be a 3-letter code

Backend dataclass

What a data argument is, and whether it is lazy.

NestedScale dataclass

A nested discrete partition: a table of leaves plus the frames grouping them.

Construct with scale_from_leaftable(). The object is immutable and every verb returns a new one: the fields cannot be assigned, the tables are Arrow tables, frames and each entry of members are tuples, and meta and members are read-only dicts (an assignment into them raises TypeError; dict(x.meta) and {**x.meta} give a plain copy). The read-only protection is one level deep: a container held as a value of meta is not copied and must not be changed in place. A changed copy is made with scale_set_props().

Two scales are equal when they are of the same class and every field is equal, a subclass's own fields included.

Examples

import nestedscales as ns s = ns.scale_example() s s.meta["name"] 'example' s == ns.scale_example() True

__getitem__

__getitem__(idx: tuple) -> NestedScale

x[frame, member] is filter_scale(x, frame, member), as in R.

NestedScalesError

Bases: ValueError

Raised for every user-facing error (R: .stop()).

NestedScalesWarning

Bases: UserWarning

Issued for every user-facing warning (R: .warn()).

backend_bind_rows

backend_bind_rows(parts: Sequence[Table]) -> pa.Table

Row-bind tables, unifying their schemas.

backend_distinct

backend_distinct(
    data: Any,
    columns: Sequence[str],
    backend: Backend | None = None,
) -> pa.Table

Distinct combinations of columns in first-appearance order, as a pyarrow.Table.

data is any supported table; only columns are read from a lazy one. Not exported by R, where it is internal.

backend_is_lazy

backend_is_lazy(backend: Backend) -> bool

Is this a lazy backend (pyarrow Dataset, polars LazyFrame)?

backend_of

backend_of(data: Any, arg: str = 'data') -> Backend

Classify a data argument; error when it is not a supported table.

arg is the argument name the error message uses.

backend_pull

backend_pull(table: Any) -> pa.Table

Any supported table, collected into a pyarrow.Table.

backend_restore

backend_restore(
    table: Table,
    backend: Backend,
    collect: bool | None = None,
) -> Any

A result in the caller's type: pandas, polars, a LazyFrame (unless collect), or a pyarrow.Table.

backend_scan

backend_scan(
    data: Any,
    backend: Backend | None = None,
    columns: Sequence[str] | None = None,
    filter: Expression | None = None,
) -> pa.Table

Materialise the needed columns (and rows) of a data argument, pushing the projection and filter into the scan of a lazy input.

columns=None reads every column; filter is a pyarrow.compute expression. Not exported by R, where it is internal.

backend_schema

backend_schema(
    data: Any, backend: Backend | None = None
) -> pa.Schema

Column names and types, without scanning a lazy input.

empty_aliases

empty_aliases() -> pa.Table

A table of no alias rows, with the columns and types of ALIAS_SCHEMA.

empty_attributes

empty_attributes() -> pa.Table

A table of no attribute rows, with the columns and types of ATTR_SCHEMA.

empty_labels

empty_labels() -> pa.Table

A table of no label rows, with the columns and types of LABEL_SCHEMA.

format_totals

format_totals(
    values: Sequence[float], digits: int = 6
) -> list[str]

Numbers formatted as one vector the way a summary prints them.

The result is what R's format(values, big.mark = ",", digits = 6) gives: a common number of decimals, fixed notation unless the scientific one is narrower, thousands separated by commas, right-justified to one width.

group_parts

group_parts(
    rule: str,
    val: ChunkedArray,
    ww: ChunkedArray,
    na_rm: bool,
) -> tuple[dict, list]

The columns and aggregates that compute one value column under one rule in a grouped aggregation, the first half of group_result().

rule is "sum", "mean", "weighted_mean", "copy" or "sd"; val the values as float64 and ww the weights, row by row; na_rm drops nulls and NaN instead of making the group null. Returns (columns, specs): columns maps a short name to an array to add to the table being grouped (under a prefix of the caller's choice), and specs lists (column, function, options) for pyarrow.TableGroupBy.aggregate(), the column named without the prefix.

group_result

group_result(
    rule: str, g: dict, na_rm: bool
) -> pa.ChunkedArray

The aggregate of one value column from the grouped columns that group_parts() asked for.

g maps "<column>_<function>" (the names of specs, without the caller's prefix) to the aggregated arrays. Returns the float64 result, one entry per group.

join_na

join_na(
    left: Table,
    right: Table,
    keys: Sequence[str],
    join_type: str = "left outer",
) -> pa.Table

Join two tables on keys so that missing keys match each other (dplyr's na_matches = "na"); a plain Arrow join never matches a null.

keys are columns of both tables; join_type is one of pyarrow's. The order of the rows of the result is not defined.

recast

recast(
    x: Any, scale: Any, *args: Any, **kwargs: Any
) -> Any

Recast data x through scale, dispatching on the scale's class.

For a NestedScale the arguments are those of recast_scale(): target is the target frame (or scale) and source the source frame, inferred when omitted.

Dimension packages register methods with recast.register(TheirClass). A method is called with the SCALE first and the data second, the two leading arguments of recast() swapped, followed by the remaining arguments unchanged: method(scale, x, *args, **kwargs).

Examples

import pyarrow as pa import nestedscales as ns d = pa.table({"period": ["p1", "p2", "p3", "p4"], "v": [1.0, 2, 3, 4]}) ns.recast(d, ns.scale_example2(), "era", rule="sum").to_pylist() [{'era': 'E1', 'v': 3.0}, {'era': 'E2', 'v': 7.0}]

recast_complete

recast_complete(
    res: Table,
    idc: Table,
    out_keys: Sequence[str | None],
    key: str,
    id_cols: Sequence[str],
    values: Sequence[str],
) -> pa.Table

Complete a recast result to the full target vocabulary, in the row order of the contract.

res has the columns key, id_cols and values, with one row per observed (identifier group, target code); idc holds the identifier groups in the order they are to appear (backend_distinct() of the data), and out_keys the target codes in member order, a None last when the missing-target row is kept. The result has one row per group and code -- groups in the order of idc, codes in the order of out_keys -- with nulls where res had no row, and the columns key, id_cols, values.

register_scale_class

register_scale_class(cls: type) -> str

Register a NestedScale subclass under its pkg::Name so read_scale() can give it back.

register_scale_validator

register_scale_validator(
    cls: type,
    validator: Callable[[Any], Sequence[str]] | None = None,
) -> Callable

Register the checks of a subclass.

validator(x) returns a list of messages, empty when the object is sound; it runs after the core checks and after the validators of the parent classes, on every construction and every scale_validate(). One validator per class: registering again replaces it. Used directly, register_scale_validator(Cls, fn), or as a decorator, @register_scale_validator(Cls). Returns the validator.

scale_alias_property

scale_alias_property(name: str) -> property

A read-only property exposing an inherited field under another name.

How a Calendar keeps timeframes and a Geoscale keeps geoframes over the inherited frames.

scale_construct

scale_construct(x: NestedScale) -> None

Finish the construction of a subclass object: normalise its fields, then validate it as the core class and as its own.

Called last in the __init__ of a subclass, after scale_init(). The order is S7's: the object is first validated as a NestedScale, so a failure of the core checks names the core class; then every check runs (the core's and those registered with register_scale_validator(), parents first) and a failure names the subclass. Raises NestedScalesError listing every problem.

scale_errors

scale_errors(x: NestedScale) -> list[str]

What is wrong with a scale: the messages of every check, the core's first and then those of the validators registered for its classes, parents first. Empty for a valid scale. Nothing is raised and x is not changed.

scale_init

scale_init(x: NestedScale, **fields: Any) -> None

Set the fields of a scale that is being constructed.

For the __init__ of a subclass: a scale is a frozen object, so plain assignment to self is refused, and this function is how a constructor stores leaftable, frames, members, leaf, meta, attributes, aliases, labels and the fields the subclass adds. The values are stored as given; scale_construct() coerces and checks them. meta defaults to an empty dict and the three member tables to empty tables when the constructor does not set them; leaf defaults to "leaf".

It is not a way to change a finished scale: for that, scale_set_props() returns a changed copy.

scale_leaf_pairs

scale_leaf_pairs(
    x: NestedScale,
    source: str,
    target: str,
    weight: str | None = None,
    **kwargs: object,
) -> pa.Table

Leaf-level correspondence between two frames: columns source, target, w.

The seam a dimension package overrides (scale_leaf_pairs.register) when its leaf layer is generated; extra identifier columns must be named in the caller's by.

scale_payload_collapse

scale_payload_collapse(
    x: NestedScale, map: Sequence[int | None]
) -> NestedScale

Merge a subclass's per-leaf payload after a collapse.

The companion of scale_payload_slice() for the rebuilds that MERGE leaves -- prune_scale(), which makes a coarser frame the leaf layer. map has one entry per row of the FORMER leaftable: the 0-based index of the new row that leaf was merged into, or None for a leaf that was dropped. The object arrives with the new core fields set and not yet validated; the method may change any field, the name of the leaf column included, with scale_set_props(). The NestedScale default returns x unchanged, which is right for a payload keyed by member codes.

scale_payload_parts

scale_payload_parts(x: NestedScale) -> Any

Describe the parts a subclass adds to a scale.

The seam a dimension package overrides so that scale_tree() can mark the fields it adds and name its own verbs. The method returns a table (or a list of dicts) with a part column and any of parent, kind, shape, mark, verb and note. A row whose part and parent match a part the core already lists replaces the fields it gives; any other row is added. A top-level part is a field of the object; parent names the field a part belongs to. mark is one of "fixed", "derived" or "mutable". The NestedScale default adds nothing.

scale_payload_slice

scale_payload_slice(
    x: NestedScale, i: Sequence[int]
) -> NestedScale

Subset a subclass's per-leaf payload to the kept leaftable rows i.

Called whenever the engine rebuilds an object from a row subset, with the core fields already set to the subset and the object not yet validated; i holds the 0-based indices of the kept rows of the former leaftable. The method returns the object, changed with scale_set_props(). The NestedScale default has no payload and returns x unchanged.

scale_read_payload

scale_read_payload(
    x: NestedScale, dir: Path | None, header: Mapping
) -> NestedScale

Rebuild a subclass from the core scale and its payload files.

Called by read_scale() with the CORE scale rebuilt from the header, the directory the files are in and the header; dispatched on the class registered under the header's class (see register_scale_class()), so the method is registered for the subclass and receives a plain NestedScale. It returns the subclass object. A scale held in meta arrives as its reference, {"_scale": {"name", "id"}}.

scale_set_props

scale_set_props(
    x: NestedScale, check: bool = False, **props: Any
) -> NestedScale

A copy of x with fields replaced, keeping the concrete class.

The counterpart of R's S7::set_props(x, ..., .check = FALSE), for the payload hooks of a subclass: a hook receives an object whose parts are consistent only once it has finished, so the copy is not validated unless check=True. Any field of the object may be named, a subclass's own included. x is left as it was.

A field replaced without check=True is stored as given: meta and members become read-only, and the other fields are coerced, when the copy is validated.

Examples

import nestedscales as ns s = ns.scale_example() t = ns.scale_set_props(s, check=True, meta={**s.meta, "source": "demo"}) t.meta["source"], "source" in s.meta ('demo', False)

scale_validate

scale_validate(x: NestedScale) -> NestedScale

Normalise and validate x in place and return it (R: S7::validate()).

Raises NestedScalesError listing every problem. Normalising coerces the fields to their stored forms (tuples, read-only dicts, the member tables' schemas); on an object that was built by a constructor or returned by a verb it changes nothing, so the only objects it alters are those under construction: a copy from scale_set_props() that was not checked, or self inside a subclass constructor.

scale_vocab

scale_vocab(x: NestedScale) -> dict[str, str]

The words engine messages use for this scale's dimension.

Subclasses register their own implementation with scale_vocab.register(Subclass).

scale_write_payload

scale_write_payload(
    x: NestedScale, dir: Path | None, header: dict
) -> dict

Write a subclass's payload in a definition; returns the header.

Called by write_scale() after the core tables are written, with the subclass object, the bundle directory (None for a single-file definition, which can hold inline data only) and the header so far. The method writes its files and returns the header with its entries added under "payload"; it may also adjust "meta" and "meta_vectors" (the top-level meta entries the other binding reads as named vectors). The NestedScale default returns the header unchanged.

set_scale_package

set_scale_package(cls: type, package: str) -> type

Name the package a subclass belongs to.

The name is the prefix of the qualified class name, <package>::<Class>, that validation messages show and that write_scale() records in a definition, so it has to be the name the R package of the same dimension uses. Without it the top-level module of the class is used. Call it before register_scale_class(). Returns cls.

scale_init

scale_init(x: NestedScale, **fields: Any) -> None

Set the fields of a scale that is being constructed.

For the __init__ of a subclass: a scale is a frozen object, so plain assignment to self is refused, and this function is how a constructor stores leaftable, frames, members, leaf, meta, attributes, aliases, labels and the fields the subclass adds. The values are stored as given; scale_construct() coerces and checks them. meta defaults to an empty dict and the three member tables to empty tables when the constructor does not set them; leaf defaults to "leaf".

It is not a way to change a finished scale: for that, scale_set_props() returns a changed copy.

scale_construct

scale_construct(x: NestedScale) -> None

Finish the construction of a subclass object: normalise its fields, then validate it as the core class and as its own.

Called last in the __init__ of a subclass, after scale_init(). The order is S7's: the object is first validated as a NestedScale, so a failure of the core checks names the core class; then every check runs (the core's and those registered with register_scale_validator(), parents first) and a failure names the subclass. Raises NestedScalesError listing every problem.

scale_errors

scale_errors(x: NestedScale) -> list[str]

What is wrong with a scale: the messages of every check, the core's first and then those of the validators registered for its classes, parents first. Empty for a valid scale. Nothing is raised and x is not changed.

register_scale_validator

register_scale_validator(
    cls: type,
    validator: Callable[[Any], Sequence[str]] | None = None,
) -> Callable

Register the checks of a subclass.

validator(x) returns a list of messages, empty when the object is sound; it runs after the core checks and after the validators of the parent classes, on every construction and every scale_validate(). One validator per class: registering again replaces it. Used directly, register_scale_validator(Cls, fn), or as a decorator, @register_scale_validator(Cls). Returns the validator.

set_scale_package

set_scale_package(cls: type, package: str) -> type

Name the package a subclass belongs to.

The name is the prefix of the qualified class name, <package>::<Class>, that validation messages show and that write_scale() records in a definition, so it has to be the name the R package of the same dimension uses. Without it the top-level module of the class is used. Call it before register_scale_class(). Returns cls.

backend_scan

backend_scan(
    data: Any,
    backend: Backend | None = None,
    columns: Sequence[str] | None = None,
    filter: Expression | None = None,
) -> pa.Table

Materialise the needed columns (and rows) of a data argument, pushing the projection and filter into the scan of a lazy input.

columns=None reads every column; filter is a pyarrow.compute expression. Not exported by R, where it is internal.

backend_distinct

backend_distinct(
    data: Any,
    columns: Sequence[str],
    backend: Backend | None = None,
) -> pa.Table

Distinct combinations of columns in first-appearance order, as a pyarrow.Table.

data is any supported table; only columns are read from a lazy one. Not exported by R, where it is internal.

join_na

join_na(
    left: Table,
    right: Table,
    keys: Sequence[str],
    join_type: str = "left outer",
) -> pa.Table

Join two tables on keys so that missing keys match each other (dplyr's na_matches = "na"); a plain Arrow join never matches a null.

keys are columns of both tables; join_type is one of pyarrow's. The order of the rows of the result is not defined.

recast_complete

recast_complete(
    res: Table,
    idc: Table,
    out_keys: Sequence[str | None],
    key: str,
    id_cols: Sequence[str],
    values: Sequence[str],
) -> pa.Table

Complete a recast result to the full target vocabulary, in the row order of the contract.

res has the columns key, id_cols and values, with one row per observed (identifier group, target code); idc holds the identifier groups in the order they are to appear (backend_distinct() of the data), and out_keys the target codes in member order, a None last when the missing-target row is kept. The result has one row per group and code -- groups in the order of idc, codes in the order of out_keys -- with nulls where res had no row, and the columns key, id_cols, values.

group_parts

group_parts(
    rule: str,
    val: ChunkedArray,
    ww: ChunkedArray,
    na_rm: bool,
) -> tuple[dict, list]

The columns and aggregates that compute one value column under one rule in a grouped aggregation, the first half of group_result().

rule is "sum", "mean", "weighted_mean", "copy" or "sd"; val the values as float64 and ww the weights, row by row; na_rm drops nulls and NaN instead of making the group null. Returns (columns, specs): columns maps a short name to an array to add to the table being grouped (under a prefix of the caller's choice), and specs lists (column, function, options) for pyarrow.TableGroupBy.aggregate(), the column named without the prefix.

group_result

group_result(
    rule: str, g: dict, na_rm: bool
) -> pa.ChunkedArray

The aggregate of one value column from the grouped columns that group_parts() asked for.

g maps "<column>_<function>" (the names of specs, without the caller's prefix) to the aggregated arrays. Returns the float64 result, one entry per group.

format_totals

format_totals(
    values: Sequence[float], digits: int = 6
) -> list[str]

Numbers formatted as one vector the way a summary prints them.

The result is what R's format(values, big.mark = ",", digits = 6) gives: a common number of decimals, fixed notation unless the scientific one is narrower, thousands separated by commas, right-justified to one width.

empty_attributes

empty_attributes() -> pa.Table

A table of no attribute rows, with the columns and types of ATTR_SCHEMA.

empty_aliases

empty_aliases() -> pa.Table

A table of no alias rows, with the columns and types of ALIAS_SCHEMA.

empty_labels

empty_labels() -> pa.Table

A table of no label rows, with the columns and types of LABEL_SCHEMA.