mixle.data package¶
Data layer for mixle – a typed, structure-aware way to get records into the encoder contract.
The core abstraction is DataSource: a lazy, typed (Schema),
structured (SampleStructure) reference to data. It is purely additive –
seq_encode(list) and seq_encode(rdd) are unchanged; a DataSource is simply a third accepted
input that funnels into the same encoder contract. The DataFrame / graph / RDD adapters below remain
input/representation helpers (not probability distributions), so they live outside mixle.stats.
- exchangeability_check(data, *, alpha=0.01, n_perm=200, seed=0)[source]
Test whether row ORDER carries information (see module docstring). Small n -> exchangeable (no power).
alphais deliberately strict (0.01): the check should flag clear violations, not manufacture warnings from noise. Non-numeric-only data passes vacuously (order tests need a numeric surface).
- class ExchangeabilityReport(label, fields=<factory>)[source]
Bases:
objectThe verdict per numeric field, plus the aggregate label the preconditions record.
- label: str
- property exchangeable: bool
- class DataSource(*args, **kwargs)[source]
Bases:
ProtocolA lazy, typed, structured source of encoder-ready records.
- schema: Schema | None
- structure: SampleStructure
- records()[source]
Yield raw records compatible with an encoder’s input type.
- class MaterializedSource(data, structure=EXCHANGEABLE, schema=None)[source]
Bases:
objectAn in-memory
DataSourcewrapping aSequence– what a bare list becomes.- Parameters:
data (Sequence[Any])
structure (SampleStructure)
schema (Schema | None)
- materialize()[source]
Return the records as a list, coerced to the schema if one is set.
- partition(n, *, by=None)[source]
Split into
nstructure-safe sub-sources (group-aware for partially-exchangeable data).
- class LazySource(factory, structure=EXCHANGEABLE, schema=None, length=None)[source]
Bases:
objectA
DataSourcethat defers reading to a records factory and materializes on demand.Connectors (Parquet, SQL, CSV, …) return one of these so
open(...)does no I/O until the data is actually encoded; the records are read (and schema-coerced) once and cached.- Parameters:
factory (Any)
structure (SampleStructure)
schema (Schema | None)
length (int | None)
- as_source(data, structure=EXCHANGEABLE, schema=None)[source]
Coerce
datato aDataSource(pass a source through; wrap a sequence as materialized).- Parameters:
data (Any)
structure (SampleStructure)
schema (Schema | None)
- Return type:
DataSource
- open_source(kind, *args, **kwargs)
Open a
DataSourceby connector kind.Examples:
open("csv", path),open("parquet", path, columns=[...]),open("sql", url, query="select ..."). The connector module is imported lazily, and a missing driver raises a clearpip install mixle[extra]message.
- class Schema(fields)[source]
Bases:
objectAn ordered set of typed fields.
- Parameters:
fields (tuple[Field, ...])
- fields: tuple[Field, ...]
- conform_record(record)[source]
Coerce one record (a scalar for a 1-field schema, else a tuple/dict) to the schema’s types.
- conform(records)[source]
Coerce every record in
recordsto this schema (raising clear errors on mismatch).
- static for_model(model)[source]
Best-effort schema a model expects, from its
fields/sources+ child distributions.Formalizes the duck-probe in the DataFrame adapter: a record/composite model exposes
fieldsandsourcesplus child distributions whose support fixes each field’s logical type; a bare leaf yields a single field typed by its support (discrete -> Count, continuous -> Real, …).- Parameters:
model (Any)
- Return type:
Schema
- class Field(name, type)[source]
Bases:
objectA named, typed column.
- Parameters:
name (str)
type (FieldType)
- name: str
- type: FieldType
- class FieldType[source]
Bases:
objectBase logical type: a canonical NumPy dtype plus a coercion to the encoder-ready Python value.
- numpy_dtype
alias of
float64
- class Real[source]
Bases:
FieldTypeA real-valued scalar.
- numpy_dtype
alias of
float64
- class Count[source]
Bases:
FieldTypeA non-negative integer count.
- numpy_dtype
alias of
int64
- class Categorical(categories=None, numpy_dtype=<class 'numpy.object_'>)[source]
Bases:
FieldTypeA categorical label, optionally over a fixed set of
categories.- numpy_dtype
alias of
object_
- class Vector(dim=None, numpy_dtype=<class 'numpy.float64'>)[source]
Bases:
FieldTypeA fixed- or free-length real vector.
- numpy_dtype
alias of
float64
- class Timestamp[source]
Bases:
FieldTypeA point in time (datetime / numpy datetime64 / ISO string / POSIX seconds).
- numpy_dtype: Any = dtype('<M8[ns]')
- class Optional(inner=<factory>)[source]
Bases:
FieldTypeA value that may be missing (
Nonepasses through; otherwise the inner type coerces).- Parameters:
inner (FieldType)
- inner: FieldType
- property numpy_dtype: Any
Double-precision floating-point number type, compatible with Python
floatand Cdouble.- Character code:
'd'- Canonical name:
numpy.double
- Alias on this platform (Linux x86_64):
numpy.float64: 64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa.
- class Nested(schema, numpy_dtype=<class 'numpy.object_'>)[source]
Bases:
FieldTypeA sub-record with its own
Schema.- Parameters:
schema (Schema)
numpy_dtype (Any)
- schema: Schema
- numpy_dtype
alias of
object_
- class SampleStructure(kind, by=None)[source]
Bases:
objectThe joint structure of a dataset’s records (an exchangeability class).
- kind: str
- property strides_records: bool
True if records may be strided/shuffled across partitions (everything but grouped data).
- partially_exchangeable(by)[source]
Return a
PARTIALLY_EXCHANGEABLEstructure grouped by field name or key functionby.
- dataset_hash(data, *, sort=False, max_records=None)[source]
Hex SHA-256 fingerprint of
data(a sequence of records or aDataSource).sort=False(default) is order-sensitive (exact training sequence).sort=Truecombines per-record hashes commutatively for an order-insensitive fingerprint.max_recordstruncates (the count is mixed in, so a truncated hash never collides with a full one).
- model_hash(model)[source]
Hex SHA-256 fingerprint of a fitted model’s parameters (its serialized state).
Stable across processes: hashes the canonical form of
to_serializable(model), so the same model always yields the same hash and two models hash equal iff their serialized parameters match. Used to fingerprint a checkpoint and chain EM iteration lineage (seemixle.inference.production.provenance).
- check_dataset(model, data, *, sample=1000, check_support=True, raise_on_error=False)[source]
Validate
dataagainst the schema/supportmodelexpects (over the firstsamplerecords).Records both type-coercion failures (wrong shape/dtype for a field) and, when
check_supportis True, support violations (a value the model assigns probability 0 ->-inflog-density). Withraise_on_errorthe first batch of issues is raised as aValueError.
- class DataReport(ok: 'bool', n_checked: 'int', schema: 'list[tuple[str, str]]', issues: 'list[str]' = <factory>)[source]
Bases:
object- ok: bool
- n_checked: int
- save_encoded(encoded, path, *, encoder=None)[source]
Write
encoded(the output ofencoder.seq_encode(...)) topath; return its hex digest.encoder(optional) records the encoder class so a load against a different encoder is flagged.
- load_encoded(path, *, encoder=None)[source]
Load encoded data written by
save_encoded(), verifying its integrity digest.If
encoderis given, its class must match the one recorded at save time (elseValueError).
- class GraphDataEncoder(directed=False, fallback_assignments=None)[source]
Bases:
DataSequenceEncoderEncode graph observations as canonical adjacency/assignment objects.
- seq_encode(x)[source]
Encode the iid observation sequence x for vectorized evaluation.
- class GraphObservation(adjacency, block_assignments=None)[source]
Bases:
objectCanonical binary graph observation used by graph encoders.
- adjacency: ndarray
- dataframe_records(df, fields=None, as_dict=False)[source]
Convert DataFrame columns into observation records for
seq_encode.A single selected field becomes scalar observations. Multiple selected fields become tuple observations in the requested field order, matching the data shape expected by composite distributions. When
as_dict=True, each row is returned as a mapping keyed by the selected source field names.
- seq_encode_dataframe(df, fields=None, encoder=None, estimator=None, model=None, num_chunks=1, chunk_size=None)[source]
Sequence-encode selected DataFrame columns with the ordinary stats API.
- sample_rdd(sc, dist, count_per_split, num_splits, seed=None)[source]
- sample_seq_as_rdd(sc, dist, seq_len, count_per_split, num_splits, seed=None)[source]
- take_sample(rdd, with_replacement, n, seed=None)[source]
Subpackages¶
- mixle.data.sources package
- Submodules
- mixle.data.sources.arrow_source module
- mixle.data.sources.graph_source module
- mixle.data.sources.hadoop_source module
- mixle.data.sources.mongo_source module
- mixle.data.sources.pandas_source module
- mixle.data.sources.spark_source module
- mixle.data.sources.sql_source module
- mixle.data.sources.text_source module
- Submodules