ambers 0.3.9__tar.gz → 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {ambers-0.3.9 → ambers-0.4.0}/.github/workflows/ci.yml +9 -3
- {ambers-0.3.9 → ambers-0.4.0}/CHANGELOG.md +11 -0
- {ambers-0.3.9 → ambers-0.4.0}/Cargo.lock +1 -1
- {ambers-0.3.9 → ambers-0.4.0}/Cargo.toml +1 -1
- {ambers-0.3.9 → ambers-0.4.0}/PKG-INFO +68 -5
- {ambers-0.3.9 → ambers-0.4.0}/README.md +67 -4
- ambers-0.4.0/apply_labels.md +325 -0
- {ambers-0.3.9 → ambers-0.4.0}/pyproject.toml +1 -1
- ambers-0.4.0/python/ambers/__init__.py +17 -0
- {ambers-0.3.9 → ambers-0.4.0}/python/ambers/__init__.pyi +61 -1
- ambers-0.4.0/python/ambers/_containers.py +121 -0
- ambers-0.3.9/python/ambers/__init__.py → ambers-0.4.0/python/ambers/_io.py +4 -125
- ambers-0.4.0/python/ambers/_transforms.py +279 -0
- ambers-0.4.0/refactoring.md +28 -0
- ambers-0.4.0/src/python/conversions.rs +297 -0
- ambers-0.4.0/src/python/diff.rs +612 -0
- ambers-0.4.0/src/python/io.rs +302 -0
- ambers-0.4.0/src/python/metadata.rs +1144 -0
- ambers-0.4.0/src/python/mod.rs +32 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/conftest.py +4 -1
- ambers-0.4.0/tests/test_apply_labels.py +361 -0
- ambers-0.3.9/src/python/mod.rs +0 -2299
- {ambers-0.3.9 → ambers-0.4.0}/.cargo/config.toml +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/.github/workflows/release.yml +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/.gitignore +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/LICENSE +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/images/ambers-banner-v2.svg +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/images/ambers-banner.svg +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/metadata.md +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/arrow_convert.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/columnar.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/compression/bytecode.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/compression/bytecode_encoder.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/compression/mod.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/compression/zlib.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/constants.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/dictionary.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/document.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/encoding.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/error.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/header.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/info_records/encoding_record.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/info_records/float_info.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/info_records/integer_info.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/info_records/long_string_labels.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/info_records/long_string_missing.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/info_records/long_var_names.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/info_records/mod.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/info_records/mr_sets.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/info_records/var_attributes.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/info_records/var_display.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/info_records/very_long_strings.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/io_utils.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/lib.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/metadata.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/scanner.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/value_labels.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/variable.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/writer/data.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/writer/layout.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/writer/mod.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/writer/records.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/src/writer/tests.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/bench_read.py +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/bench_write.py +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/diag_zsav.py +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/test_long_strings.py +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/test_medium_write.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/test_metadata.py +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/test_metadata_api.py +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/test_paths.example.py +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/test_temporal.rs +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/test_wide_columns.py +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/test_write_roundtrip.py +0 -0
- {ambers-0.3.9 → ambers-0.4.0}/tests/test_writer_issues.py +0 -0
|
@@ -51,7 +51,13 @@ jobs:
|
|
|
51
51
|
- name: Build wheel
|
|
52
52
|
run: maturin build --release -o dist
|
|
53
53
|
|
|
54
|
-
- name: Install
|
|
54
|
+
- name: Install wheel
|
|
55
|
+
run: uv pip install --system dist/*.whl
|
|
56
|
+
|
|
57
|
+
- name: Smoke test
|
|
58
|
+
run: python -c "import ambers; print('ambers imported successfully')"
|
|
59
|
+
|
|
60
|
+
- name: Run Python tests (small/synthetic data only)
|
|
55
61
|
run: |
|
|
56
|
-
uv pip install --system
|
|
57
|
-
|
|
62
|
+
uv pip install --system pytest
|
|
63
|
+
pytest tests/test_apply_labels.py tests/test_metadata_api.py tests/test_writer_issues.py -v
|
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to ambers are documented in this file.
|
|
4
4
|
|
|
5
|
+
## [0.4.0] - 2026-04-07
|
|
6
|
+
|
|
7
|
+
- **Modularity refactor:** split `src/python/mod.rs` (2,299 LOC) into 5 focused submodules: `conversions.rs`, `metadata.rs`, `diff.rs`, `io.rs`, and thin `mod.rs`
|
|
8
|
+
- **Python package cleanup:** slim `__init__.py` (432 → 18 LOC) to thin re-exports; implementation moved to `_containers.py` and `_io.py`
|
|
9
|
+
- Add `apply_labels()` with three output modes: `"enum"` (default), `"string"`, `"enum_null"`
|
|
10
|
+
- Dtype-aware label application: Enum for numeric columns, pass-through for string columns
|
|
11
|
+
- Add 42 tests for `apply_labels`: output modes, dtype-aware behavior, error handling, LazyFrame
|
|
12
|
+
- Add Python pytest step to CI: apply_labels, metadata_api, writer_issues
|
|
13
|
+
- Fix CI: make test_paths import conditional in conftest.py
|
|
14
|
+
- No public API changes, no performance impact
|
|
15
|
+
|
|
5
16
|
## [0.3.9] - 2026-04-05
|
|
6
17
|
|
|
7
18
|
- Add `source`, `shape`, `file_size`, `read_time`, `compression` fields to `SavFile`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ambers
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Requires-Dist: polars>=1.3
|
|
5
5
|
License-File: LICENSE
|
|
6
6
|
Summary: Pure Rust SPSS .sav/.zsav reader with Polars DataFrame output
|
|
@@ -76,10 +76,73 @@ am.write_sav(df, "fast.zsav", meta=meta, compression_level=1) # fast zlib
|
|
|
76
76
|
|
|
77
77
|
# From scratch — metadata is optional, inferred from DataFrame schema
|
|
78
78
|
am.write_sav(df, "new.sav")
|
|
79
|
+
|
|
80
|
+
# Apply value labels — replace codes with labels for export/analysis
|
|
81
|
+
df, meta = sav.data, sav.meta
|
|
82
|
+
labeled = am.apply_labels(df, meta) # Enum dtype (ordered, strict)
|
|
83
|
+
labeled.write_excel("survey.xlsx") # Enum auto-casts to String
|
|
84
|
+
labeled = am.apply_labels(df, meta, output="string") # String dtype for export
|
|
85
|
+
labeled = am.apply_labels(df, meta, output="enum_null") # Enum, unmapped → null
|
|
79
86
|
```
|
|
80
87
|
|
|
81
88
|
`.sav` uses bytecode compression by default, `.zsav` uses zlib. Pass `compression=` to override (`"uncompressed"`, `"bytecode"`, `"zlib"`). Pass `meta=` to preserve all metadata from a prior `read_sav()`, or omit it to infer formats from the DataFrame.
|
|
82
89
|
|
|
90
|
+
### SavFile
|
|
91
|
+
|
|
92
|
+
`read_sav()` and `scan_sav()` return a `SavFile` object with file-level metadata alongside the data:
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
>>> sav = am.read_sav("survey_2025.sav")
|
|
96
|
+
>>> sav
|
|
97
|
+
┌─ SavFile ──────────────────────────┐
|
|
98
|
+
│ Data DataFrame (polars) │
|
|
99
|
+
│ Shape 22,070 rows x 677 cols │
|
|
100
|
+
│ Source survey_2025.sav │
|
|
101
|
+
│ File size 146.5 MB, bytecode │
|
|
102
|
+
│ Read time 0.286s │
|
|
103
|
+
└────────────────────────────────────┘
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
| Attribute | Type | Description |
|
|
107
|
+
|-----------|------|-------------|
|
|
108
|
+
| `sav.data` | `DataFrame` or `LazyFrame` | The data (eager from `read_sav`, lazy from `scan_sav`) |
|
|
109
|
+
| `sav.meta` | `SpssMetadata` | All variable metadata (labels, formats, value labels, etc.) |
|
|
110
|
+
| `sav.source` | `str \| None` | Source file path |
|
|
111
|
+
| `sav.shape` | `tuple[int, int] \| None` | `(n_rows, n_cols)` |
|
|
112
|
+
| `sav.file_size` | `int \| None` | File size in bytes |
|
|
113
|
+
| `sav.read_time` | `float \| None` | Wall-clock read time in seconds |
|
|
114
|
+
| `sav.compression` | `str` | `"uncompressed"`, `"bytecode"`, or `"zlib"` |
|
|
115
|
+
|
|
116
|
+
For `scan_sav()`, `read_time` measures metadata/schema reading only (not lazy collection).
|
|
117
|
+
|
|
118
|
+
### apply_labels
|
|
119
|
+
|
|
120
|
+
Replace numeric/string codes with their SPSS value labels. By default produces Polars `Enum` columns that preserve SPSS definition order — crucial for Likert scales and survey analysis.
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
sav = am.read_sav("survey.sav")
|
|
124
|
+
df, meta = sav.data, sav.meta
|
|
125
|
+
|
|
126
|
+
# Default: Enum output, strict validation
|
|
127
|
+
labeled = am.apply_labels(df, meta)
|
|
128
|
+
labeled.group_by("satisfaction").agg(pl.len()) # sorted by definition order
|
|
129
|
+
labeled.write_excel("survey.xlsx") # Enum auto-casts to String
|
|
130
|
+
|
|
131
|
+
# String output for quick export
|
|
132
|
+
labeled = am.apply_labels(df, meta, output="string")
|
|
133
|
+
|
|
134
|
+
# Enum output with unmapped values as null
|
|
135
|
+
labeled = am.apply_labels(df, meta, output="enum_null")
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
| `output=` | Dtype | Unmapped values | Best for |
|
|
139
|
+
|-----------|-------|-----------------|----------|
|
|
140
|
+
| `"enum"` (default) | `pl.Enum` (ordered) | Error | Analysis — strict, validated categories |
|
|
141
|
+
| `"string"` | `pl.String` | Stringify (`3.0` → `"3"`) | Export — readable text for Excel/CSV |
|
|
142
|
+
| `"enum_null"` | `pl.Enum` (ordered) | Null | Analysis — exclude unknowns from base |
|
|
143
|
+
|
|
144
|
+
Numeric columns without value labels are skipped. String columns always pass through unmapped text. See [apply_labels.md](apply_labels.md) for full documentation.
|
|
145
|
+
|
|
83
146
|
## Rust
|
|
84
147
|
|
|
85
148
|
```rust
|
|
@@ -251,11 +314,11 @@ On the 5.4 GB file, selecting 5 columns and 1000 rows completes in **13ms** —
|
|
|
251
314
|
|
|
252
315
|
## Roadmap
|
|
253
316
|
|
|
317
|
+
- `apply_missing_values()` — apply SPSS missing value definitions to DataFrames
|
|
318
|
+
- `meta.validate(df)` — validate metadata against a DataFrame
|
|
319
|
+
- Codebook export — generate variable documentation from metadata
|
|
254
320
|
- Continued I/O performance optimization
|
|
255
|
-
-
|
|
256
|
-
- Rich metadata manipulation — add, update, merge, and remove metadata programmatically
|
|
257
|
-
- Individual metadata field overrides in `write_sav()` — pass `variable_labels=`, `variable_value_labels=`, etc. alongside `meta=` to selectively override fields
|
|
258
|
-
- Currently supports read and write with Polars DataFrames (eager and lazy) — extending to pandas, Narwhals, DuckDB, and others
|
|
321
|
+
- Currently Polars-only — pandas/other DataFrame libraries may be added later
|
|
259
322
|
|
|
260
323
|
## License
|
|
261
324
|
|
|
@@ -66,10 +66,73 @@ am.write_sav(df, "fast.zsav", meta=meta, compression_level=1) # fast zlib
|
|
|
66
66
|
|
|
67
67
|
# From scratch — metadata is optional, inferred from DataFrame schema
|
|
68
68
|
am.write_sav(df, "new.sav")
|
|
69
|
+
|
|
70
|
+
# Apply value labels — replace codes with labels for export/analysis
|
|
71
|
+
df, meta = sav.data, sav.meta
|
|
72
|
+
labeled = am.apply_labels(df, meta) # Enum dtype (ordered, strict)
|
|
73
|
+
labeled.write_excel("survey.xlsx") # Enum auto-casts to String
|
|
74
|
+
labeled = am.apply_labels(df, meta, output="string") # String dtype for export
|
|
75
|
+
labeled = am.apply_labels(df, meta, output="enum_null") # Enum, unmapped → null
|
|
69
76
|
```
|
|
70
77
|
|
|
71
78
|
`.sav` uses bytecode compression by default, `.zsav` uses zlib. Pass `compression=` to override (`"uncompressed"`, `"bytecode"`, `"zlib"`). Pass `meta=` to preserve all metadata from a prior `read_sav()`, or omit it to infer formats from the DataFrame.
|
|
72
79
|
|
|
80
|
+
### SavFile
|
|
81
|
+
|
|
82
|
+
`read_sav()` and `scan_sav()` return a `SavFile` object with file-level metadata alongside the data:
|
|
83
|
+
|
|
84
|
+
```
|
|
85
|
+
>>> sav = am.read_sav("survey_2025.sav")
|
|
86
|
+
>>> sav
|
|
87
|
+
┌─ SavFile ──────────────────────────┐
|
|
88
|
+
│ Data DataFrame (polars) │
|
|
89
|
+
│ Shape 22,070 rows x 677 cols │
|
|
90
|
+
│ Source survey_2025.sav │
|
|
91
|
+
│ File size 146.5 MB, bytecode │
|
|
92
|
+
│ Read time 0.286s │
|
|
93
|
+
└────────────────────────────────────┘
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
| Attribute | Type | Description |
|
|
97
|
+
|-----------|------|-------------|
|
|
98
|
+
| `sav.data` | `DataFrame` or `LazyFrame` | The data (eager from `read_sav`, lazy from `scan_sav`) |
|
|
99
|
+
| `sav.meta` | `SpssMetadata` | All variable metadata (labels, formats, value labels, etc.) |
|
|
100
|
+
| `sav.source` | `str \| None` | Source file path |
|
|
101
|
+
| `sav.shape` | `tuple[int, int] \| None` | `(n_rows, n_cols)` |
|
|
102
|
+
| `sav.file_size` | `int \| None` | File size in bytes |
|
|
103
|
+
| `sav.read_time` | `float \| None` | Wall-clock read time in seconds |
|
|
104
|
+
| `sav.compression` | `str` | `"uncompressed"`, `"bytecode"`, or `"zlib"` |
|
|
105
|
+
|
|
106
|
+
For `scan_sav()`, `read_time` measures metadata/schema reading only (not lazy collection).
|
|
107
|
+
|
|
108
|
+
### apply_labels
|
|
109
|
+
|
|
110
|
+
Replace numeric/string codes with their SPSS value labels. By default produces Polars `Enum` columns that preserve SPSS definition order — crucial for Likert scales and survey analysis.
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
sav = am.read_sav("survey.sav")
|
|
114
|
+
df, meta = sav.data, sav.meta
|
|
115
|
+
|
|
116
|
+
# Default: Enum output, strict validation
|
|
117
|
+
labeled = am.apply_labels(df, meta)
|
|
118
|
+
labeled.group_by("satisfaction").agg(pl.len()) # sorted by definition order
|
|
119
|
+
labeled.write_excel("survey.xlsx") # Enum auto-casts to String
|
|
120
|
+
|
|
121
|
+
# String output for quick export
|
|
122
|
+
labeled = am.apply_labels(df, meta, output="string")
|
|
123
|
+
|
|
124
|
+
# Enum output with unmapped values as null
|
|
125
|
+
labeled = am.apply_labels(df, meta, output="enum_null")
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
| `output=` | Dtype | Unmapped values | Best for |
|
|
129
|
+
|-----------|-------|-----------------|----------|
|
|
130
|
+
| `"enum"` (default) | `pl.Enum` (ordered) | Error | Analysis — strict, validated categories |
|
|
131
|
+
| `"string"` | `pl.String` | Stringify (`3.0` → `"3"`) | Export — readable text for Excel/CSV |
|
|
132
|
+
| `"enum_null"` | `pl.Enum` (ordered) | Null | Analysis — exclude unknowns from base |
|
|
133
|
+
|
|
134
|
+
Numeric columns without value labels are skipped. String columns always pass through unmapped text. See [apply_labels.md](apply_labels.md) for full documentation.
|
|
135
|
+
|
|
73
136
|
## Rust
|
|
74
137
|
|
|
75
138
|
```rust
|
|
@@ -241,11 +304,11 @@ On the 5.4 GB file, selecting 5 columns and 1000 rows completes in **13ms** —
|
|
|
241
304
|
|
|
242
305
|
## Roadmap
|
|
243
306
|
|
|
307
|
+
- `apply_missing_values()` — apply SPSS missing value definitions to DataFrames
|
|
308
|
+
- `meta.validate(df)` — validate metadata against a DataFrame
|
|
309
|
+
- Codebook export — generate variable documentation from metadata
|
|
244
310
|
- Continued I/O performance optimization
|
|
245
|
-
-
|
|
246
|
-
- Rich metadata manipulation — add, update, merge, and remove metadata programmatically
|
|
247
|
-
- Individual metadata field overrides in `write_sav()` — pass `variable_labels=`, `variable_value_labels=`, etc. alongside `meta=` to selectively override fields
|
|
248
|
-
- Currently supports read and write with Polars DataFrames (eager and lazy) — extending to pandas, Narwhals, DuckDB, and others
|
|
311
|
+
- Currently Polars-only — pandas/other DataFrame libraries may be added later
|
|
249
312
|
|
|
250
313
|
## License
|
|
251
314
|
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
# apply_labels
|
|
2
|
+
|
|
3
|
+
Replace SPSS numeric/string codes with their metadata value labels.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
import ambers as am
|
|
7
|
+
|
|
8
|
+
sav = am.read_sav("survey.sav")
|
|
9
|
+
df, meta = sav.data, sav.meta
|
|
10
|
+
labeled = am.apply_labels(df, meta)
|
|
11
|
+
labeled.write_excel("survey.xlsx")
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Why Enum is the default
|
|
15
|
+
|
|
16
|
+
SPSS categorical variables have an inherent ordering defined by their value codes (1, 2, 3...). When you apply value labels, that ordering carries semantic meaning — especially for Likert scales:
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
1 = "Strongly disagree"
|
|
20
|
+
2 = "Disagree"
|
|
21
|
+
3 = "Neutral"
|
|
22
|
+
4 = "Agree"
|
|
23
|
+
5 = "Strongly agree"
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Polars `Enum` preserves this definition order. Sort, group_by, and value_counts all follow the original SPSS code order, not alphabetical order. This is critical for survey analysis where "Strongly disagree" should come before "Disagree", not after.
|
|
27
|
+
|
|
28
|
+
| Feature | `pl.String` | `pl.Enum` |
|
|
29
|
+
|---------|-------------|-----------|
|
|
30
|
+
| Sort order | Alphabetical | Definition order (SPSS key order) |
|
|
31
|
+
| Memory | Full string per row | Integer index (u8) |
|
|
32
|
+
| Validation | Accepts any string | Rejects undefined values |
|
|
33
|
+
| group_by/filter | String comparison | Integer comparison (faster) |
|
|
34
|
+
| Excel/CSV export | As-is | Auto-casts to String |
|
|
35
|
+
|
|
36
|
+
`Enum` is the best of both worlds: ordered and validated for analysis, readable text for export.
|
|
37
|
+
|
|
38
|
+
## Design philosophy
|
|
39
|
+
|
|
40
|
+
ambers is a Rust-powered library, and its API reflects a core Rust principle: **"Make illegal states unrepresentable."** In Rust, the compiler refuses to build code with unhandled cases. In ambers, `apply_labels` refuses to produce data with unhandled values.
|
|
41
|
+
|
|
42
|
+
The three output modes map directly to Rust's error handling patterns:
|
|
43
|
+
|
|
44
|
+
| `output=` | Rust equivalent | Philosophy |
|
|
45
|
+
|-----------|-----------------|------------|
|
|
46
|
+
| `"enum"` | `unwrap()` | **Fail fast.** Data must be complete — every value needs a label. If not, stop and fix the metadata before analysis. |
|
|
47
|
+
| `"enum_null"` | `Option<T>` | **Acknowledge incompleteness.** Some values may lack labels — express this explicitly as `null` rather than hiding it. |
|
|
48
|
+
| `"string"` | `format!("{:?}")` | **Escape hatch.** Trade type safety for convenience when you just need readable text for export. |
|
|
49
|
+
|
|
50
|
+
Traditional workflows (pandas + `map()`) silently turn unmapped values into `NaN` — a data quality bug that may go unnoticed for months. ambers defaults to `output="enum"` because catching metadata gaps at load time is always cheaper than debugging silent corruption downstream.
|
|
51
|
+
|
|
52
|
+
This is **type-safe data engineering**: the same discipline that makes Rust code reliable, applied to survey data pipelines.
|
|
53
|
+
|
|
54
|
+
### Why labeling is separate from reading
|
|
55
|
+
|
|
56
|
+
Some libraries (e.g., pyreadstat's `apply_value_formats=True`) apply labels at read time. If something goes wrong — incomplete labels, unmapped codes — you may get silent `NaN` values or an error with no way to inspect or fix the data.
|
|
57
|
+
|
|
58
|
+
ambers separates reading from labeling into a **read → inspect → fix → label** workflow:
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
sav = am.read_sav("survey.sav")
|
|
62
|
+
df, meta = sav.data, sav.meta
|
|
63
|
+
|
|
64
|
+
# 1. Inspect: see raw data + metadata before any transformation
|
|
65
|
+
meta.describe("S2")
|
|
66
|
+
meta.value("S2") # {1.0: "Male", 2.0: "Female"} — missing 3, 4?
|
|
67
|
+
df.select(pl.col("S2").unique()) # [1.0, 2.0, 3.0, 4.0]
|
|
68
|
+
|
|
69
|
+
# 2. Fix: patch metadata with immutable .with_*() methods
|
|
70
|
+
meta2 = meta.with_variable_value_labels({
|
|
71
|
+
"S2": {3: "Another gender", 4: "Rather not say"}
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
# 3. Label: apply only when ready
|
|
75
|
+
labeled = am.apply_labels(df, meta2)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Each step can be inspected and corrected independently. You always have access to both the raw data and the metadata — nothing is lost or transformed prematurely.
|
|
79
|
+
|
|
80
|
+
## Signature
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
def apply_labels(
|
|
84
|
+
df: DataFrame | LazyFrame,
|
|
85
|
+
meta: SpssMetadata,
|
|
86
|
+
*,
|
|
87
|
+
columns: list[str] | None = None,
|
|
88
|
+
output: Literal["enum", "string", "enum_null"] = "enum",
|
|
89
|
+
) -> DataFrame | LazyFrame
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Parameters
|
|
93
|
+
|
|
94
|
+
### `df`
|
|
95
|
+
|
|
96
|
+
A Polars DataFrame or LazyFrame with raw SPSS codes. Always unpack from a SavFile first:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
sav = am.read_sav("survey.sav")
|
|
100
|
+
df, meta = sav.data, sav.meta
|
|
101
|
+
|
|
102
|
+
labeled = am.apply_labels(df, meta)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### `meta`
|
|
106
|
+
|
|
107
|
+
An `SpssMetadata` object containing value labels. Get it from `sav.meta`.
|
|
108
|
+
|
|
109
|
+
### `columns`
|
|
110
|
+
|
|
111
|
+
Which columns to apply labels to. Default `None` applies to all columns that have value labels in the metadata AND exist in the data.
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
# All columns with value labels
|
|
115
|
+
am.apply_labels(df, meta)
|
|
116
|
+
|
|
117
|
+
# Specific columns only
|
|
118
|
+
am.apply_labels(df, meta, columns=["gender", "satisfaction"])
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
When specified explicitly, raises `ValueError` if:
|
|
122
|
+
- A column doesn't exist in the data
|
|
123
|
+
- A column has no value labels (or an empty label dict) in the metadata
|
|
124
|
+
|
|
125
|
+
### `output`
|
|
126
|
+
|
|
127
|
+
Controls both the output dtype and how unmapped values are handled. One parameter, three clear modes:
|
|
128
|
+
|
|
129
|
+
| `output=` | Dtype | Unmapped values | Best for |
|
|
130
|
+
|-----------|-------|-----------------|----------|
|
|
131
|
+
| `"enum"` (default) | `pl.Enum` (ordered) | **Error** — raises with diagnostic | Analysis with strict validation |
|
|
132
|
+
| `"string"` | `pl.String` | **Stringify** — `3.0` → `"3"` | Excel/CSV export |
|
|
133
|
+
| `"enum_null"` | `pl.Enum` (ordered) | **Null** — unmapped become null | Analysis, exclude unknowns from base |
|
|
134
|
+
|
|
135
|
+
**Note:** The `output` mode only affects **numeric columns**. String columns always pass through unmapped text and produce `pl.String` — see [Dtype-aware behavior](#dtype-aware-behavior) below.
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
sav = am.read_sav("survey.sav")
|
|
139
|
+
df, meta = sav.data, sav.meta
|
|
140
|
+
|
|
141
|
+
# output="enum" — strict, raises if any value has no label
|
|
142
|
+
labeled = am.apply_labels(df, meta)
|
|
143
|
+
labeled = am.apply_labels(df, meta, output="enum") # same as default
|
|
144
|
+
|
|
145
|
+
# output="string" — tolerant, unmapped values become strings
|
|
146
|
+
labeled = am.apply_labels(df, meta, output="string")
|
|
147
|
+
|
|
148
|
+
# output="enum_null" — ordered categories, unknowns become null
|
|
149
|
+
labeled = am.apply_labels(df, meta, output="enum_null")
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
#### When to use each mode
|
|
153
|
+
|
|
154
|
+
**`output="enum"` (default)** — Use when you want validated, ordered categories for analysis. If your metadata is incomplete (e.g., value `99` exists in data but has no label), you'll get a clear error telling you exactly which columns and values are missing labels. Fix the metadata, then retry.
|
|
155
|
+
|
|
156
|
+
**`output="string"`** — Use when exporting to Excel or CSV. All values become readable text. Unmapped numeric codes become their string representation (`99.0` → `"99"`). No ordering, no validation — just text.
|
|
157
|
+
|
|
158
|
+
**`output="enum_null"`** — Use when you want ordered categories but some values intentionally lack labels (e.g., "other" responses coded as `99`). Unmapped values become null and are excluded from group_by, value_counts, etc. This keeps your analysis base clean.
|
|
159
|
+
|
|
160
|
+
## Dtype-aware behavior
|
|
161
|
+
|
|
162
|
+
SPSS files contain both numeric and string columns, each with different labeling semantics:
|
|
163
|
+
|
|
164
|
+
| Column type | Has labels? | Behavior |
|
|
165
|
+
|---|---|---|
|
|
166
|
+
| **Float64** | Yes | **Categorical variable.** Apply labels. `output` mode controls dtype and unmapped handling. |
|
|
167
|
+
| **Float64** | No | **Numeric/continuous** (age, income). Skipped entirely. |
|
|
168
|
+
| **String** | Yes | **Partial labeling.** Common for open-ended fields with special codes ("RF" → "Refused", "DK" → "Don't Know"). Labeled values are replaced; unlabeled text passes through unchanged. Always `pl.String` — never Enum. |
|
|
169
|
+
| **String** | No | Skipped. |
|
|
170
|
+
|
|
171
|
+
### Why string columns always pass through
|
|
172
|
+
|
|
173
|
+
SPSS string columns with value labels are typically open-ended text fields where only specific codes have labels:
|
|
174
|
+
|
|
175
|
+
```
|
|
176
|
+
Value labels for "Q5_other":
|
|
177
|
+
"RF" → "Refused"
|
|
178
|
+
"DK" → "Don't Know"
|
|
179
|
+
|
|
180
|
+
Actual data:
|
|
181
|
+
"I like the product" → passes through (legitimate response)
|
|
182
|
+
"RF" → becomes "Refused"
|
|
183
|
+
"Too expensive" → passes through
|
|
184
|
+
"DK" → becomes "Don't Know"
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Erroring on unlabeled text would break legitimate open-ended responses. The `output` mode intentionally does not affect string columns.
|
|
188
|
+
|
|
189
|
+
## Return type
|
|
190
|
+
|
|
191
|
+
Returns the same type as input:
|
|
192
|
+
|
|
193
|
+
| Input | Output |
|
|
194
|
+
|-------|--------|
|
|
195
|
+
| `DataFrame` | `DataFrame` |
|
|
196
|
+
| `LazyFrame` | `LazyFrame` |
|
|
197
|
+
|
|
198
|
+
## Error messages
|
|
199
|
+
|
|
200
|
+
When `output="enum"` and unmapped values are found, `apply_labels` raises a structured `ValueError` with diagnostics:
|
|
201
|
+
|
|
202
|
+
```
|
|
203
|
+
apply_labels: 2 columns have values without labels (output='enum')
|
|
204
|
+
|
|
205
|
+
S2: 1 unmapped value: [4.0] (4 unique, 3 labeled)
|
|
206
|
+
Q5: 2 unmapped values: [98.0, 99.0] (10 unique, 8 labeled)
|
|
207
|
+
|
|
208
|
+
To fix, either:
|
|
209
|
+
- Add missing labels: meta = meta.with_variable_value_labels({...})
|
|
210
|
+
- Use output="enum_null" to set unmapped values to null
|
|
211
|
+
- Use output="string" to keep unmapped as strings
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
When Enum output modes detect duplicate label values (multiple codes mapping to the same label):
|
|
215
|
+
|
|
216
|
+
```
|
|
217
|
+
apply_labels: 1 column has duplicate label values (multiple codes -> same label)
|
|
218
|
+
|
|
219
|
+
POL_23: 3 duplicate labels: [2.0, 36.0] -> 'Socialist Party'; [3.0, 37.0] -> "People's Party"; [4.0, 38.0] -> 'Democratic Party'
|
|
220
|
+
|
|
221
|
+
With Enum output, duplicate labels collapse distinct codes into the same category.
|
|
222
|
+
If intentional, this is fine. If not, fix the labels in metadata.
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Both diagnostics can appear together in a single error if both issues exist.
|
|
226
|
+
|
|
227
|
+
## Examples
|
|
228
|
+
|
|
229
|
+
### Survey analysis workflow (default)
|
|
230
|
+
|
|
231
|
+
```python
|
|
232
|
+
sav = am.read_sav("survey.sav")
|
|
233
|
+
df, meta = sav.data, sav.meta
|
|
234
|
+
labeled = am.apply_labels(df, meta)
|
|
235
|
+
|
|
236
|
+
# Enum columns sort by definition order
|
|
237
|
+
labeled.select("satisfaction").unique().sort("satisfaction")
|
|
238
|
+
# → "Very Dissatisfied", "Dissatisfied", "Neutral", "Satisfied", "Very Satisfied"
|
|
239
|
+
# NOT alphabetical!
|
|
240
|
+
|
|
241
|
+
# Group by works naturally
|
|
242
|
+
labeled.group_by("gender").agg(pl.col("score").mean())
|
|
243
|
+
|
|
244
|
+
# Export — Enum auto-casts to String
|
|
245
|
+
labeled.write_excel("survey.xlsx")
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### Quick export (String output)
|
|
249
|
+
|
|
250
|
+
```python
|
|
251
|
+
sav = am.read_sav("survey.sav")
|
|
252
|
+
df, meta = sav.data, sav.meta
|
|
253
|
+
labeled = am.apply_labels(df, meta, output="string")
|
|
254
|
+
labeled.write_csv("survey.csv")
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
### Exclude unknowns from analysis base
|
|
258
|
+
|
|
259
|
+
```python
|
|
260
|
+
sav = am.read_sav("survey.sav")
|
|
261
|
+
df, meta = sav.data, sav.meta
|
|
262
|
+
labeled = am.apply_labels(df, meta, output="enum_null")
|
|
263
|
+
|
|
264
|
+
# Unmapped values (e.g., 99="other") are null — excluded from counts
|
|
265
|
+
labeled.group_by("Q1").agg(pl.len())
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### Data quality check
|
|
269
|
+
|
|
270
|
+
```python
|
|
271
|
+
sav = am.read_sav("survey.sav")
|
|
272
|
+
df, meta = sav.data, sav.meta
|
|
273
|
+
try:
|
|
274
|
+
am.apply_labels(df, meta) # output="enum" by default
|
|
275
|
+
except ValueError as e:
|
|
276
|
+
print(e)
|
|
277
|
+
# Shows exactly which columns and values need labels
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
### After filtering
|
|
281
|
+
|
|
282
|
+
```python
|
|
283
|
+
sav = am.read_sav("survey.sav")
|
|
284
|
+
df, meta = sav.data, sav.meta
|
|
285
|
+
filtered = df.filter(pl.col("age") > 30)
|
|
286
|
+
labeled = am.apply_labels(filtered, meta)
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
### Lazy pipeline
|
|
290
|
+
|
|
291
|
+
```python
|
|
292
|
+
sav = am.scan_sav("big_survey.sav")
|
|
293
|
+
df, meta = sav.data, sav.meta
|
|
294
|
+
labeled = am.apply_labels(df, meta, output="enum_null")
|
|
295
|
+
result = labeled.select(["gender", "satisfaction"]).collect()
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
### Selective columns
|
|
299
|
+
|
|
300
|
+
```python
|
|
301
|
+
sav = am.read_sav("survey.sav")
|
|
302
|
+
df, meta = sav.data, sav.meta
|
|
303
|
+
labeled = am.apply_labels(df, meta, columns=["gender", "satisfaction"])
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
## Performance
|
|
307
|
+
|
|
308
|
+
`apply_labels` builds one Polars expression per column and executes them all in a single `with_columns()` call. Polars runs all expressions in parallel in Rust.
|
|
309
|
+
|
|
310
|
+
Compared to pyreadstat's `set_value_labels()`:
|
|
311
|
+
- **No per-column unique value iteration** — pyreadstat iterates all unique values per column to fill in unmapped entries
|
|
312
|
+
- **No deepcopy** — pyreadstat deep-copies the entire label dict per column
|
|
313
|
+
- **Single batched call** — pyreadstat calls `with_columns()` once per column in a loop
|
|
314
|
+
- **Enum support** — pyreadstat uses `Categorical` (unordered); ambers uses `Enum` (ordered)
|
|
315
|
+
|
|
316
|
+
## Edge cases
|
|
317
|
+
|
|
318
|
+
| Scenario | Behavior |
|
|
319
|
+
|----------|----------|
|
|
320
|
+
| Column has empty label dict `{}` | Skipped (no labels to apply) |
|
|
321
|
+
| All values in column are null | Null stays null (no error even with `output="enum"`) |
|
|
322
|
+
| Duplicate label values (`{1: "Yes", 2: "Yes"}`) | Deduplicated preserving order → `Enum(["Yes"])`. Diagnostic raised for Enum modes. |
|
|
323
|
+
| Label value is empty string (`{99: ""}`) | Treated as a valid label (empty string) |
|
|
324
|
+
| Float precision (`3.0000001`) | Matched against label keys as-is; may not match `3.0` |
|
|
325
|
+
| Integer-valued floats with `output="string"` | `3.0` → `"3"`, `2.5` → `"2.5"` |
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""ambers: Pure Rust SPSS .sav/.zsav reader and writer."""
|
|
2
|
+
|
|
3
|
+
from ambers._ambers import MetaDiff, SpssMetadata
|
|
4
|
+
from ambers._containers import SavFile
|
|
5
|
+
from ambers._io import read_sav, read_sav_meta, scan_sav, write_sav
|
|
6
|
+
from ambers._transforms import apply_labels
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"SavFile",
|
|
10
|
+
"apply_labels",
|
|
11
|
+
"read_sav",
|
|
12
|
+
"read_sav_meta",
|
|
13
|
+
"scan_sav",
|
|
14
|
+
"write_sav",
|
|
15
|
+
"SpssMetadata",
|
|
16
|
+
"MetaDiff",
|
|
17
|
+
]
|
|
@@ -2,7 +2,7 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
from dataclasses import dataclass
|
|
4
4
|
from pathlib import Path
|
|
5
|
-
from typing import Generic, TypeVar
|
|
5
|
+
from typing import Generic, TypeVar, overload
|
|
6
6
|
|
|
7
7
|
import polars
|
|
8
8
|
|
|
@@ -748,3 +748,63 @@ def write_sav(
|
|
|
748
748
|
>>> am.write_sav(df, "raw.sav", meta=meta, compression="uncompressed")
|
|
749
749
|
"""
|
|
750
750
|
...
|
|
751
|
+
|
|
752
|
+
@overload
|
|
753
|
+
def apply_labels(
|
|
754
|
+
df: polars.DataFrame,
|
|
755
|
+
meta: SpssMetadata,
|
|
756
|
+
*,
|
|
757
|
+
columns: list[str] | None = ...,
|
|
758
|
+
output: str = ...,
|
|
759
|
+
) -> polars.DataFrame: ...
|
|
760
|
+
@overload
|
|
761
|
+
def apply_labels(
|
|
762
|
+
df: polars.LazyFrame,
|
|
763
|
+
meta: SpssMetadata,
|
|
764
|
+
*,
|
|
765
|
+
columns: list[str] | None = ...,
|
|
766
|
+
output: str = ...,
|
|
767
|
+
) -> polars.LazyFrame: ...
|
|
768
|
+
def apply_labels(
|
|
769
|
+
df: polars.DataFrame | polars.LazyFrame,
|
|
770
|
+
meta: SpssMetadata,
|
|
771
|
+
*,
|
|
772
|
+
columns: list[str] | None = None,
|
|
773
|
+
output: str = "enum",
|
|
774
|
+
) -> polars.DataFrame | polars.LazyFrame:
|
|
775
|
+
"""Replace numeric/string codes with value labels from SPSS metadata.
|
|
776
|
+
|
|
777
|
+
Converts categorical columns from raw codes to their string labels.
|
|
778
|
+
By default produces ``pl.Enum`` columns preserving SPSS label ordering.
|
|
779
|
+
|
|
780
|
+
Parameters
|
|
781
|
+
----------
|
|
782
|
+
df
|
|
783
|
+
A Polars DataFrame or LazyFrame with raw SPSS codes.
|
|
784
|
+
meta
|
|
785
|
+
SpssMetadata with value labels.
|
|
786
|
+
columns
|
|
787
|
+
Columns to apply labels to. None applies to all columns with
|
|
788
|
+
value labels in the metadata.
|
|
789
|
+
output
|
|
790
|
+
Output mode for labeled numeric columns.
|
|
791
|
+
|
|
792
|
+
- ``"enum"`` (default) — ``pl.Enum`` with ordered categories.
|
|
793
|
+
Raises if any non-null value has no label.
|
|
794
|
+
- ``"string"`` — ``pl.String``. Unmapped values become their
|
|
795
|
+
string representation.
|
|
796
|
+
- ``"enum_null"`` — ``pl.Enum`` with ordered categories.
|
|
797
|
+
Unmapped values become null.
|
|
798
|
+
|
|
799
|
+
Returns
|
|
800
|
+
-------
|
|
801
|
+
polars.DataFrame | polars.LazyFrame
|
|
802
|
+
|
|
803
|
+
Examples
|
|
804
|
+
--------
|
|
805
|
+
>>> sav = am.read_sav("survey.sav")
|
|
806
|
+
>>> df, meta = sav.data, sav.meta
|
|
807
|
+
>>> labeled = am.apply_labels(df, meta)
|
|
808
|
+
>>> labeled.write_excel("survey.xlsx")
|
|
809
|
+
"""
|
|
810
|
+
...
|