ihb2032/MoonFrame/series does not have a README file

    KeyCell

    type KeyCell derive(Eq, Hash)

    One cell of a composite key, normalised for hashing / equality. Kept separate from Scalar because keying needs NaN to collapse and -0.0 to fold — both differ from Scalar's IEEE-following Eq — and a key never needs Scalar's numeric-promotion comparisons. KNull lets group_by give a null cell its own group; join rejects a null key before building the tuple (see join_row_key).

    ReduceOp

    pub(all) enum ReduceOp {
    Sum
    Mean
    Min
    Max
    Count
    Std
    Var
    Median
    NUnique
    First
    Last
    }

    The eleven reductions the shared kernel resolves. Lives here in series and is pub(all) so the frame-side aggregations can construct it — they can't reuse @expr.AggOp, a read-only enum (matchable but not constructible outside expr). The grouped (agg) and scoped (eval_agg) reductions both map @expr.AggOp into this one vocabulary.

    This variant list mirrors @expr.AggOp one-to-one; frame's reduce_op_of_agg translates between them. Keep the two in lockstep — a reduction added here must also be added to @expr.AggOp and to that map.

    Series

    A one-dimensional, dtype-aware column with a name. Series is the per-column unit behind DataFrame: it bundles a ColumnStorage (the pluggable backend seam — Builtin Arrow storage with an explicit validity bitmap, or the all-valid unboxed Numeric fast path) with a column name, and exposes the structural, nullability, transform, and cast surface that ops / IO layers rely on. Statistics live in series_stats.mbt.

    The storage field is a ColumnStorage as of v0.3 (it was a bare BuiltinColumn through v0.2). Every accessor forwards to the identically-named ColumnStorage method, so the backend is transparent to readers — storage_kind / to_numeric / to_builtin are the only surface that observes or chooses it.

    The struct is read-only from outside this package — always go through the named constructors so the underlying column maintains its data-and-validity invariants.

    Series::cast

    Cast to the target dtype, the single cross-dtype conversion entry (Polars' Series.cast). Delegates to BuiltinColumn::cast; the supported targets are:

    • Int — identity on Int; Float truncates toward zero (NaN, ±Inf, and out-of-Int64-range values raise ParseError); Bool → 1 / 0; String parses plain base-10 integers (other forms raise ParseError).
    • Float — Int promoted; identity on Float; Bool → 1.0 / 0.0; String parses decimals / scientific notation.
    • String — every dtype renders to its value form; never rejects a value, so the only failure is the unsupported-target guard below.

    Null slots are preserved verbatim. A numeric result lands on the Builtin backend (re-converge with to_numeric for the fast path). Bool and Null targets raise Unsupported(_).

    Series::count

    fn Series::count(self : Series) -> Int

    Count of non-null cells.

    Series::drop_nulls

    fn Series::drop_nulls(self : Series) -> Series

    Drop every null cell. The returned series has len = original.len -original.null_count and no null cells left. A source that already has no nulls is returned unchanged — so an all-valid Numeric column stays on the fast path (no bitmap to carry); otherwise the kept cells are gathered, and a numeric result — now necessarily all-valid — canonicalises onto Numeric (gather_series), so dropping nulls cannot leave a numeric column off the fast path.

    Series::dtype

    Logical dtype. Delegates to the underlying column so the two never drift apart.

    Series::fill_null

    Replace every null cell with value. raise TypeMismatch(...) if value is Scalar::Null (filling nulls with null is meaningless) or if its dtype differs from the series'. The returned series has a fully-valid bitmap and keeps the source storage backend (preserve_backend) — a no-op fill on an all-valid Numeric column stays Numeric.

    Series::from_bool_options

    fn Series::from_bool_options(name : String, values : Array[Bool?]) -> Series

    Build a Bool series where None entries are nulls.

    Series::from_bools

    fn Series::from_bools(name : String, values : Array[Bool]) -> Series

    Build a Bool series from raw values (no nulls). Bool is non-numeric, so it lands on the Builtin backend. values is defensively copied, so the series is independent of the caller's array.

    Series::from_builtin

    fn Series::from_builtin(name : String, storage :
    BuiltinColumn
    ) -> Series

    Wrap an existing BuiltinColumn under the given name, behind a ColumnStorage::Builtin. The source-compatible path for callers that already hold a BuiltinColumn (the v0.2 new signature).

    Series::from_float_options

    fn Series::from_float_options(name : String, values : Array[Double?]) -> Series

    Build a Float series where None entries are nulls. Nullable, so it lands on the Builtin backend.

    Series::from_floats

    fn Series::from_floats(name : String, values : Array[Double]) -> Series

    Build a Float series from raw values (no nulls). Lands on the Numeric fast-path backend. Like from_ints, values is defensively copied, so the series is independent of the caller's array.

    Series::from_int_options

    fn Series::from_int_options(name : String, values : Array[Int64?]) -> Series

    Build an Int series where None entries are nulls. Nullable, so it lands on the general-purpose Builtin backend.

    Series::from_ints

    fn Series::from_ints(name : String, values : Array[Int64]) -> Series

    Build an Int series from raw values (no nulls). Lands on the Numeric fast-path backend — no validity bitmap is allocated.

    values is defensively copied, so a Series is independent of the caller's array: mutating values afterwards does not change the series' cells. (The nullable constructors from_*_options likewise copy while boxing into Option.)

    Series::from_string_options

    fn Series::from_string_options(name : String, values : Array[String?]) -> Series

    Build a String series where None entries are nulls.

    Series::from_strings

    fn Series::from_strings(name : String, values : Array[String]) -> Series

    Build a String series from raw values (no nulls). String is non-numeric, so it lands on the Builtin backend. values is defensively copied, so the series is independent of the caller's array.

    Series::gather

    fn Series::gather(self : Series, indices : Array[Int]) -> Series raise
    DataError

    Gather: produce a new series whose i-th entry is self[indices[i]]. Out-of-bounds indices surface as IndexOutOfBounds(idx). The result is canonicalised onto the Numeric fast path when the gathered rows leave an Int / Float column all-valid (the same invariant gather_series keeps), so the backend is a function of the gathered content, not the source.

    Series::get

    Read cell i as a Scalar (Null for null cells). Out-of-bounds indices bubble the underlying IndexOutOfBounds error.

    Series::is_empty

    fn Series::is_empty(self : Series) -> Bool

    true when the series has zero cells.

    Series::is_null

    fn Series::is_null(self : Series, i : Int) -> Bool raise
    DataError

    Whether cell i is null. Out-of-bounds indices bubble the underlying IndexOutOfBounds error.

    Series::len

    fn Series::len(self : Series) -> Int

    Number of cells (valid plus null).

    Series::max

    Maximum non-null cell as a Scalar (Polars' Series.max). Mirrors min with the order reversed; the Float NaN and empty-series rules are identical. Total — unlike the v0.1 Result-wrapped form this replaces.

    Series::mean

    Arithmetic mean of non-null cells, returned as Double.

    Int columns accumulate the numerator in Double (the mean's output type), so a large-magnitude column cannot wrap past 2^63 and flip the mean's sign; Float columns accumulate in Double. The division is performed in Double. (Series::sum, by contrast, keeps the Int dtype and so accumulates in Int64, overflowing past 2^63.)

    The denominator is the non-null count (Series::count), so a Float NaN is a present value that both counts toward the divisor and propagates: any non-null NaN makes the mean NaN (Polars semantics; only Null is skipped).

    • Empty / all-null numeric series → raise InvalidOperation(...).
    • Non-numeric series → raise TypeMismatch(...).

    Series::mean_opt

    fn Series::mean_opt(self : Series) -> Double?

    Total arithmetic mean: Some(mean) for a numeric series with at least one non-null cell, None for a non-numeric, empty, or all-null series — i.e. None exactly where Series::mean raises (TypeMismatch / InvalidOperation). This is the total form frame's DataFrame::describe summarises with, mirroring the total min / max; Series::mean remains the raising public form that distinguishes the two failure causes, and this folds both of them into None. A Float NaN is summed in and propagates to Some(NaN), matching mean (Polars — only Null is missing). Exercised directly by this package's tests and, across the package boundary, by DataFrame::describe (which summarises numeric, non-numeric, and all-null columns, so both arms below are reached).

    Series::min

    Minimum non-null cell as a Scalar, by the natural order of the series' dtype (Polars' Series.min). Total — every v0.1 dtype has an order, so it never fails (unlike the v0.1 Result-wrapped form this replaces).

    • Empty / all-null → Scalar::Null.
    • Float NaN is skipped (treated as missing), matching sort and Polars' regular min / max, which ignore NaN — distinct from the propagating nan_min / nan_max. (This differs from sum / mean, where NaN propagates — exactly as in Polars.) A series of only NaN (and/or nulls) → Scalar::Null.
    • Bool order: false < true.

    Series::n_unique

    fn Series::n_unique(self : Series) -> Int

    Number of distinct non-null values. Cells are keyed by the same composite-key normalisation group_by / join use (key_cell), so the distinct count agrees with grouping cell-for-cell: two cells collide exactly when they would share a group_by group. Two Float normalisations follow from that shared key — every NaN collapses into one bucket (it is a value, not missing, so it is one distinct value, the rule that also puts every NaN key in one group_by group), and -0.0 folds into +0.0 (they are IEEE-equal and share a group, hence one distinct value). Keying by Scalar::to_string would instead let the -0.0 rendering split them, diverging from group_by.

    Series::name

    fn Series::name(self : Series) -> String

    Column name.

    Series::new

    Wrap an existing ColumnStorage under the given name — the canonical constructor at the backend seam. The backend (and validity / null-count) is whatever the storage already carries. Callers holding a BuiltinColumn use from_builtin instead.

    Series::null_count

    fn Series::null_count(self : Series) -> Int

    Number of null cells.

    Series::rename

    fn Series::rename(self : Series, new_name : String) -> Series

    Return a copy of this series with a different column name. Storage is shared (immutable), so this is O(1).

    Series::slice

    fn Series::slice(self : Series, start : Int, end : Int) -> Series raise
    DataError

    Half-open [start, end) slice. Bounds checks mirror BuiltinColumn::slice; errors surface unchanged so callers receive the same IndexOutOfBounds / InvalidOperation diagnostics.

    Series::storage

    Expose the underlying ColumnStorage. Ops layers use this to reach the typed (int_values / float_values / ...) accessors and the data() / validity() reads, bypassing Scalar boxing. The return type changed from BuiltinColumn to ColumnStorage in v0.3; the data() / validity() surface is identical, so column-reading call sites are unaffected.

    Series::storage_kind

    Which storage backend currently backs this column: Numeric for the all-valid unboxed fast path (built by from_ints / from_floats, and preserved through structural transforms), Builtin otherwise.

    Series::sum

    Sum of non-null cells.

    • Int series → Scalar::Int(sum), accumulated in 64-bit Int64 (so only sums past 2^63 overflow, not the old 32-bit ceiling).
    • Float series → Scalar::Float(sum), accumulated in 64-bit Double. A NaN cell is a valid value, not missing, so it participates and propagates: any non-null NaN makes the sum NaN (Polars semantics; only Null is skipped).
    • Empty / all-null numeric series → Scalar::Int(0) or Scalar::Float(0.0) (additive identity). An all-NaN Float series sums to NaN, not the identity — every cell is a present value.
    • Non-numeric series (Bool, String) → raise TypeMismatch.

    Series::to_builtin

    fn Series::to_builtin(self : Series) -> Series

    Materialise this column onto the general-purpose Builtin backend (the inverse of to_numeric). Total and lossless: an all-valid Numeric column widens to a BuiltinColumn with an all-valid bitmap; a Builtin column is returned unchanged.

    Series::to_numeric

    Move this column onto the Numeric fast-path backend. The values are unchanged — only the backing representation. raise TypeMismatch for a non-numeric column and raise InvalidOperation for one carrying nulls (a NumericColumn has no validity bitmap to record them); an already-Numeric column is returned unchanged.

    Series::to_scalars

    Materialise every cell as a Scalar (Null for null cells), in order. Total — reads the backing array and validity mask once. Renderers (CSV / JSON / Markdown) use this to walk a column without a per-cell bounds-checked get.

    gather_series

    fn gather_series(s : Series, idx : Array[Int]) -> Series

    Total gather: position k of the result is s[idx[k]]. The caller is expected to pass indices in [0, s.len()); a stray index outside that range yields a null cell at its position — never a panic — the same on both storage backends, mirroring Bitmap::take_view's hardening (a caller that breaks the in-bounds contract still cannot abort). The result is canonical: a Numeric source rebuilds straight onto the Numeric fast path, and a Builtin source whose gathered rows leave it all-valid re-converges onto Numeric too (via rebuild_options), so the backend is a function of the gathered content, not the source — the invariant predicate pushdown relies on. Backs drop_nulls, take, and the row-gather DataFrame transforms.

    key_cell

    Normalise one key cell to its KeyCell. The Float arm delegates to float_key_cell (folding NaN / -0.0 so the key hashes / compares exactly as the previous Scalar::to_string key did); the five Scalar variants are exhaustive.

    preserve_backend

    fn preserve_backend(source : Series, rebuilt : Series) -> Series

    Re-converge a freshly rebuilt (Builtin-backed) column to source's backend: a Numeric source's all-valid rebuild moves back onto the Numeric fast path, a Builtin source's stays Builtin. The backend-preserving re-convergence, kept for the transforms that must hold their source backend rather than canonicalise — fill_null (whose filled column is built straight on Builtin). The row gathers (gather_series / Series::gather) and rebuild_options now canonicalise instead (an all-valid numeric result lands on Numeric whatever its source held), so a caller wrapping a rebuild_options result here — the join assembly — gets a no-op passthrough; the slices (slice_series) preserve the backend by sharing the validity bitmap (the row data is copied), never reaching here.

    rebuild_options

    fn rebuild_options(source : Series, name : String, n : Int, int_cell : (Array[Int64], Int) -> Int64?, float_cell : (Array[Double], Int) -> Double?, bool_cell : (Array[Bool], Int) -> Bool?, string_cell : (Array[String], Int) -> String?) -> Series

    Rebuild a column cell-by-cell through the option constructors, dispatching on source's storage variant exactly once. Output cell k (for k in 0 ..< n) is produced by the dtype-matching closure applied to source's typed data array — int_cell for an Int column, string_cell for a String one, and so on — each returning Some(v) for a value or None for a null slot.

    This is the single 4-arm match data() -> from_*_options skeleton behind gather_series' nullable path, gather_series_opt, and coalesce_into: the per-caller cell logic is all that differs between them, so it is all each caller supplies. The match stays exhaustive over the four dtypes — every arm is the live path for a column of that dtype, so none is dead.

    The rebuilt column is canonicalised (try_column_to_numeric): a row / cell selection that leaves an Int / Float column all-valid lands on the Numeric fast path, even when its source carried nulls those dropped rows held. This makes a column's backend a function of its content, not of how it was produced — the invariant the query optimizer relies on, so that sinking a Filter below a stage (recomputing a derived column over the surviving rows) cannot flip its backend from Builtin to Numeric and make collect diverge from the eager chain that Series equality observes.

    reducer_for

    Resolve a ReduceOp to its window reducer plus the ColumnData probe that fixes the output dtype: Count / NUnique are always Int, Mean / Std / Var / Median always Float, and Sum / Min / Max / First / Last keep the source dtype. Shared by the grouped (agg) and scoped (eval_agg) reductions so the op → reducer mapping lives in one place. Sum / Mean / Std / Var / Median raise TypeMismatch here for a non-numeric column, before any window work.

    scalars_to_series

    Project per-window reduction Scalars into a typed output column. probe fixes the output dtype, so an all-null result (every cell Null) still types correctly; each cell is projected "matching variant → Some, anything else (including Null) → None"; and an all-valid numeric result then converges onto the Numeric fast path (try_column_to_numeric, a no-op for a nullable, Bool, or String column, which keeps Builtin). This is the single column builder behind the grouped (agg) and scoped (eval_agg) reductions, so both agree on backend as well as on every cell value: the catch-all None arm is reached by the nullable reductions (mean / min / max / std / var / median over an empty / all-null window, and first / last over a null cell), so no arm is dead.

    slice_series

    fn slice_series(s : Series, start : Int, len : Int) -> Series

    Total contiguous slice [start, start + len). Delegates to ColumnStorage::slice_total, which keeps the source backend and shares the validity bitmap as a zero-copy view while copying the row data — the single slice path behind head / tail / DataFrame::slice (no rebuild, no Result). The caller guarantees 0 <= start and start + len <= self.len(); slice_total clamps anyway, so a stray bound can never abort.

    try_column_to_numeric

    fn try_column_to_numeric(s : Series) -> Series

    Best-effort, total move of one column onto the Numeric fast-path backend: an all-valid Int / Float Builtin column is rebuilt on NumericColumn; every other column — already Numeric, carrying nulls, or non-numeric — is returned unchanged. Unlike Series::to_numeric this never raises: it is the per-column step behind the total DataFrame::to_numeric, the canonicalisation in the row gathers (gather_series / Series::gather / rebuild_options) and preserve_backend, and the expression engine's computed-column convergence, so a column that cannot move is simply kept rather than failing (and rather than leaving a dead error arm, feedback_lib_no_abort). The null-free Int / Float arms rebuild through the NumericColumn constructors, which copy their input since the 0.5.2 immutable-ingestion change — one extra O(n) array copy per converged column (the column package's own ColumnStorage::to_numeric keeps its zero-copy move via direct struct construction).

    validity_bools

    fn validity_bools(storage :
    ColumnStorage
    ) -> Array[Bool]

    Materialise a column's validity as a dense Array[Bool] (true = valid) for a bounded scan. The Numeric arm builds the all-true array directly, skipping the synthetic all-valid Bitmap that ColumnStorage::validity() would allocate for a backend that has none — a Numeric column is present in every slot by construction. Equivalent to storage.validity().to_bools() but without the intermediate bitmap on the fast path. The row-level scanners (sort / group_by / join / drop_nulls) and the elementwise expression kernels (expr_eval, whose operands are frequently Numeric) read the mask by plain index, so they share this instead of each repacking a throwaway bitmap for a Numeric column.