Metadata-Version: 2.4
Name: pyivt
Version: 0.1.0
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Programming Language :: Rust
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Typing :: Typed
Requires-Dist: pyarrow>=14
License-File: LICENSE
Summary: Read Statistics Canada Beyond 20/20 .ivt tables: metadata and Apache Arrow export
Keywords: arrow,beyond-2020,ivt,pyarrow,statcan,statistics-canada
Author: Nate Babyak
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/natebabyak/pyivt/blob/main/CHANGELOG.md
Project-URL: Homepage, https://github.com/natebabyak/pyivt
Project-URL: Issues, https://github.com/natebabyak/pyivt/issues
Project-URL: Repository, https://github.com/natebabyak/pyivt.git

# pyivt

Read Statistics Canada Beyond 20/20 (`.ivt`) tables in Python: bilingual
metadata, and export to Apache Arrow.

> [!NOTE]
> The API can change in any release before v1.0.0, so pin an exact version. From
> v1.0.0, the [stability policy](https://github.com/natebabyak/pyivt/blob/main/docs/api.md#stability-and-deprecation-policy)
> applies.

## Install

```sh
pip install pyivt
```

pyivt needs Python 3.11 or later and PyArrow 14 or later. There are wheels for
Linux (x86_64 and aarch64, glibc or musl), Windows (x64) and macOS (x86_64 and
arm64). See [supported platforms](https://github.com/natebabyak/pyivt/blob/main/docs/api.md#supported-platforms)
for details.

## Open a table

The examples use the 2021 Census table 98-10-0001:

```sh
curl -O https://www150.statcan.gc.ca/n1/en/tbl/b2020/98100001.zip
```

```python
import pyivt

ivt = pyivt.open("98100001.zip")
print(ivt.metadata.title.en)
print(ivt.metadata.title.fr)
```

```text
Population and dwelling counts: Canada, provinces and territories
Chiffres de population et des logements : Canada, provinces et territoires
```

`open()` takes an `.ivt` file or a ZIP that contains one, as a path, bytes or a
binary file object.

## Inspect dimensions

```python
for dimension in ivt.metadata.dimensions:
    print(dimension.slug, dimension.items, dimension.members.en[:2])
```

```text
geography 14 ['Canada', 'Newfoundland and Labrador']
population_and_dwelling_counts_11 11 ['Population, 2021', 'Population, 2016']
```

Slugs name the columns in exports and the keys in selections.

## Export

```python
import pyarrow.parquet as pq

table = ivt.to_arrow()
members = ivt.to_member_table()
print(table.num_rows, table.column_names)
pq.write_table(table, "98100001.parquet")
pq.write_table(members, "98100001.members.parquet")
```

```text
154 ['geography', 'population_and_dwelling_counts_11', 'value']
```

`to_arrow()` has one row per cell. Dimension columns hold 1-based member
positions, and a null `value` is a missing cell. `to_member_table()` has the
label and native attributes of each member. Use `to_member_table(language="fr")`
for French labels.

For a table too large to build at once, stream it:

```python
with ivt.iter_batches() as reader:
    with pq.ParquetWriter("98100001.parquet", reader.schema) as writer:
        for batch in reader:
            writer.write_batch(batch)
```

## Select a subset

An integer fixes a dimension at one member and drops its column. A list keeps
the column and limits it to those members.

```python
selection = {"geography": [1, 2, 3], "population_and_dwelling_counts_11": 1}
population = ivt.to_arrow(select=selection)
members = ivt.to_member_table(select=selection)

labels = dict(zip(members["code"].to_pylist(), members["label"].to_pylist()))
for row in population.to_pylist():
    print(labels[row["geography"]], row["value"])
```

```text
Canada 36991981.0
Newfoundland and Labrador 510550.0
Prince Edward Island 154331.0
```

To select by name instead of number, generate a Python module of enums with
`pyivt codegen 98100001.zip --output dimensions.py`.

## Errors

A file that cannot be read raises a subclass of `pyivt.IvtError`, which is a
`ValueError`:

- `CorruptFileError`: the file is damaged or is not an IVT file.
- `UnsupportedFormatError`: the file is an IVT, but pyivt cannot read its layout.
  Container versions 2 and 4 are supported.
- `ResourceLimitError`: a memory estimate exceeds a safety limit. Use `select` or
  `iter_batches()`, or raise `max_memory_bytes`.

```python
try:
    pyivt.open(b"not an IVT file")
except pyivt.CorruptFileError as error:
    print(f"{error.file_len} bytes is too short for an IVT file")
```

```text
15 bytes is too short for an IVT file
```

The [API reference](https://github.com/natebabyak/pyivt/blob/main/docs/api.md)
covers every public name.

## License

[MIT](https://github.com/natebabyak/pyivt/blob/main/LICENSE). Thanks to
[canivt](https://github.com/mountainMath/canivt) and
[REA](https://github.com/morluto/rea).

