ambers 0.4.4__tar.gz → 0.4.6__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.4.4 → ambers-0.4.6}/.github/workflows/ci.yml +1 -1
- {ambers-0.4.4 → ambers-0.4.6}/CHANGELOG.md +19 -0
- {ambers-0.4.4 → ambers-0.4.6}/Cargo.lock +1 -1
- {ambers-0.4.4 → ambers-0.4.6}/Cargo.toml +1 -1
- {ambers-0.4.4 → ambers-0.4.6}/PKG-INFO +34 -1
- {ambers-0.4.4 → ambers-0.4.6}/README.md +33 -0
- {ambers-0.4.4 → ambers-0.4.6}/pyproject.toml +1 -1
- {ambers-0.4.4 → ambers-0.4.6}/python/ambers/__init__.py +2 -0
- {ambers-0.4.4 → ambers-0.4.6}/python/ambers/__init__.pyi +23 -2
- {ambers-0.4.4 → ambers-0.4.6}/python/ambers/_containers.py +11 -1
- {ambers-0.4.4 → ambers-0.4.6}/python/ambers/_io.py +9 -1
- ambers-0.4.6/python/ambers/_warnings.py +44 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/columnar.rs +84 -22
- {ambers-0.4.4 → ambers-0.4.6}/src/compression/bytecode.rs +84 -14
- {ambers-0.4.4 → ambers-0.4.6}/src/compression/zlib.rs +1 -1
- {ambers-0.4.4 → ambers-0.4.6}/src/dictionary.rs +140 -34
- {ambers-0.4.4 → ambers-0.4.6}/src/document.rs +1 -1
- {ambers-0.4.4 → ambers-0.4.6}/src/error.rs +6 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/header.rs +5 -5
- {ambers-0.4.4 → ambers-0.4.6}/src/info_records/long_string_labels.rs +5 -6
- {ambers-0.4.4 → ambers-0.4.6}/src/info_records/long_string_missing.rs +5 -6
- ambers-0.4.6/src/info_records/long_var_names.rs +53 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/info_records/mod.rs +2 -2
- {ambers-0.4.4 → ambers-0.4.6}/src/info_records/mr_sets.rs +120 -75
- {ambers-0.4.4 → ambers-0.4.6}/src/info_records/var_attributes.rs +49 -33
- {ambers-0.4.4 → ambers-0.4.6}/src/info_records/var_display.rs +1 -1
- ambers-0.4.6/src/info_records/very_long_strings.rs +45 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/io_utils.rs +32 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/lib.rs +4 -2
- {ambers-0.4.4 → ambers-0.4.6}/src/metadata.rs +17 -2
- {ambers-0.4.4 → ambers-0.4.6}/src/python/io.rs +2 -1
- {ambers-0.4.4 → ambers-0.4.6}/src/python/metadata.rs +16 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/scanner.rs +86 -12
- {ambers-0.4.4 → ambers-0.4.6}/src/value_labels.rs +2 -2
- {ambers-0.4.4 → ambers-0.4.6}/src/variable.rs +49 -21
- ambers-0.4.6/tests/test_encoding.py +64 -0
- ambers-0.4.6/tests/test_encoding.rs +278 -0
- ambers-0.4.6/tests/test_malformed.py +118 -0
- ambers-0.4.6/tests/test_malformed.rs +658 -0
- ambers-0.4.6/tests/test_warnings.py +227 -0
- ambers-0.4.6/warnings_and_errors.md +108 -0
- ambers-0.4.4/src/info_records/long_var_names.rs +0 -39
- ambers-0.4.4/src/info_records/very_long_strings.rs +0 -41
- {ambers-0.4.4 → ambers-0.4.6}/.cargo/config.toml +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/.github/workflows/release.yml +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/.gitignore +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/LICENSE +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/apply_labels.md +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/images/ambers-banner-v2.svg +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/images/ambers-banner.svg +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/metadata.md +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/python/ambers/_missing.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/python/ambers/_transforms.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/python/ambers/_validate.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/python/ambers/codebook/__init__.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/python/ambers/codebook/_engine.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/python/ambers/codebook/_types.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/arrow_convert.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/compression/bytecode_encoder.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/compression/mod.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/constants.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/encoding.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/info_records/encoding_record.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/info_records/float_info.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/info_records/integer_info.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/python/conversions.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/python/diff.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/python/mod.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/writer/data.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/writer/layout.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/writer/mod.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/writer/records.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/src/writer/tests.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/bench_read.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/bench_write.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/conftest.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/diag_zsav.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_apply_labels.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_apply_missing.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_codebook.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_codebook_engine.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_codebook_types.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_long_strings.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_medium_write.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_metadata.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_metadata_api.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_paths.example.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_polars_compat.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_temporal.rs +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_validate.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_wide_columns.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_write_roundtrip.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/tests/test_writer_issues.py +0 -0
- {ambers-0.4.4 → ambers-0.4.6}/validate.md +0 -0
|
@@ -60,4 +60,4 @@ jobs:
|
|
|
60
60
|
- name: Run Python tests (small/synthetic data only)
|
|
61
61
|
run: |
|
|
62
62
|
uv pip install --system pytest
|
|
63
|
-
pytest tests/test_apply_labels.py tests/test_apply_missing.py tests/test_validate.py tests/test_metadata_api.py tests/test_writer_issues.py tests/test_polars_compat.py -v -k "not RealFile"
|
|
63
|
+
pytest tests/test_apply_labels.py tests/test_apply_missing.py tests/test_validate.py tests/test_metadata_api.py tests/test_writer_issues.py tests/test_polars_compat.py tests/test_malformed.py tests/test_warnings.py tests/test_encoding.py -v -k "not RealFile"
|
|
@@ -2,6 +2,25 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to ambers are documented in this file.
|
|
4
4
|
|
|
5
|
+
## [0.4.6] - 2026-10-07
|
|
6
|
+
|
|
7
|
+
- Fix GitHub issue #5: on code-page encoded files (windows-1250 and every other mapped code page) variable names, long names, MR-set names/labels/counted values, variable attributes, long-string record names and the file label were decoded as UTF-8 before the file's encoding was known, turning accented characters into U+FFFD and truncating or panicking in the MR-set parser. All dictionary text now stays raw bytes until `resolve_dictionary` decodes it once with the file encoding. Fixes a related false "duplicate variable name" error for names differing only by an accented letter. UTF-8 files and data columns are unchanged
|
|
8
|
+
|
|
9
|
+
## [0.4.5] - 2026-10-07
|
|
10
|
+
|
|
11
|
+
- Add `warnings_and_errors.md`, a catalogue of every reader warning finding and error message with meaning and remedy, and a "Warnings and Errors" section at the end of the README
|
|
12
|
+
|
|
13
|
+
- Fix GitHub issue #4: a variable record whose type field is not 0, 1-255 or -1 is rejected (`InvalidVariable`); a garbage width of hundreds of millions made every row walk millions of string segments (seconds for a 4 KB file, now milliseconds). Negative values other than -1 are tolerated as continuation slots with a finding, since SPSS opens such files
|
|
14
|
+
- Fix GitHub issue #3: sizes declared by the file are checked before allocating. `read_bytes` refuses requests larger than the file, a variable may declare at most 3 missing values, buffer capacities are capped by the bytes actually present, and cold reservations are capped. Fuzzer files that requested 1-7 GB now fail or read in milliseconds without touching memory
|
|
15
|
+
- Date/time values outside years 1-9999 (or non-finite) are set to null and reported as a finding instead of being stored as saturated values that made Polars panic on display
|
|
16
|
+
- **Behaviour change (issue #1 follow-up):** a header row width that disagrees with the variable list is now a finding instead of an error, matching SPSS which ignores that field; the variable list is used. Duplicate variable names are now rejected with `InvalidDictionary` (SPSS rejects them too)
|
|
17
|
+
- Very-long-string declarations with an impossible width or more segments than variables remain are ignored with a finding
|
|
18
|
+
- Add file-damage warnings: when a file's header disagrees with its contents (declared row count vs rows read, compression bias other than 100, missing row width), `read_sav`/`scan_sav`/`read_sav_meta` emit `ambers.CorruptFileWarning` and list the findings in `SavFile.warnings` and `SpssMetadata.warnings` (also in `meta.schema["warnings"]` and `meta.summary()`). The data is still read exactly as stored, never silently corrected. Rust: new `SpssMetadata::warnings`; `read_sav` now returns metadata cloned after the read so it carries data-time findings
|
|
19
|
+
- Fix GitHub issue #2: a header declaring 0 cases while data follows made the reader write past a zero-length row buffer in release builds (process crash). The header case count is now only a capacity hint floored at one row, and the bounds check guarding the decompressor's unsafe writes is unconditional (`SpssError::Internal`) instead of debug-only. Such files now read the rows actually present, matching SPSS (the reporter's file: 5 rows). Legitimately empty files no longer trip a debug assertion. No change for files with a positive case count
|
|
20
|
+
- Fix GitHub issue #1: row width is now derived from the dictionary's type 2 records instead of the header's `nominal_case_size`. A file whose header disagrees with its dictionary is rejected with `invalid dictionary: header declares N slots per case but the dictionary defines M` (SPSS and pyreadstat reject such files too). Previously the mismatch caused an out-of-bounds read and returned garbage columns. A header value of 0 or -1 is tolerated, as some writers store that. No change for valid files (verified byte-identical output on all local test files)
|
|
21
|
+
- Add `SpssError::InvalidDictionary`
|
|
22
|
+
- Add `tests/test_malformed.rs` and `tests/test_malformed.py` (synthetic header/dictionary mismatch fixtures); Python test added to CI
|
|
23
|
+
|
|
5
24
|
## [0.4.4] - 2026-09-18
|
|
6
25
|
|
|
7
26
|
- Fix `FutureWarning: from_arrow(<ArrowStreamExportable>) will return a Series` emitted by `read_sav()` and `scan_sav()` on Polars >= 1.44 — Arrow streams are now converted with `pl.DataFrame()` (available since Polars 1.3, which remains the minimum)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ambers
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.6
|
|
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
|
|
@@ -125,9 +125,19 @@ report.to_frame() # DataFrame for
|
|
|
125
125
|
| `sav.file_size` | `int \| None` | File size in bytes |
|
|
126
126
|
| `sav.read_time` | `float \| None` | Wall-clock read time in seconds |
|
|
127
127
|
| `sav.compression` | `str` | `"uncompressed"`, `"bytecode"`, or `"zlib"` |
|
|
128
|
+
| `sav.warnings` | `list[str]` | File-damage findings; empty for a healthy file |
|
|
128
129
|
|
|
129
130
|
For `scan_sav()`, `read_time` measures metadata/schema reading only (not lazy collection).
|
|
130
131
|
|
|
132
|
+
**Damaged files.** ambers reads a file exactly as stored and never silently "corrects" values.
|
|
133
|
+
If the header disagrees with the contents (declared row count or row width vs what the file
|
|
134
|
+
holds, a non-standard compression bias, date/time values outside years 1-9999 which become
|
|
135
|
+
null), it raises a `CorruptFileWarning` naming the findings and lists them in
|
|
136
|
+
`sav.warnings` / `meta.warnings`. Treat such a file with suspicion and re-export it from the
|
|
137
|
+
source. Structures that cannot be read at all (duplicate variable names, an impossible
|
|
138
|
+
variable type, a record larger than the file) raise an `OSError` immediately. Silence the
|
|
139
|
+
warning with `warnings.filterwarnings("ignore", category=ambers.CorruptFileWarning)`.
|
|
140
|
+
|
|
131
141
|
### apply_labels
|
|
132
142
|
|
|
133
143
|
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.
|
|
@@ -227,6 +237,7 @@ All fields returned by the reader. Fields marked **Write** are preserved when pa
|
|
|
227
237
|
| `number_rows` | yes | — | `int \| None` |
|
|
228
238
|
| `weight_variable` | yes | yes | `str \| None` |
|
|
229
239
|
| `notes` | yes | yes | `list[str]` |
|
|
240
|
+
| `warnings` | yes | — | `list[str]` |
|
|
230
241
|
| `variable_names` | yes | — | `list[str]` |
|
|
231
242
|
| `variable_labels` | yes | yes | `dict[str, str]` |
|
|
232
243
|
| `variable_value_labels` | yes | yes | `dict[str, dict[float\|str, str]]` |
|
|
@@ -356,6 +367,28 @@ On the 5.4 GB file, selecting 5 columns and 1000 rows completes in **13ms** —
|
|
|
356
367
|
- Continued I/O performance optimization
|
|
357
368
|
- Currently Polars-only — pandas/other DataFrame libraries may be added later
|
|
358
369
|
|
|
370
|
+
## Warnings and Errors
|
|
371
|
+
|
|
372
|
+
ambers never silently "corrects" a damaged file. It either reads the data and tells you what
|
|
373
|
+
was wrong, or stops when the file cannot be read at all.
|
|
374
|
+
|
|
375
|
+
- **Warning, data returned** — the file contradicts itself but a more reliable part of it says
|
|
376
|
+
what the bytes mean. You get a `CorruptFileWarning` listing the findings, also available as
|
|
377
|
+
`sav.warnings` / `meta.warnings`. Examples: header row count or row width that disagrees with
|
|
378
|
+
the file, a non-standard compression bias (values may be shifted; SPSS assumes 100),
|
|
379
|
+
date/time values outside years 1-9999 (set to null), impossible very-long-string
|
|
380
|
+
declarations (ignored).
|
|
381
|
+
- **Error, nothing returned** — the structure needed to navigate the file is broken and no
|
|
382
|
+
guess would be safe. You get an `OSError` naming the cause. Examples: duplicate variable
|
|
383
|
+
names, an impossible variable type, a record larger than the file, a truncated file, a file
|
|
384
|
+
that is not SPSS at all.
|
|
385
|
+
- **Silence or escalate** — `warnings.filterwarnings("ignore", category=ambers.CorruptFileWarning)`
|
|
386
|
+
hides the warning (findings stay in `sav.warnings`); `warnings.simplefilter("error",
|
|
387
|
+
ambers.CorruptFileWarning)` makes any damaged file fatal in a pipeline.
|
|
388
|
+
|
|
389
|
+
See [warnings_and_errors.md](warnings_and_errors.md) for every message, what it means, what
|
|
390
|
+
ambers did, and what to do.
|
|
391
|
+
|
|
359
392
|
## License
|
|
360
393
|
|
|
361
394
|
[MIT](LICENSE)
|
|
@@ -115,9 +115,19 @@ report.to_frame() # DataFrame for
|
|
|
115
115
|
| `sav.file_size` | `int \| None` | File size in bytes |
|
|
116
116
|
| `sav.read_time` | `float \| None` | Wall-clock read time in seconds |
|
|
117
117
|
| `sav.compression` | `str` | `"uncompressed"`, `"bytecode"`, or `"zlib"` |
|
|
118
|
+
| `sav.warnings` | `list[str]` | File-damage findings; empty for a healthy file |
|
|
118
119
|
|
|
119
120
|
For `scan_sav()`, `read_time` measures metadata/schema reading only (not lazy collection).
|
|
120
121
|
|
|
122
|
+
**Damaged files.** ambers reads a file exactly as stored and never silently "corrects" values.
|
|
123
|
+
If the header disagrees with the contents (declared row count or row width vs what the file
|
|
124
|
+
holds, a non-standard compression bias, date/time values outside years 1-9999 which become
|
|
125
|
+
null), it raises a `CorruptFileWarning` naming the findings and lists them in
|
|
126
|
+
`sav.warnings` / `meta.warnings`. Treat such a file with suspicion and re-export it from the
|
|
127
|
+
source. Structures that cannot be read at all (duplicate variable names, an impossible
|
|
128
|
+
variable type, a record larger than the file) raise an `OSError` immediately. Silence the
|
|
129
|
+
warning with `warnings.filterwarnings("ignore", category=ambers.CorruptFileWarning)`.
|
|
130
|
+
|
|
121
131
|
### apply_labels
|
|
122
132
|
|
|
123
133
|
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.
|
|
@@ -217,6 +227,7 @@ All fields returned by the reader. Fields marked **Write** are preserved when pa
|
|
|
217
227
|
| `number_rows` | yes | — | `int \| None` |
|
|
218
228
|
| `weight_variable` | yes | yes | `str \| None` |
|
|
219
229
|
| `notes` | yes | yes | `list[str]` |
|
|
230
|
+
| `warnings` | yes | — | `list[str]` |
|
|
220
231
|
| `variable_names` | yes | — | `list[str]` |
|
|
221
232
|
| `variable_labels` | yes | yes | `dict[str, str]` |
|
|
222
233
|
| `variable_value_labels` | yes | yes | `dict[str, dict[float\|str, str]]` |
|
|
@@ -346,6 +357,28 @@ On the 5.4 GB file, selecting 5 columns and 1000 rows completes in **13ms** —
|
|
|
346
357
|
- Continued I/O performance optimization
|
|
347
358
|
- Currently Polars-only — pandas/other DataFrame libraries may be added later
|
|
348
359
|
|
|
360
|
+
## Warnings and Errors
|
|
361
|
+
|
|
362
|
+
ambers never silently "corrects" a damaged file. It either reads the data and tells you what
|
|
363
|
+
was wrong, or stops when the file cannot be read at all.
|
|
364
|
+
|
|
365
|
+
- **Warning, data returned** — the file contradicts itself but a more reliable part of it says
|
|
366
|
+
what the bytes mean. You get a `CorruptFileWarning` listing the findings, also available as
|
|
367
|
+
`sav.warnings` / `meta.warnings`. Examples: header row count or row width that disagrees with
|
|
368
|
+
the file, a non-standard compression bias (values may be shifted; SPSS assumes 100),
|
|
369
|
+
date/time values outside years 1-9999 (set to null), impossible very-long-string
|
|
370
|
+
declarations (ignored).
|
|
371
|
+
- **Error, nothing returned** — the structure needed to navigate the file is broken and no
|
|
372
|
+
guess would be safe. You get an `OSError` naming the cause. Examples: duplicate variable
|
|
373
|
+
names, an impossible variable type, a record larger than the file, a truncated file, a file
|
|
374
|
+
that is not SPSS at all.
|
|
375
|
+
- **Silence or escalate** — `warnings.filterwarnings("ignore", category=ambers.CorruptFileWarning)`
|
|
376
|
+
hides the warning (findings stay in `sav.warnings`); `warnings.simplefilter("error",
|
|
377
|
+
ambers.CorruptFileWarning)` makes any damaged file fatal in a pipeline.
|
|
378
|
+
|
|
379
|
+
See [warnings_and_errors.md](warnings_and_errors.md) for every message, what it means, what
|
|
380
|
+
ambers did, and what to do.
|
|
381
|
+
|
|
349
382
|
## License
|
|
350
383
|
|
|
351
384
|
[MIT](LICENSE)
|
|
@@ -6,6 +6,7 @@ from ambers._io import read_sav, read_sav_meta, scan_sav, write_sav
|
|
|
6
6
|
from ambers._missing import apply_missing
|
|
7
7
|
from ambers._transforms import apply_labels
|
|
8
8
|
from ambers._validate import ValidationIssue, ValidationReport, validate
|
|
9
|
+
from ambers._warnings import CorruptFileWarning
|
|
9
10
|
from ambers.codebook import codebook
|
|
10
11
|
|
|
11
12
|
__all__ = [
|
|
@@ -22,4 +23,5 @@ __all__ = [
|
|
|
22
23
|
"write_sav",
|
|
23
24
|
"SpssMetadata",
|
|
24
25
|
"MetaDiff",
|
|
26
|
+
"CorruptFileWarning",
|
|
25
27
|
]
|
|
@@ -8,6 +8,15 @@ import polars
|
|
|
8
8
|
|
|
9
9
|
T = TypeVar("T", polars.DataFrame, polars.LazyFrame)
|
|
10
10
|
|
|
11
|
+
class CorruptFileWarning(UserWarning):
|
|
12
|
+
"""The .sav file appears damaged or corrupted: its header disagrees with its contents.
|
|
13
|
+
|
|
14
|
+
Emitted by ``read_sav``, ``scan_sav`` and ``read_sav_meta``. The data is read exactly as
|
|
15
|
+
stored; the findings are listed in ``SavFile.warnings`` / ``SpssMetadata.warnings``.
|
|
16
|
+
Silence with ``warnings.filterwarnings("ignore", category=ambers.CorruptFileWarning)``.
|
|
17
|
+
"""
|
|
18
|
+
...
|
|
19
|
+
|
|
11
20
|
@dataclass
|
|
12
21
|
class SavFile(Generic[T]):
|
|
13
22
|
"""Result of reading an SPSS .sav/.zsav file.
|
|
@@ -27,6 +36,8 @@ class SavFile(Generic[T]):
|
|
|
27
36
|
read_time
|
|
28
37
|
Wall-clock seconds for the read operation, or None if not measured.
|
|
29
38
|
For ``scan_sav`` this covers metadata/schema reading only.
|
|
39
|
+
warnings
|
|
40
|
+
File-damage findings (empty for a healthy file); see ``CorruptFileWarning``.
|
|
30
41
|
|
|
31
42
|
Examples
|
|
32
43
|
--------
|
|
@@ -43,6 +54,7 @@ class SavFile(Generic[T]):
|
|
|
43
54
|
shape: tuple[int, int] | None = ...
|
|
44
55
|
file_size: int | None = ...
|
|
45
56
|
read_time: float | None = ...
|
|
57
|
+
warnings: list[str] = ...
|
|
46
58
|
|
|
47
59
|
@property
|
|
48
60
|
def compression(self) -> str:
|
|
@@ -336,6 +348,15 @@ class SpssMetadata:
|
|
|
336
348
|
"""Document record notes (list of strings)."""
|
|
337
349
|
...
|
|
338
350
|
@property
|
|
351
|
+
def warnings(self) -> list[str]:
|
|
352
|
+
"""File-damage findings recorded while reading (empty for a healthy file).
|
|
353
|
+
|
|
354
|
+
Each entry describes a way the header disagrees with the file contents, e.g.
|
|
355
|
+
``"header declares 0 rows but 5 rows were read"`` or a non-standard compression
|
|
356
|
+
bias. Read-only; never written back to a file.
|
|
357
|
+
"""
|
|
358
|
+
...
|
|
359
|
+
@property
|
|
339
360
|
def number_rows(self) -> int | None:
|
|
340
361
|
"""Row count from the file header, or None if not recorded."""
|
|
341
362
|
...
|
|
@@ -405,10 +426,10 @@ class SpssMetadata:
|
|
|
405
426
|
...
|
|
406
427
|
@property
|
|
407
428
|
def schema(self) -> dict:
|
|
408
|
-
"""Full metadata as a nested Python dict (
|
|
429
|
+
"""Full metadata as a nested Python dict (23 fields).
|
|
409
430
|
|
|
410
431
|
Field order: file_label, file_format, file_encoding, creation_time,
|
|
411
|
-
compression, number_columns, number_rows, weight_variable, notes,
|
|
432
|
+
compression, number_columns, number_rows, weight_variable, notes, warnings,
|
|
412
433
|
variable_names, variable_labels, variable_value_labels,
|
|
413
434
|
variable_formats, variable_measures, variable_alignments,
|
|
414
435
|
variable_storage_widths, variable_display_widths, variable_roles,
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import os
|
|
6
|
-
from dataclasses import dataclass
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
7
|
from typing import Generic, TypeVar
|
|
8
8
|
|
|
9
9
|
import polars as pl
|
|
@@ -37,6 +37,10 @@ class SavFile(Generic[T]):
|
|
|
37
37
|
read_time: Wall-clock seconds for the read operation, or None if
|
|
38
38
|
not measured. For ``scan_sav`` this covers metadata/schema
|
|
39
39
|
reading only (not lazy collection).
|
|
40
|
+
warnings: File-damage findings (empty for a healthy file). Each entry
|
|
41
|
+
describes a way the file's header disagrees with its contents.
|
|
42
|
+
A ``CorruptFileWarning`` was emitted when this is non-empty. The
|
|
43
|
+
data is always read exactly as stored.
|
|
40
44
|
"""
|
|
41
45
|
|
|
42
46
|
data: T
|
|
@@ -45,6 +49,7 @@ class SavFile(Generic[T]):
|
|
|
45
49
|
shape: tuple[int, int] | None = None
|
|
46
50
|
file_size: int | None = None
|
|
47
51
|
read_time: float | None = None
|
|
52
|
+
warnings: list[str] = field(default_factory=list)
|
|
48
53
|
|
|
49
54
|
@property
|
|
50
55
|
def compression(self) -> str:
|
|
@@ -78,6 +83,11 @@ class SavFile(Generic[T]):
|
|
|
78
83
|
if not isinstance(self.data, pl.DataFrame):
|
|
79
84
|
time_str += " (metadata only)"
|
|
80
85
|
lines.append(("Read time", time_str))
|
|
86
|
+
# Warnings line (only when the file looks damaged)
|
|
87
|
+
if self.warnings:
|
|
88
|
+
n = len(self.warnings)
|
|
89
|
+
noun = "finding" if n == 1 else "findings"
|
|
90
|
+
lines.append(("Warnings", f"{n} {noun} - file may be damaged, see .warnings"))
|
|
81
91
|
# Build box
|
|
82
92
|
label_w = max(len(label) for label, _ in lines)
|
|
83
93
|
content_parts = [f"{label:<{label_w}} {value}" for label, value in lines]
|
|
@@ -17,6 +17,7 @@ from ambers._ambers import (
|
|
|
17
17
|
)
|
|
18
18
|
|
|
19
19
|
from ambers._containers import SavFile, _get_dtype_map, _resolve_columns
|
|
20
|
+
from ambers._warnings import warn_if_damaged
|
|
20
21
|
|
|
21
22
|
|
|
22
23
|
def read_sav(
|
|
@@ -70,11 +71,13 @@ def read_sav(
|
|
|
70
71
|
df = df.with_row_index(row_index_name, offset=row_index_offset)
|
|
71
72
|
|
|
72
73
|
read_time = time.perf_counter() - t0
|
|
74
|
+
file_warnings = warn_if_damaged(meta, path)
|
|
73
75
|
|
|
74
76
|
return SavFile(
|
|
75
77
|
data=df, meta=meta, source=str(path),
|
|
76
78
|
shape=(df.height, df.width),
|
|
77
79
|
file_size=file_size, read_time=read_time,
|
|
80
|
+
warnings=file_warnings,
|
|
78
81
|
)
|
|
79
82
|
|
|
80
83
|
|
|
@@ -95,7 +98,9 @@ def read_sav_meta(path: str) -> SpssMetadata:
|
|
|
95
98
|
>>> meta.variable_names
|
|
96
99
|
>>> meta.label("Q1")
|
|
97
100
|
"""
|
|
98
|
-
|
|
101
|
+
meta = _read_sav_meta(str(path))
|
|
102
|
+
warn_if_damaged(meta, path)
|
|
103
|
+
return meta
|
|
99
104
|
|
|
100
105
|
|
|
101
106
|
def scan_sav(
|
|
@@ -149,6 +154,8 @@ def scan_sav(
|
|
|
149
154
|
reader = _SavBatchReader(str(path))
|
|
150
155
|
meta = reader.metadata()
|
|
151
156
|
raw_schema = reader.schema()
|
|
157
|
+
# Header-level findings only: the row count is not known until collected.
|
|
158
|
+
file_warnings = warn_if_damaged(meta, path)
|
|
152
159
|
|
|
153
160
|
# Resolve int indices to column names
|
|
154
161
|
resolved = _resolve_columns(columns, meta.variable_names)
|
|
@@ -198,6 +205,7 @@ def scan_sav(
|
|
|
198
205
|
return SavFile(
|
|
199
206
|
data=lf, meta=meta, source=str(path),
|
|
200
207
|
shape=shape, file_size=file_size, read_time=read_time,
|
|
208
|
+
warnings=file_warnings,
|
|
201
209
|
)
|
|
202
210
|
|
|
203
211
|
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""File-damage warnings: tell the caller when a .sav file looks corrupted.
|
|
2
|
+
|
|
3
|
+
ambers always reads a file exactly as stored and never "corrects" values to
|
|
4
|
+
what SPSS would assume. When the file's header disagrees with its contents
|
|
5
|
+
(row count, compression bias, row width), the Rust reader records a message in
|
|
6
|
+
``SpssMetadata.warnings``; this module turns those into one Python warning so
|
|
7
|
+
notebooks and scripts see it immediately, and returns the list for
|
|
8
|
+
``SavFile.warnings``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import warnings
|
|
15
|
+
|
|
16
|
+
from ambers._ambers import SpssMetadata
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CorruptFileWarning(UserWarning):
|
|
20
|
+
"""The .sav file appears damaged or corrupted.
|
|
21
|
+
|
|
22
|
+
Its header disagrees with its contents, so the values may not be what the
|
|
23
|
+
file's author stored. The data was read exactly as found in the file.
|
|
24
|
+
Silence with ``warnings.filterwarnings("ignore", category=ambers.CorruptFileWarning)``.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def warn_if_damaged(meta: SpssMetadata, source: str | os.PathLike | None, *, stacklevel: int = 3) -> list[str]:
|
|
29
|
+
"""Emit one ``CorruptFileWarning`` summarising ``meta.warnings`` and return them.
|
|
30
|
+
|
|
31
|
+
``stacklevel=3`` points the warning at the caller of the public ambers
|
|
32
|
+
function (``warn_if_damaged`` -> ``read_sav`` -> user code).
|
|
33
|
+
"""
|
|
34
|
+
found = list(meta.warnings)
|
|
35
|
+
if found:
|
|
36
|
+
name = os.path.basename(str(source)) if source else "SPSS file"
|
|
37
|
+
details = "; ".join(f"({i}) {m}" for i, m in enumerate(found, 1))
|
|
38
|
+
warnings.warn(
|
|
39
|
+
f"{name} appears damaged or corrupted; please double-check the source. "
|
|
40
|
+
f"Findings: {details}. The data was read exactly as stored in the file.",
|
|
41
|
+
CorruptFileWarning,
|
|
42
|
+
stacklevel=stacklevel,
|
|
43
|
+
)
|
|
44
|
+
return found
|
|
@@ -14,6 +14,7 @@ use arrow::array::{
|
|
|
14
14
|
Array, ArrayRef, Date32Array, DurationMicrosecondArray, Float64Array, Float64Builder,
|
|
15
15
|
StringViewBuilder, TimestampMicrosecondArray,
|
|
16
16
|
};
|
|
17
|
+
use arrow::buffer::{BooleanBuffer, NullBuffer};
|
|
17
18
|
use arrow::datatypes::{Field, Schema};
|
|
18
19
|
use arrow::record_batch::RecordBatch;
|
|
19
20
|
use encoding_rs::Encoding;
|
|
@@ -346,7 +347,10 @@ impl ColumnarBatchBuilder {
|
|
|
346
347
|
///
|
|
347
348
|
/// Temporal columns are converted from Float64 to their proper Arrow types
|
|
348
349
|
/// here, outside the hot path. This keeps the read loops fast for all columns.
|
|
349
|
-
|
|
350
|
+
/// Finish the batch. Also returns how many date/time values were outside
|
|
351
|
+
/// the representable range and were therefore set to null.
|
|
352
|
+
pub fn finish_with_stats(self) -> Result<(RecordBatch, usize)> {
|
|
353
|
+
let mut out_of_range = 0usize;
|
|
350
354
|
let mut columns: Vec<ArrayRef> = self
|
|
351
355
|
.builders
|
|
352
356
|
.into_iter()
|
|
@@ -365,11 +369,13 @@ impl ColumnarBatchBuilder {
|
|
|
365
369
|
.as_any()
|
|
366
370
|
.downcast_ref::<Float64Array>()
|
|
367
371
|
.expect("temporal column should be Float64Array");
|
|
368
|
-
|
|
372
|
+
let (converted, nulled) = convert_float64_to_temporal(float_arr, kind);
|
|
373
|
+
columns[col_idx] = converted;
|
|
374
|
+
out_of_range += nulled;
|
|
369
375
|
}
|
|
370
376
|
|
|
371
377
|
let batch = RecordBatch::try_new(self.schema, columns)?;
|
|
372
|
-
Ok(batch)
|
|
378
|
+
Ok((batch, out_of_range))
|
|
373
379
|
}
|
|
374
380
|
|
|
375
381
|
/// Number of rows appended so far.
|
|
@@ -456,36 +462,92 @@ fn process_string_rows(
|
|
|
456
462
|
// Temporal post-processing (runs in finish(), NOT in hot path)
|
|
457
463
|
// ---------------------------------------------------------------------------
|
|
458
464
|
|
|
465
|
+
/// Representable range for dates and timestamps: years 1..=9999. SPSS cannot
|
|
466
|
+
/// store dates outside it, and Polars (chrono), pandas and Excel all fail on
|
|
467
|
+
/// values far beyond it. Anything outside, and any non-finite value, becomes
|
|
468
|
+
/// null and is counted so the caller can report it; nothing is silently kept
|
|
469
|
+
/// as a saturated garbage value.
|
|
470
|
+
const DATE_MIN_DAYS: f64 = -719_162.0; // 0001-01-01 relative to 1970-01-01
|
|
471
|
+
const DATE_MAX_DAYS: f64 = 2_932_896.0; // 9999-12-31
|
|
472
|
+
const TS_MIN_US: f64 = -62_135_596_800_000_000.0; // 0001-01-01T00:00:00
|
|
473
|
+
const TS_MAX_US: f64 = 253_402_300_799_999_999.0; // 9999-12-31T23:59:59.999999
|
|
474
|
+
const DURATION_MAX_US: f64 = 9.0e18; // well inside i64; never saturates
|
|
475
|
+
|
|
459
476
|
/// Convert a Float64Array of SPSS numeric values to the appropriate Arrow
|
|
460
|
-
/// temporal type.
|
|
477
|
+
/// temporal type. Returns the array and the number of source-valid values
|
|
478
|
+
/// that were outside the representable range and set to null. When nothing is
|
|
479
|
+
/// out of range the source null bitmap is reused as is.
|
|
461
480
|
#[inline(never)]
|
|
462
|
-
fn convert_float64_to_temporal(arr: &Float64Array, kind: TemporalKind) -> ArrayRef {
|
|
463
|
-
let
|
|
481
|
+
fn convert_float64_to_temporal(arr: &Float64Array, kind: TemporalKind) -> (ArrayRef, usize) {
|
|
482
|
+
let src_nulls = arr.nulls().cloned();
|
|
464
483
|
let values = arr.values();
|
|
484
|
+
let n = values.len();
|
|
485
|
+
let mut valid = vec![true; n];
|
|
486
|
+
let mut out_of_range = 0usize;
|
|
487
|
+
let src_is_valid = |i: usize| src_nulls.as_ref().is_none_or(|nb| nb.is_valid(i));
|
|
488
|
+
|
|
489
|
+
macro_rules! convert {
|
|
490
|
+
($t:ty, $lo:expr, $hi:expr, $f:expr) => {{
|
|
491
|
+
let mut out: Vec<$t> = Vec::with_capacity(n);
|
|
492
|
+
for (i, &v) in values.iter().enumerate() {
|
|
493
|
+
let x: f64 = $f(v);
|
|
494
|
+
if x.is_finite() && ($lo..=$hi).contains(&x) {
|
|
495
|
+
out.push(x as $t);
|
|
496
|
+
} else {
|
|
497
|
+
out.push(0);
|
|
498
|
+
valid[i] = false;
|
|
499
|
+
if src_is_valid(i) {
|
|
500
|
+
out_of_range += 1;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
out
|
|
505
|
+
}};
|
|
506
|
+
}
|
|
465
507
|
|
|
466
|
-
match kind {
|
|
508
|
+
let (array, _): (ArrayRef, ()) = match kind {
|
|
467
509
|
TemporalKind::Date => {
|
|
468
|
-
let
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
Arc::new(Date32Array::new(
|
|
510
|
+
let out = convert!(i32, DATE_MIN_DAYS, DATE_MAX_DAYS, |v: f64| v
|
|
511
|
+
/ SECONDS_PER_DAY
|
|
512
|
+
- SPSS_EPOCH_OFFSET_DAYS as f64);
|
|
513
|
+
let nulls = merge_nulls(src_nulls, valid, out_of_range);
|
|
514
|
+
(Arc::new(Date32Array::new(out.into(), nulls)), ())
|
|
473
515
|
}
|
|
474
516
|
TemporalKind::Timestamp => {
|
|
475
|
-
let
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
517
|
+
let out = convert!(i64, TS_MIN_US, TS_MAX_US, |v: f64| (v
|
|
518
|
+
- SPSS_EPOCH_OFFSET_SECONDS)
|
|
519
|
+
* MICROS_PER_SECOND);
|
|
520
|
+
let nulls = merge_nulls(src_nulls, valid, out_of_range);
|
|
521
|
+
(
|
|
522
|
+
Arc::new(TimestampMicrosecondArray::new(out.into(), nulls)),
|
|
523
|
+
(),
|
|
524
|
+
)
|
|
480
525
|
}
|
|
481
526
|
TemporalKind::Duration => {
|
|
482
|
-
let
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
527
|
+
let out = convert!(i64, -DURATION_MAX_US, DURATION_MAX_US, |v: f64| v
|
|
528
|
+
* MICROS_PER_SECOND);
|
|
529
|
+
let nulls = merge_nulls(src_nulls, valid, out_of_range);
|
|
530
|
+
(
|
|
531
|
+
Arc::new(DurationMicrosecondArray::new(out.into(), nulls)),
|
|
532
|
+
(),
|
|
533
|
+
)
|
|
487
534
|
}
|
|
535
|
+
};
|
|
536
|
+
(array, out_of_range)
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/// Source nulls unioned with the out-of-range mask; the source bitmap is
|
|
540
|
+
/// reused untouched when no value was out of range (the common case).
|
|
541
|
+
fn merge_nulls(
|
|
542
|
+
src: Option<NullBuffer>,
|
|
543
|
+
valid: Vec<bool>,
|
|
544
|
+
out_of_range: usize,
|
|
545
|
+
) -> Option<NullBuffer> {
|
|
546
|
+
if out_of_range == 0 {
|
|
547
|
+
return src;
|
|
488
548
|
}
|
|
549
|
+
let mask = NullBuffer::new(BooleanBuffer::from(valid));
|
|
550
|
+
NullBuffer::union(src.as_ref(), Some(&mask))
|
|
489
551
|
}
|
|
490
552
|
|
|
491
553
|
// ---------------------------------------------------------------------------
|