Introduce Pheon GDSII parsing and layout review tools

Implement native GDSII reading and writing with Arrow interchange, hierarchy
scans and selective cell loading. Validate numeric packing and array pitches,
and preserve normalized REAL8 encodings exactly within the supported range.

Add standalone dump, structural diff, hierarchy, layer-name annotation and Git
diff commands. Provide scoped text and JSON reports, deterministic comparison,
and record-preserving metadata edits.

Package the shared library and optional Python Arrow readers as pheon using
CFFI ABI mode and Python-independent platform wheels. Include locked source
builds, native API checks, cross-platform artifact workflows, documentation
and regression coverage. Require Rust 1.88 or newer and Python 3.11 or newer.

Validation: 87 native tests, 14 binding tests on Python 3.11/3.13/3.14,
and 71 installed companion integration tests pass. Full, scanned and selected
Arrow layouts match the previous schemas.
This commit is contained in:
Jan Petykiewicz 2026-11-16 16:21:21 -08:00
commit b3346b40a4
59 changed files with 12956 additions and 1 deletions

23
.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,23 @@
name: Native checks
on:
push:
pull_request:
workflow_dispatch:
permissions:
contents: read
jobs:
rust:
runs-on: ubuntu-latest
strategy:
matrix:
rust: ['1.88.0', stable]
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- run: rustup toolchain install ${{ matrix.rust }} --profile minimal
- run: cargo +${{ matrix.rust }} test --locked
- run: cargo +${{ matrix.rust }} test --locked --release

123
.github/workflows/packages.yml vendored Normal file
View file

@ -0,0 +1,123 @@
name: Package artifacts
on:
pull_request:
workflow_dispatch:
push:
tags: ['v*']
permissions:
contents: read
jobs:
sdist:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- uses: actions/setup-python@v6
with:
python-version: '3.11'
- run: python -m pip install build
- run: python -m build --sdist
- uses: actions/upload-artifact@v4
with:
name: source
path: dist/*.tar.gz
wheels:
needs: sdist
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, ubuntu-24.04-arm, macos-15-intel, macos-15, windows-latest]
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- uses: actions/download-artifact@v4
with:
name: source
path: source-dist
- name: Unpack the source release
shell: bash
run: |
mkdir source-build
tar -xzf source-dist/*.tar.gz -C source-build --strip-components=1
- name: Build and repair Python-independent wheels from the sdist
uses: pypa/cibuildwheel@v4.3.5
with:
package-dir: source-build
env:
CIBW_BUILD: cp311-*
CIBW_SKIP: '*-musllinux_* *-win32'
CIBW_ARCHS: native
CIBW_ENVIRONMENT_LINUX: 'CARGO_HOME=/tmp/pheon-cargo RUSTUP_HOME=/tmp/pheon-rustup PATH=/tmp/pheon-cargo/bin:$PATH'
CIBW_BEFORE_ALL_LINUX: 'curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable'
CIBW_TEST_EXTRAS: arrow
CIBW_TEST_COMMAND: 'python -I {project}/tools/check_installed.py'
- name: Check wheel ABI tags
shell: python
run: |
from pathlib import Path
wheels = list(Path('wheelhouse').glob('*.whl'))
assert wheels
assert all('-py3-none-' in p.name for p in wheels), wheels
- uses: actions/upload-artifact@v4
with:
name: wheel-${{ matrix.os }}
path: wheelhouse/*.whl
same-wheel:
needs: wheels
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, ubuntu-24.04-arm, macos-15-intel, macos-15, windows-latest]
python: ['3.11', '3.12', '3.13', '3.14']
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python }}
- uses: actions/download-artifact@v4
with:
name: wheel-${{ matrix.os }}
path: wheelhouse
- name: Install the same artifact on another Python version
shell: bash
run: python -m pip install wheelhouse/*.whl pyarrow
- run: python -I tools/check_installed.py
cli:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, ubuntu-24.04-arm, macos-15-intel, macos-15, windows-latest]
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- run: cargo test --release --locked
- run: cargo build --release --locked --bin pheon
- name: Assemble standalone CLI artifact
shell: bash
run: |
mkdir cli-dist
if [ "$RUNNER_OS" = Windows ]; then
cp target/release/pheon.exe cli-dist/
else
cp target/release/pheon cli-dist/
fi
cp LICENSE.md README.md cli-dist/
cp -R contrib cli-dist/
- uses: actions/upload-artifact@v4
with:
name: cli-${{ matrix.os }}
path: cli-dist/

6
.gitignore vendored
View file

@ -1,6 +1,10 @@
/target/
**/*.rs.bk
Cargo.lock
*.swp
*.swo
__pycache__/
/build/
/dist/
/*.egg-info/

154
ARROW_SCHEMA.md Normal file
View file

@ -0,0 +1,154 @@
# Arrow Schema Documentation
Pheon's native `pheon_arrow_schema_version()` returns 1 for the full-read,
scan and selected-read layouts documented here. This version is independent
of the C API version, package release and CLI JSON report schema. The stable
Arrow C Data Interface transports these application-specific layouts; consumers
must check both the native API and application schema before reading data.
This project uses Apache Arrow to represent GDSII (Graphic Data System II) library data. The schema is optimized for memory efficiency and fast access, employing several packed representations for common data types.
## Top-Level Structure
The top-level object is a `StructArray` representing the entire GDSII library.
| Field | Type | Description |
|---|---|---|
| `meters_per_db_unit` | `Float64` | Database unit size in meters. |
| `user_units_per_db_unit` | `Float64` | Number of user units in one database unit. |
| `lib_name` | `Utf8` | The name of the GDSII library. |
| `mod_time` | `FixedSizeList(Int16, 6)` | Last modification time [year, month, day, hour, minute, second]. |
| `acc_time` | `FixedSizeList(Int16, 6)` | Last access time [year, month, day, hour, minute, second]. |
| `cells` | `List(Cell)` | A list of cells (structures) in the library. |
| `cell_names` | `List(Utf8)` | Names of all cells, indexed by their ID. |
| `layers` | `List(UInt32)` | List of packed layer/datatype pairs, indexed by their ID. |
## Cell Structure
Each cell in the `cells` list is a `StructArray`.
| Field | Type | Description |
|---|---|---|
| `id` | `UInt32` | Unique identifier for the cell. |
| `file_offset` | `UInt64` | Byte offset immediately after the cell's `STRNAME` record (the first element, or `ENDSTR` for an empty cell). Identical for full and selected reads. |
| `srefs` | `List(SRef)` | Simple structure references (no properties). |
| `arefs` | `List(ARef)` | Array references (no properties). |
| `sref_props` | `List(SRefProp)` | Structure references with properties. |
| `aref_props` | `List(ARefProp)` | Array references with properties. |
| `rect_batches` | `List(RectBatch)` | Batches of rectangular boundaries (optimized). |
| `boundary_batches` | `List(BoundaryBatch)` | Batches of generic boundaries. |
| `boundary_props` | `List(BoundaryProp)` | Individual boundaries with properties. |
| `paths` | `List(Path)` | Path elements. |
| `nodes` | `List(BoxNode)` | Node elements. |
| `boxes` | `List(BoxNode)` | Box elements. |
| `texts` | `List(Text)` | Text labels. |
## Hierarchy Scan Schema
`scan_library` and `scan_bytes` return the same library metadata and `cell_names`
as a full read, with the following `cells` schema and no `layers` field:
| Field | Type | Description |
|---|---|---|
| `id` | `UInt32` | Cell ID indexing this result's `cell_names`. |
| `struct_start_offset` | `UInt64` | Inclusive byte offset of the `BGNSTR` record. |
| `struct_end_offset` | `UInt64` | Exclusive byte offset immediately after `ENDSTR`. |
| `refs` | `List(ScanRef)` | SREFs and AREFs, including references with properties, sorted by target ID. |
Each scan reference has `target`, `invert_y`, `scale`, `angle_rad`, `xy`, `xy0`,
`xy1`, and `counts`, using the ARef types and packed encodings described below.
SREFs use zero basis vectors and counts `(1, 1)`. Properties are omitted from the
scan output; geometry and text are skipped without decoding.
Pass the half-open scan ranges to `read_selected_library` or `read_cells_bytes`
to obtain the full library schema for just those cells. Each range must contain
exactly one complete cell, from `BGNSTR` through `ENDSTR`. Cells appear in the
requested order. Cell and layer IDs are assigned within each result, so use
`cell_names` and `layers` from that result when resolving them; IDs can differ
from a full read or a scan. An empty selection returns metadata and empty lists.
The Rust random-access reader returns the original input slice as its remainder.
## Element Types
### Common Packed Encodings
- **Layer ID (`UInt32`)**: A packed representation of `(layer, datatype)`.
- `layer = (layer_id >> 16) as i16`
- `datatype = (layer_id & 0xFFFF) as i16`
- **XY Coordinate (`UInt64`)**: A packed representation of a single point `(x, y)`.
- `x = (xy >> 32) as i32`
- `y = (xy & 0xFFFFFFFF) as i32`
- **Array Counts (`UInt32`)**: A packed representation of `(columns, rows)`.
- `columns = (counts >> 16) as i16`
- `rows = (counts & 0xFFFF) as i16`
### Reference Elements (SRef / ARef)
References point to other cells in the library.
**SRef (Simple Reference)**:
- `target`: `UInt32` (Cell ID)
- `invert_y`: `Boolean` (Vertical flip)
- `scale`: `Float64` (Magnification)
- `angle_rad`: `Float64` (Rotation in radians)
- `xy`: `UInt64` (Packed origin point)
**ARef (Array Reference)**:
- Same as SRef, plus:
- `xy0`: `UInt64` (Packed column basis vector increment)
- `xy1`: `UInt64` (Packed row basis vector increment)
- `counts`: `UInt32` (Packed columns and rows)
Array increments must be exact signed 32-bit integer database-unit values. Full
reads, hierarchy scans, selected reads, and their FFI entry points reject arrays
whose endpoint/count division is fractional or outside that range. They never
round or truncate placements. The review CLI retains original endpoints and can
compare fractional arrays independently of this Arrow representation.
**SRefProp / ARefProp**:
- Same as above, plus a `properties` field.
### Boundary Elements
Boundaries are grouped into batches for efficiency when they share properties or are simple rectangles.
**RectBatch**:
- `layer`: `UInt32` (Packed Layer ID)
- `rects`: `List(Int32)` (Flattened list of `[min_x, min_y, max_x, max_y]` for each rectangle)
**BoundaryBatch**:
- `layer`: `UInt32` (Packed Layer ID)
- `vertices`: `List(Int32)` (Flattened list of all vertices for all boundaries in the batch)
- `vertex_offsets`: `List(UInt32)` (Start index for each boundary in the `vertices` list)
**BoundaryProp**:
- Individual boundary with `properties`.
### Other Elements
**Path**:
- `layer`: `UInt32`
- `path_type`: `Int16` (Optional)
- `extension_start`: `Int32` (Optional)
- `extension_end`: `Int32` (Optional)
- `width`: `Int32` (Optional; null when `WIDTH` is absent)
- `xy`: `List(Int32)` (centerline coordinates)
- `properties`: `List(Property)`
**Text**:
- `layer`: `UInt32`
- `presentation_horiz`: `UInt8`
- `presentation_vert`: `UInt8`
- `presentation_font`: `UInt8`
- `path_type`: `Int16`
- `width`: `Int32`
- `invert_y`: `Boolean`
- `mag`: `Float64`
- `angle_deg`: `Float64`
- `xy`: `UInt64` (Packed position)
- `string`: `Utf8`
- `properties`: `List(Property)`
**Property**:
- `key`: `Int16`
- `value`: `Utf8`

587
Cargo.lock generated Normal file
View file

@ -0,0 +1,587 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "ahash"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011"
dependencies = [
"cfg-if",
"const-random",
"getrandom",
"once_cell",
"version_check",
"zerocopy",
]
[[package]]
name = "android-tzdata"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0"
[[package]]
name = "android_system_properties"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
dependencies = [
"libc",
]
[[package]]
name = "arrow-array"
version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a12fcdb3f1d03f69d3ec26ac67645a8fe3f878d77b5ebb0b15d64a116c212985"
dependencies = [
"ahash",
"arrow-buffer",
"arrow-data",
"arrow-schema",
"chrono",
"half",
"hashbrown",
"num",
]
[[package]]
name = "arrow-buffer"
version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "263f4801ff1839ef53ebd06f99a56cecd1dbaf314ec893d93168e2e860e0291c"
dependencies = [
"bytes",
"half",
"num",
]
[[package]]
name = "arrow-data"
version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61cfdd7d99b4ff618f167e548b2411e5dd2c98c0ddebedd7df433d34c20a4429"
dependencies = [
"arrow-buffer",
"arrow-schema",
"half",
"num",
]
[[package]]
name = "arrow-schema"
version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cfaf5e440be44db5413b75b72c2a87c1f8f0627117d110264048f2969b99e9"
dependencies = [
"bitflags",
]
[[package]]
name = "autocfg"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "bitflags"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd"
[[package]]
name = "bumpalo"
version = "3.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf"
[[package]]
name = "bytes"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
[[package]]
name = "cc"
version = "1.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e3a13707ac958681c13b39b458c073d0d9bc8a22cb1b2f4c8e55eb72c13f362"
dependencies = [
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chrono"
version = "0.4.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a7964611d71df112cb1730f2ee67324fcf4d0fc6606acbbe9bfe06df124637c"
dependencies = [
"android-tzdata",
"iana-time-zone",
"num-traits",
"windows-link",
]
[[package]]
name = "const-random"
version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"
dependencies = [
"const-random-macro",
]
[[package]]
name = "const-random-macro"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"
dependencies = [
"getrandom",
"once_cell",
"tiny-keccak",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "crunchy"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43da5946c66ffcc7745f48db692ffbb10a83bfe0afd96235c5c2a4fb23994929"
[[package]]
name = "getrandom"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "half"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9"
dependencies = [
"cfg-if",
"crunchy",
"num-traits",
]
[[package]]
name = "hashbrown"
version = "0.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289"
[[package]]
name = "iana-time-zone"
version = "0.1.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0c919e5debc312ad217002b8048a17b7d83f80703865bbfcfebb0458b0b27d8"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"log",
"wasm-bindgen",
"windows-core",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]]
name = "itoa"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
[[package]]
name = "js-sys"
version = "0.3.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f"
dependencies = [
"once_cell",
"wasm-bindgen",
]
[[package]]
name = "libc"
version = "0.2.172"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa"
[[package]]
name = "libm"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa"
[[package]]
name = "log"
version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
[[package]]
name = "memchr"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "num"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
dependencies = [
"num-bigint",
"num-complex",
"num-integer",
"num-iter",
"num-rational",
"num-traits",
]
[[package]]
name = "num-bigint"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-complex"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"num-traits",
]
[[package]]
name = "num-integer"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
dependencies = [
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-bigint",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
"libm",
]
[[package]]
name = "once_cell"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "pheon"
version = "0.3.0"
dependencies = [
"arrow-array",
"arrow-schema",
"serde_json",
]
[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustversion"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2"
[[package]]
name = "ryu"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
[[package]]
name = "serde"
version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.140"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"
dependencies = [
"itoa",
"memchr",
"ryu",
"serde",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "syn"
version = "2.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tiny-keccak"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
dependencies = [
"crunchy",
]
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6"
dependencies = [
"bumpalo",
"log",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d"
dependencies = [
"unicode-ident",
]
[[package]]
name = "windows-core"
version = "0.61.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4763c1de310c86d75a878046489e2e5ba02c649d185f21c67d4cf8a56d098980"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-implement"
version = "0.60.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "windows-interface"
version = "0.59.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "windows-link"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76840935b766e1b0a05c0066835fb9ec80071d4c09a16f6bd5f7e655e3c14c38"
[[package]]
name = "windows-result"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c64fd11a4fd95df68efcfee5f44a294fe71b8bc6a91993e2791938abcc712252"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a2ba9642430ee452d5a7aa78d72907ebe8cfda358e8cb7918a2050581322f97"
dependencies = [
"windows-link",
]
[[package]]
name = "zerocopy"
version = "0.7.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.7.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e"
dependencies = [
"proc-macro2",
"quote",
"syn",
]

25
Cargo.toml Normal file
View file

@ -0,0 +1,25 @@
[package]
name = "pheon"
version = "0.3.0"
authors = ["jan <jan@mpxd.net>"]
edition = "2024"
rust-version = "1.88"
description = "GDSII parsing, Arrow interchange, and structural layout review"
license = "GPL-3.0-only"
readme = "README.md"
repository = "https://mpxd.net/code/jan/pheon"
[lib]
name = "pheon"
crate-type = ["cdylib", "rlib"]
[dependencies]
arrow-array = {version = "^54", features = ["ffi"]}
arrow-schema = "^54"
serde_json = "1"
[profile.release]
lto = true

595
LICENSE.md Normal file
View file

@ -0,0 +1,595 @@
GNU General Public License
==========================
_Version 3, 29 June 2007_
_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
## Preamble
The GNU General Public License is a free, copyleft license for software and other
kinds of works.
The licenses for most software and other practical works are designed to take away
your freedom to share and change the works. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change all versions of a
program--to make sure it remains free software for all its users. We, the Free
Software Foundation, use the GNU General Public License for most of our software; it
applies also to any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General
Public Licenses are designed to make sure that you have the freedom to distribute
copies of free software (and charge for them if you wish), that you receive source
code or can get it if you want it, that you can change the software or use pieces of
it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or
asking you to surrender the rights. Therefore, you have certain responsibilities if
you distribute copies of the software, or if you modify it: responsibilities to
respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee,
you must pass on to the recipients the same freedoms that you received. You must make
sure that they, too, receive or can get the source code. And you must show them these
terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: **(1)** assert
copyright on the software, and **(2)** offer you this License giving you legal permission
to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is
no warranty for this free software. For both users' and authors' sake, the GPL
requires that modified versions be marked as changed, so that their problems will not
be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of
the software inside them, although the manufacturer can do so. This is fundamentally
incompatible with the aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we have designed
this version of the GPL to prohibit the practice for those products. If such problems
arise substantially in other domains, we stand ready to extend this provision to
those domains in future versions of the GPL, as needed to protect the freedom of
users.
Finally, every program is threatened constantly by software patents. States should
not allow patents to restrict development and use of software on general-purpose
computers, but in those that do, we wish to avoid the special danger that patents
applied to a free program could make it effectively proprietary. To prevent this, the
GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
## TERMS AND CONDITIONS
### 0. Definitions
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this
License. Each licensee is addressed as “you”. “Licensees” and
“recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in
a fashion requiring copyright permission, other than the making of an exact copy. The
resulting work is called a “modified version” of the earlier work or a
work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on
the Program.
To “propagate” a work means to do anything with it that, without
permission, would make you directly or secondarily liable for infringement under
applicable copyright law, except executing it on a computer or modifying a private
copy. Propagation includes copying, distribution (with or without modification),
making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through a computer
network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the
extent that it includes a convenient and prominently visible feature that **(1)**
displays an appropriate copyright notice, and **(2)** tells the user that there is no
warranty for the work (except to the extent that warranties are provided), that
licensees may convey the work under this License, and how to view a copy of this
License. If the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
### 1. Source Code
The “source code” for a work means the preferred form of the work for
making modifications to it. “Object code” means any non-source form of a
work.
A “Standard Interface” means an interface that either is an official
standard defined by a recognized standards body, or, in the case of interfaces
specified for a particular programming language, one that is widely used among
developers working in that language.
The “System Libraries” of an executable work include anything, other than
the work as a whole, that **(a)** is included in the normal form of packaging a Major
Component, but which is not part of that Major Component, and **(b)** serves only to
enable use of the work with that Major Component, or to implement a Standard
Interface for which an implementation is available to the public in source code form.
A “Major Component”, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (if any) on which
the executable work runs, or a compiler used to produce the work, or an object code
interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the
source code needed to generate, install, and (for an executable work) run the object
code and to modify the work, including scripts to control those activities. However,
it does not include the work's System Libraries, or general-purpose tools or
generally available free programs which are used unmodified in performing those
activities but which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for the work, and
the source code for shared libraries and dynamically linked subprograms that the work
is specifically designed to require, such as by intimate data communication or
control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate
automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
### 2. Basic Permissions
All rights granted under this License are granted for the term of copyright on the
Program, and are irrevocable provided the stated conditions are met. This License
explicitly affirms your unlimited permission to run the unmodified Program. The
output from running a covered work is covered by this License only if the output,
given its content, constitutes a covered work. This License acknowledges your rights
of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without
conditions so long as your license otherwise remains in force. You may convey covered
works to others for the sole purpose of having them make modifications exclusively
for you, or provide you with facilities for running those works, provided that you
comply with the terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for you must do so
exclusively on your behalf, under your direction and control, on terms that prohibit
them from making any copies of your copyrighted material outside their relationship
with you.
Conveying under any other circumstances is permitted solely under the conditions
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law
No covered work shall be deemed part of an effective technological measure under any
applicable law fulfilling obligations under article 11 of the WIPO copyright treaty
adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention
of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of
technological measures to the extent such circumvention is effected by exercising
rights under this License with respect to the covered work, and you disclaim any
intention to limit operation or modification of the work as a means of enforcing,
against the work's users, your or third parties' legal rights to forbid circumvention
of technological measures.
### 4. Conveying Verbatim Copies
You may convey verbatim copies of the Program's source code as you receive it, in any
medium, provided that you conspicuously and appropriately publish on each copy an
appropriate copyright notice; keep intact all notices stating that this License and
any non-permissive terms added in accord with section 7 apply to the code; keep
intact all notices of the absence of any warranty; and give all recipients a copy of
this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer
support or warranty protection for a fee.
### 5. Conveying Modified Source Versions
You may convey a work based on the Program, or the modifications to produce it from
the Program, in the form of source code under the terms of section 4, provided that
you also meet all of these conditions:
* **a)** The work must carry prominent notices stating that you modified it, and giving a
relevant date.
* **b)** The work must carry prominent notices stating that it is released under this
License and any conditions added under section 7. This requirement modifies the
requirement in section 4 to “keep intact all notices”.
* **c)** You must license the entire work, as a whole, under this License to anyone who
comes into possession of a copy. This License will therefore apply, along with any
applicable section 7 additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no permission to license the
work in any other way, but it does not invalidate such permission if you have
separately received it.
* **d)** If the work has interactive user interfaces, each must display Appropriate Legal
Notices; however, if the Program has interactive interfaces that do not display
Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are
not by their nature extensions of the covered work, and which are not combined with
it such as to form a larger program, in or on a volume of a storage or distribution
medium, is called an “aggregate” if the compilation and its resulting
copyright are not used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work in an aggregate
does not cause this License to apply to the other parts of the aggregate.
### 6. Conveying Non-Source Forms
You may convey a covered work in object code form under the terms of sections 4 and
5, provided that you also convey the machine-readable Corresponding Source under the
terms of this License, in one of these ways:
* **a)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by the Corresponding Source fixed on a
durable physical medium customarily used for software interchange.
* **b)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by a written offer, valid for at least
three years and valid for as long as you offer spare parts or customer support for
that product model, to give anyone who possesses the object code either **(1)** a copy of
the Corresponding Source for all the software in the product that is covered by this
License, on a durable physical medium customarily used for software interchange, for
a price no more than your reasonable cost of physically performing this conveying of
source, or **(2)** access to copy the Corresponding Source from a network server at no
charge.
* **c)** Convey individual copies of the object code with a copy of the written offer to
provide the Corresponding Source. This alternative is allowed only occasionally and
noncommercially, and only if you received the object code with such an offer, in
accord with subsection 6b.
* **d)** Convey the object code by offering access from a designated place (gratis or for
a charge), and offer equivalent access to the Corresponding Source in the same way
through the same place at no further charge. You need not require recipients to copy
the Corresponding Source along with the object code. If the place to copy the object
code is a network server, the Corresponding Source may be on a different server
(operated by you or a third party) that supports equivalent copying facilities,
provided you maintain clear directions next to the object code saying where to find
the Corresponding Source. Regardless of what server hosts the Corresponding Source,
you remain obligated to ensure that it is available for as long as needed to satisfy
these requirements.
* **e)** Convey the object code using peer-to-peer transmission, provided you inform
other peers where the object code and Corresponding Source of the work are being
offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the
Corresponding Source as a System Library, need not be included in conveying the
object code work.
A “User Product” is either **(1)** a “consumer product”, which
means any tangible personal property which is normally used for personal, family, or
household purposes, or **(2)** anything designed or sold for incorporation into a
dwelling. In determining whether a product is a consumer product, doubtful cases
shall be resolved in favor of coverage. For a particular product received by a
particular user, “normally used” refers to a typical or common use of
that class of product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected to use, the
product. A product is a consumer product regardless of whether the product has
substantial commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
“Installation Information” for a User Product means any methods,
procedures, authorization keys, or other information required to install and execute
modified versions of a covered work in that User Product from a modified version of
its Corresponding Source. The information must suffice to ensure that the continued
functioning of the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for
use in, a User Product, and the conveying occurs as part of a transaction in which
the right of possession and use of the User Product is transferred to the recipient
in perpetuity or for a fixed term (regardless of how the transaction is
characterized), the Corresponding Source conveyed under this section must be
accompanied by the Installation Information. But this requirement does not apply if
neither you nor any third party retains the ability to install modified object code
on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to
continue to provide support service, warranty, or updates for a work that has been
modified or installed by the recipient, or for the User Product in which it has been
modified or installed. Access to a network may be denied when the modification itself
materially and adversely affects the operation of the network or violates the rules
and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with
this section must be in a format that is publicly documented (and with an
implementation available to the public in source code form), and must require no
special password or key for unpacking, reading or copying.
### 7. Additional Terms
“Additional permissions” are terms that supplement the terms of this
License by making exceptions from one or more of its conditions. Additional
permissions that are applicable to the entire Program shall be treated as though they
were included in this License, to the extent that they are valid under applicable
law. If additional permissions apply only to part of the Program, that part may be
used separately under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any
additional permissions from that copy, or from any part of it. (Additional
permissions may be written to require their own removal in certain cases when you
modify the work.) You may place additional permissions on material, added by you to a
covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a
covered work, you may (if authorized by the copyright holders of that material)
supplement the terms of this License with terms:
* **a)** Disclaiming warranty or limiting liability differently from the terms of
sections 15 and 16 of this License; or
* **b)** Requiring preservation of specified reasonable legal notices or author
attributions in that material or in the Appropriate Legal Notices displayed by works
containing it; or
* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that
modified versions of such material be marked in reasonable ways as different from the
original version; or
* **d)** Limiting the use for publicity purposes of names of licensors or authors of the
material; or
* **e)** Declining to grant rights under trademark law for use of some trade names,
trademarks, or service marks; or
* **f)** Requiring indemnification of licensors and authors of that material by anyone
who conveys the material (or modified versions of it) with contractual assumptions of
liability to the recipient, for any liability that these contractual assumptions
directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further
restrictions” within the meaning of section 10. If the Program as you received
it, or any part of it, contains a notice stating that it is governed by this License
along with a term that is a further restriction, you may remove that term. If a
license document contains a further restriction but permits relicensing or conveying
under this License, you may add to a covered work material governed by the terms of
that license document, provided that the further restriction does not survive such
relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in
the relevant source files, a statement of the additional terms that apply to those
files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a
separately written license, or stated as exceptions; the above requirements apply
either way.
### 8. Termination
You may not propagate or modify a covered work except as expressly provided under
this License. Any attempt otherwise to propagate or modify it is void, and will
automatically terminate your rights under this License (including any patent licenses
granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a
particular copyright holder is reinstated **(a)** provisionally, unless and until the
copyright holder explicitly and finally terminates your license, and **(b)** permanently,
if the copyright holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently
if the copyright holder notifies you of the violation by some reasonable means, this
is the first time you have received notice of violation of this License (for any
work) from that copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of
parties who have received copies or rights from you under this License. If your
rights have been terminated and not permanently reinstated, you do not qualify to
receive new licenses for the same material under section 10.
### 9. Acceptance Not Required for Having Copies
You are not required to accept this License in order to receive or run a copy of the
Program. Ancillary propagation of a covered work occurring solely as a consequence of
using peer-to-peer transmission to receive a copy likewise does not require
acceptance. However, nothing other than this License grants you permission to
propagate or modify any covered work. These actions infringe copyright if you do not
accept this License. Therefore, by modifying or propagating a covered work, you
indicate your acceptance of this License to do so.
### 10. Automatic Licensing of Downstream Recipients
Each time you convey a covered work, the recipient automatically receives a license
from the original licensors, to run, modify and propagate that work, subject to this
License. You are not responsible for enforcing compliance by third parties with this
License.
An “entity transaction” is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an organization, or
merging organizations. If propagation of a covered work results from an entity
transaction, each party to that transaction who receives a copy of the work also
receives whatever licenses to the work the party's predecessor in interest had or
could give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if the predecessor
has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or
affirmed under this License. For example, you may not impose a license fee, royalty,
or other charge for exercise of rights granted under this License, and you may not
initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging
that any patent claim is infringed by making, using, selling, offering for sale, or
importing the Program or any portion of it.
### 11. Patents
A “contributor” is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The work thus
licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or
controlled by the contributor, whether already acquired or hereafter acquired, that
would be infringed by some manner, permitted by this License, of making, using, or
selling its contributor version, but do not include claims that would be infringed
only as a consequence of further modification of the contributor version. For
purposes of this definition, “control” includes the right to grant patent
sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license
under the contributor's essential patent claims, to make, use, sell, offer for sale,
import and otherwise run, modify and propagate the contents of its contributor
version.
In the following three paragraphs, a “patent license” is any express
agreement or commitment, however denominated, not to enforce a patent (such as an
express permission to practice a patent or covenant not to sue for patent
infringement). To “grant” such a patent license to a party means to make
such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the
Corresponding Source of the work is not available for anyone to copy, free of charge
and under the terms of this License, through a publicly available network server or
other readily accessible means, then you must either **(1)** cause the Corresponding
Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the
patent license for this particular work, or **(3)** arrange, in a manner consistent with
the requirements of this License, to extend the patent license to downstream
recipients. “Knowingly relying” means you have actual knowledge that, but
for the patent license, your conveying the covered work in a country, or your
recipient's use of the covered work in a country, would infringe one or more
identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you
convey, or propagate by procuring conveyance of, a covered work, and grant a patent
license to some of the parties receiving the covered work authorizing them to use,
propagate, modify or convey a specific copy of the covered work, then the patent
license you grant is automatically extended to all recipients of the covered work and
works based on it.
A patent license is “discriminatory” if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on the
non-exercise of one or more of the rights that are specifically granted under this
License. You may not convey a covered work if you are a party to an arrangement with
a third party that is in the business of distributing software, under which you make
payment to the third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties who would receive
the covered work from you, a discriminatory patent license **(a)** in connection with
copies of the covered work conveyed by you (or copies made from those copies), or **(b)**
primarily for and in connection with specific products or compilations that contain
the covered work, unless you entered into that arrangement, or that patent license
was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied
license or other defenses to infringement that may otherwise be available to you
under applicable patent law.
### 12. No Surrender of Others' Freedom
If conditions are imposed on you (whether by court order, agreement or otherwise)
that contradict the conditions of this License, they do not excuse you from the
conditions of this License. If you cannot convey a covered work so as to satisfy
simultaneously your obligations under this License and any other pertinent
obligations, then as a consequence you may not convey it at all. For example, if you
agree to terms that obligate you to collect a royalty for further conveying from
those to whom you convey the Program, the only way you could satisfy both those terms
and this License would be to refrain entirely from conveying the Program.
### 13. Use with the GNU Affero General Public License
Notwithstanding any other provision of this License, you have permission to link or
combine any covered work with a work licensed under version 3 of the GNU Affero
General Public License into a single combined work, and to convey the resulting work.
The terms of this License will continue to apply to the part which is the covered
work, but the special requirements of the GNU Affero General Public License, section
13, concerning interaction through a network will apply to the combination as such.
### 14. Revised Versions of this License
The Free Software Foundation may publish revised and/or new versions of the GNU
General Public License from time to time. Such new versions will be similar in spirit
to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that
a certain numbered version of the GNU General Public License “or any later
version” applies to it, you have the option of following the terms and
conditions either of that numbered version or of any later version published by the
Free Software Foundation. If the Program does not specify a version number of the GNU
General Public License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU
General Public License can be used, that proxy's public statement of acceptance of a
version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no
additional obligations are imposed on any author or copyright holder as a result of
your choosing to follow a later version.
### 15. Disclaimer of Warranty
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
### 16. Limitation of Liability
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS
PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE
OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
### 17. Interpretation of Sections 15 and 16
If the disclaimer of warranty and limitation of liability provided above cannot be
given local legal effect according to their terms, reviewing courts shall apply local
law that most closely approximates an absolute waiver of all civil liability in
connection with the Program, unless a warranty or assumption of liability accompanies
a copy of the Program in return for a fee.
_END OF TERMS AND CONDITIONS_
## How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to
the public, the best way to achieve this is to make it free software which everyone
can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them
to the start of each source file to most effectively state the exclusion of warranty;
and each file should have at least the “copyright” line and a pointer to
where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this
when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type 'show c' for details.
The hypothetical commands `show w` and `show c` should show the appropriate parts of
the General Public License. Of course, your program's commands might be different;
for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to
sign a “copyright disclaimer” for the program, if necessary. For more
information on this, and how to apply and follow the GNU GPL, see
&lt;<http://www.gnu.org/licenses/>&gt;.
The GNU General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may consider it
more useful to permit linking proprietary applications with the library. If this is
what you want to do, use the GNU Lesser General Public License instead of this
License. But first, please read
&lt;<http://www.gnu.org/philosophy/why-not-lgpl.html>&gt;.

7
MANIFEST.in Normal file
View file

@ -0,0 +1,7 @@
include Cargo.toml Cargo.lock rust-toolchain.toml README.md ARROW_SCHEMA.md LICENSE.md
recursive-include src *.rs
recursive-include pheon *.py *.h py.typed
recursive-include tests *.rs *.py *.json *.txt *.mmd
recursive-include docs *.md *.json
recursive-include contrib *
recursive-include tools *.py

337
README.md Normal file
View file

@ -0,0 +1,337 @@
# Pheon
A fast GDSII parser and writer in Rust, with Apache Arrow integration for efficient data handling.
Pheon provides native GDSII codecs and a standalone layout review CLI. The Rust
crate, Python package and executable are all named `pheon`. Python Klamath and
Masque remain separate consumers. The former `klamath_rs_ext` import and
`klamath` executable are not provided as aliases.
## Overview
`pheon` is designed to handle large GDSII files with high performance. It uses Apache Arrow as its primary in-memory data representation, allowing for efficient memory usage and easy integration with other tools in the Arrow ecosystem (like pandas, polars, or DuckDB via Python bindings).
## Documentation
- [Arrow Schema Documentation](ARROW_SCHEMA.md): Detailed information about the Arrow schema used for GDSII data.
## Features
- Fast parsing of GDSII files.
- Efficient memory representation using Apache Arrow.
- Support for common GDSII elements: SREF, AREF, Boundary, Path, Text, etc.
- Optimized "batch" representations for rectangles and boundaries sharing the same layer.
- C-compatible FFI for integration with other languages (e.g., Python).
REAL8 writing uses normalized GDS encodings and represents every in-range `f64`
exactly. Finite magnitudes below `2^-260` underflow to canonical zero; nonfinite
values and magnitudes at or above `2^252` are rejected by the encoder.
## Usage
`read_path` exports a library through the Arrow C Data Interface. Allocate
initialized `ArrowArray` and `ArrowSchema` output structures, then check the
returned status: `0` means success and `-1` means failure. Only import the Arrow
outputs after success; the caller owns their release callbacks. Failed calls
leave the outputs unchanged. `pheon/_ffi.h` declares the C API; `test.py`
demonstrates the supported Python reader.
`last_error_message()` returns a UTF-8, null-terminated error string, or null
after a successful parser call. Errors belong to the calling thread. Copy the
message before making another parser call on that thread, and before the thread
exits; calls on other threads do not invalidate it. Parser panics that unwind
are converted into errors.
For partial reads, call `scan_bytes` with a borrowed GDSII byte buffer to obtain
cell ranges and references without decoding geometry. Pass the desired ranges
to `read_cells_bytes` to load their full contents. Both calls use the same Arrow
outputs and status/error handling as `read_path`:
```c
int scan_bytes(const uint8_t *data, size_t size,
struct ArrowArray *array, struct ArrowSchema *schema);
int read_cells_bytes(const uint8_t *data, size_t size,
const uint64_t *ranges, size_t range_count,
struct ArrowArray *array, struct ArrowSchema *schema);
```
`ranges` contains alternating inclusive start and exclusive end offsets, with
two native-endian `uint64_t` values per cell. Each range must cover one complete
cell. A null `ranges` pointer is accepted when `range_count` is zero. Likewise,
null `data` is accepted for zero bytes and produces an ordinary parse error for
the empty input. Nonempty buffers must be readable for the duration of the call;
range values must be aligned. Exported Arrow data owns its storage independently
of the input. See [Arrow Schema Documentation](ARROW_SCHEMA.md) for the scan
schema, offset definitions, and ID assignment.
## Python package and validation
Python 3.11 or newer is required. Source builds require Rust 1.88 or newer;
installing a prebuilt wheel requires no Rust compiler. The shared library uses
a C ABI rather than Python's or Rust's native ABI, so one platform wheel serves
multiple Python minor versions. CFFI, NumPy and optional PyArrow must themselves
support the selected interpreter. A Rust application uses the crate normally
and compiles it with its own compatible toolchain. The checkout selects the
stable toolchain locally through `rust-toolchain.toml`, without changing your
global default. CI checks both Rust 1.88 and current stable.
```sh
python3 -m pip install 'pheon[arrow]'
```
```python
from pheon import arrow
library = arrow.read_path('chip.gds') # one-row StructArray; also accepts gzip
scan = arrow.scan_bytes(gds_bytes)
cells = scan.field('cells')[0].values
ranges = list(zip(cells.field('struct_start_offset').to_pylist(),
cells.field('struct_end_offset').to_pylist()))
selected = arrow.read_cells_bytes(gds_bytes, ranges[:2])
```
`read_bytes` reads a complete borrowed buffer. Full, scanned and selected Arrow
results own their storage independently of that buffer. `PheonError` reports
native parse failures; malformed range shapes and types raise Python value/type
errors before calling native code. Integer packing needs no PyArrow import.
### Discovery and companion packages
Klamath's `native` extra installs `pheon`; Masque's `arrow` extra installs
`pheon[arrow]`. Klamath imports Pheon's packing helpers, while Masque calls
`pheon.arrow` and translates parse failures to its existing error type.
The Python loader selects the library bundled with the imported `pheon` package,
or the exact file selected by `PHEON_LIBRARY`. It checks C ABI version 1 and
Arrow layout schema version 1 before exposing native functions. Incompatible
or unversioned libraries fail with an import error. Those versions are independent
of package releases and the CLI's JSON report schema.
`cargo install --path . --locked --bin pheon` installs the CLI, not the Python
package or a discoverable shared library. Klamath does not search PATH or Cargo
directories for it. To reuse an external native build, install the Python
components too and set `PHEON_LIBRARY`; an editable source install is useful
during development. The old library override variables are not recognized.
The Python packing helpers require NumPy and CFFI, both declared as runtime
dependencies. Setuptools invokes `cargo build --release --lib` and bundles the
C ABI shared library in a platform-specific wheel. Its version comes from
`Cargo.toml`. The C declarations are in `pheon/_ffi.h`; the loader uses
CFFI ABI mode, so no Python extension compilation or Maturin is required.
```sh
python3 -m pip install .
```
To build a source archive and a wheel with the `build` frontend and installed
Setuptools/Wheel tooling:
```sh
python3 -m build --no-isolation
```
Source archives include a Cargo lockfile, and wheel builds use `--locked` so
building from an archive retains the resolved Rust dependency versions. Wheels
are tagged for the build platform and use the Python-independent `py3-none` ABI.
The CLI continues to build directly with Cargo and has no Python dependency.
For source-tree development, point the CFFI loader at a Cargo-built library:
```sh
cargo build --release --lib
PHEON_LIBRARY="$PWD/target/release/libpheon.so" \
python3 -m unittest discover -s tests/python -v
```
Use `libpheon.dylib` on macOS or `pheon.dll` on Windows. Without
the explicit override, the loader uses the library bundled inside the package.
After installing a wheel, run its tests outside the source checkout to exercise
the installed package:
```sh
python3 -I -m unittest discover -s /absolute/path/to/pheon/tests/python -v
```
The Python tests cover multidimensional and noncontiguous packing, input
preservation, range errors, and the C declarations for Arrow exports and release
callbacks, input lifetimes and ABI mismatches. Run `cargo test` and
`cargo test --release` for native validation. See [release validation](docs/releases.md)
for wheel builds, platform repair and testing the same artifact on multiple
Python versions.
## Layout review CLI
The review CLI is a standalone Rust executable:
```sh
cargo build --bin pheon
target/debug/pheon dump chip.gds
target/debug/pheon dump chip.gds --records
target/debug/pheon diff old.gds new.gds --hierarchy ascii
target/debug/pheon diff old.gds new.gds --hierarchy mermaid --max-changes 20
target/debug/pheon hierarchy chip.gds --format mermaid --depth 4
target/debug/pheon diff old.gds new.gds --top CHIP --layer 1/0
target/debug/pheon diff old.gds new.gds --show-layer 1/0
target/debug/pheon diff old.gds new.gds --format json
target/debug/pheon diff old.gds new.gds --format json --hierarchy graph
target/debug/pheon name-layers chip.gds named.gds --cell CHIP --carrier 900/7 --name 1:0:WG
```
The object dump is deterministic and omits source offsets. Record dumps preserve
record order and show offsets, tags, sizes, and values, including records the
object reviewer does not support. They can inspect an invalid metadata declaration
without invoking object-level validation. Zero padding after ENDLIB is accepted.
The fixed `klamath-object-v2` comparison profile:
- Matches cells by name and layers by numeric pair. The default scope is the
entire library; explicit selectors are recorded in each report.
- Ignores library/cell timestamps, cell order, element order, and property order.
- Normalizes boundary/box starting vertex and winding, retaining other vertices.
- Preserves duplicate objects and duplicate properties as multisets.
- Compares paths, labels, references, array endpoints/counts, properties, and all
retained flags exactly. Explicit defaults and their omission remain distinct;
SREFs and single-element AREFs remain distinct. REAL8 encodings are retained.
- Reports library fields, including UNITS, separately. It does not rescale files
into a shared grid, infer cell renames, or perform geometric Boolean operations.
- Uses bounding boxes as coordinate envelopes, not evidence of equality. Path
envelopes do not include stroke width; text/reference envelopes are coordinates,
not rendered or recursively transformed bounds.
- Returns an incomplete result for unsupported records, future metadata versions,
unresolved references, or cycles. These cannot produce an equality claim.
`diff` exits with **0** for equality under this profile, **1** for differences,
and **2** for invalid input or incomplete comparison. `--max-changes` limits the
number of object details displayed, not the comparison. Source offsets are
included in changed-object reports for tracing changes back to record dumps.
`diff --format json` emits a versioned report with typed before/after evidence,
structured diagnostics, and independent comparison status and completeness.
JSON includes all changes by default. Explicit display filters and `--max-changes`
record omitted evidence without changing totals or exit status. `--hierarchy graph`
adds the complete scoped reference graph, with symbolic array multiplicities;
`--depth` applies to text output only. Timestamp-only changes still return 0.
Input and argument errors also produce JSON when requested. See the
[report contract](docs/diff-reports.md) and
[version 1 JSON Schema](docs/diff-report-v1.schema.json).
Unmatched objects are paired for explanation only when candidates are unique by
type/layer/bounding box, then by type/layer among the remaining objects.
References additionally match by target. Ambiguous groups stay additions and
removals. Reports explain reference movement, array-count changes, path widths,
and polygons changed within the same bounds. Full before/after records remain
visible, and duplicate counts remain significant. Unchanged layer names appear
once as a legend for changed objects on those layers.
### Comparison scope and display filters
`--top NAME` compares that cell and its reachable subtree independently in each
revision. `--cell NAME` compares the exact cell, including its reference records,
without comparing descendant contents. Combine the two to select a cell within
a subtree. A selector absent from both revisions is an error; absence on one
side is an addition/deletion.
`--layer L/T` selects objects on a numeric layer/type pair, plus references whose
targets use that layer transitively. Cells with no relevant content are omitted.
Unresolved references, cycles, and unsupported records with unknown layer effect
remain incomplete results. Unsupported objects on another known layer can be
excluded. Library fields, including units, remain compared. Unsupported layer-name
version diagnostics are always retained, since those declarations can affect any
layer or cell in the library. Scoped dumps and
hierarchy views accept the same selectors. Scope selection parses the complete
input: malformed record grammar and conflicting metadata are still errors.
`--show-cell NAME` and `--show-layer L/T` filter object details in a diff report
without changing comparison status, totals, metadata changes, or hierarchy.
References have no numeric layer and are hidden by `--show-layer`. The comparison
scope and any display-only filter are printed explicitly. The Rust API accepts
one combined `Scope`; applying another scope to an already scoped document is
rejected rather than losing reference coverage information.
Hierarchy output distinguishes directly changed cells, affected ancestors, and
unchanged targets of modified references. It includes edges from both revisions,
so removed branches remain visible. Counts are direct edge multiplicities,
including arrays, rather than expanded placements. Shared definitions are marked
as already shown in text and appear once in Mermaid. `--depth` limits displayed
descendants only. The CLI emits Mermaid source, requiring no diagram renderer.
Layer names are read from labels in an existing cell. A label with the exact
string `KLAMATH_LAYER_NAMES_V1` identifies an annotation carrier `(layer, texttype)`
pair within that cell. All other labels on that same pair in that same cell must
be `layer:datatype:name` declarations, for example `1:0:WG`. The carrier pair is
not fixed; choose a suitable annotation layer in the design's technology.
Declarations split at the first two colons, allowing colons in names. Numeric
fields are unsigned 16-bit decimal integers. Names are nonempty UTF-8 strings.
Repeated identical declarations are accepted; conflicting declarations fail.
Names are collected across the library. Recognized metadata labels are omitted
from object comparison; mappings are compared separately and printed once per
numeric pair, so renaming a layer does not rewrite every shape description.
`name-layers INPUT OUTPUT --cell NAME --carrier L/T --name L:T:NAME ...` writes
this convention. It consolidates existing recognized declarations into one legend
in the chosen existing cell, retains existing names not explicitly updated, and
overrides the named pairs. The chosen carrier must contain no ordinary design
objects in that cell. Unrelated records, timestamps, unknown records and trailing
padding are copied byte-for-byte. No structures or references are added. Output
must be a new file: the CLI refuses to overwrite an existing destination, including
the input. Invalid declarations, conflicting arguments, oversized labels and
future metadata versions fail before output creation.
The record-preserving review adapter retains information normalized or omitted
by the Arrow geometry reader; existing Arrow APIs are unchanged. Structured Rust
change records feed the text and hierarchy renderers. LayoutEditor's `LayerNames`
extension, layout extraction/remapping, and geometric Boolean comparison remain
outside the current CLI.
### Git integration
Install the executable on PATH with `cargo install --path . --bin pheon`.
The templates in [contrib/git/config](contrib/git/config) and
[contrib/git/attributes](contrib/git/attributes) provide two alternative drivers.
For structural summaries and affected hierarchy, add this attribute:
```gitattributes
*.gds diff=pheon
```
Configure the native external driver in Git config:
```gitconfig
[diff "pheon"]
command = pheon git-diff --hierarchy ascii --
binary = true
trustExitCode = false
```
The adapter consumes Git's old/new temporary files directly, handles additions,
deletions and renames, and quotes display paths. It returns success after rendering
either equality or differences, as expected by the external-driver protocol.
Invalid or incomplete comparisons retain a nonzero exit and diagnostics. Scope
and display options can precede the final `--` in the configured command. Existing
repositories using `diff=layout` can put the same command under `[diff "layout"]`.
For ordinary Git line diffs, use canonical textconv instead:
```gitattributes
*.gds diff=pheon-text
```
Configure the driver in Git config:
```gitconfig
[diff "pheon-text"]
textconv = pheon dump
binary = true
cachetextconv = true
```
This is a human review representation, not an applicable GDS patch. Invalidate
Git's textconv cache when changing the dump profile/tool version. For automated
equality checks, use `pheon diff` and its exit status directly.
`tests/review.rs` contains ten initial fixture pairs, checked-in canonical/text/
Mermaid goldens, metadata byte-preservation checks, scope and report regressions,
and actual Git integration tests. It also checks near-limit polygon records,
2048-cell hierarchies and arrays representing over a billion placements without
expanding them. Run `cargo test` and `cargo test --release` for debug and optimized
validation. No KLayout installation or Python package is required.

5
contrib/git/attributes Normal file
View file

@ -0,0 +1,5 @@
# Add these lines to the layout repository's .gitattributes.
*.gds diff=pheon
# For canonical textconv instead, replace the line above with:
# *.gds diff=pheon-text

10
contrib/git/config Normal file
View file

@ -0,0 +1,10 @@
# Include this file from Git config after installing pheon on PATH.
[diff "pheon"]
command = pheon git-diff --hierarchy ascii --
binary = true
trustExitCode = false
[diff "pheon-text"]
textconv = pheon dump
binary = true
cachetextconv = true

View file

@ -0,0 +1,206 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Pheon diff report version 1",
"description": "Object-profile comparison evidence, not a layout serialization. Unknown additional fields are permitted for compatible extensions.",
"type": "object",
"required": ["schema_version", "kind", "producer", "comparison_profile", "inputs", "scope", "coordinates", "status", "result", "exit_code", "summary", "report_selection", "layer_legend", "library_changes", "layer_name_changes", "cell_changes", "hierarchy", "diagnostics"],
"properties": {
"schema_version": {"const": 1},
"kind": {"const": "diff"},
"producer": {
"type": "object", "required": ["name", "version"],
"properties": {"name": {"const": "pheon"}, "version": {"type": "string"}}
},
"comparison_profile": {"type": "string"},
"inputs": {
"type": "object", "required": ["old", "new"],
"properties": {"old": {"$ref": "#/$defs/input"}, "new": {"$ref": "#/$defs/input"}}
},
"scope": {
"type": "object", "required": ["top", "cell", "layer"],
"properties": {"top": {"type": ["string", "null"]}, "cell": {"type": ["string", "null"]}, "layer": {"$ref": "#/$defs/nullableLayer"}}
},
"coordinates": {
"type": "object", "required": ["unit", "frame", "bounds"],
"properties": {"unit": {"const": "database_unit"}, "frame": {"const": "cell_local"}, "bounds": {"const": "coordinate_envelope"}}
},
"status": {"enum": ["complete", "incomplete", "failed"]},
"result": {"enum": ["equal", "different", "unknown"]},
"exit_code": {"enum": [0, 1, 2]},
"summary": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/summary"}]},
"report_selection": {"$ref": "#/$defs/selection"},
"layer_legend": {
"type": "array", "items": {
"type": "object", "required": ["layer", "name"],
"properties": {"layer": {"$ref": "#/$defs/layer"}, "name": {"type": "string"}}
}
},
"library_changes": {"type": "array", "items": {"$ref": "#/$defs/libraryChange"}},
"layer_name_changes": {
"type": "array", "items": {
"type": "object", "required": ["layer", "before", "after"],
"properties": {"layer": {"$ref": "#/$defs/layer"}, "before": {"type": ["string", "null"]}, "after": {"type": ["string", "null"]}}
}
},
"cell_changes": {"type": "array", "items": {"$ref": "#/$defs/cellChange"}},
"hierarchy": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/graph"}]},
"diagnostics": {"type": "array", "items": {"$ref": "#/$defs/diagnostic"}}
},
"allOf": [
{
"if": {"properties": {"status": {"const": "complete"}}},
"then": {
"properties": {"result": {"enum": ["equal", "different"]}, "summary": {"$ref": "#/$defs/summary", "properties": {"counts": {"const": "exact"}}}, "diagnostics": {"maxItems": 0}},
"if": {"properties": {"result": {"const": "equal"}}},
"then": {"properties": {"exit_code": {"const": 0}}},
"else": {"properties": {"exit_code": {"const": 1}}}
},
"else": {"properties": {"exit_code": {"const": 2}, "diagnostics": {"minItems": 1}}}
},
{
"if": {"properties": {"status": {"const": "incomplete"}}},
"then": {"properties": {"result": {"enum": ["different", "unknown"]}, "summary": {"$ref": "#/$defs/summary", "properties": {"counts": {"const": "observed"}}}}}
},
{
"if": {"properties": {"status": {"const": "failed"}}},
"then": {"properties": {"result": {"const": "unknown"}, "summary": {"type": "null"}, "library_changes": {"maxItems": 0}, "layer_name_changes": {"maxItems": 0}, "cell_changes": {"maxItems": 0}, "hierarchy": {"type": "null"}}}
}
],
"$defs": {
"decimal": {"type": "string", "pattern": "^(0|[1-9][0-9]*)$"},
"hex": {"type": "string", "pattern": "^0x([0-9a-f]{2})*$"},
"uint16": {"type": "integer", "minimum": 0, "maximum": 65535},
"int32": {"type": "integer", "minimum": -2147483648, "maximum": 2147483647},
"layer": {
"type": "object", "required": ["number", "purpose"],
"properties": {"number": {"$ref": "#/$defs/uint16"}, "purpose": {"$ref": "#/$defs/uint16"}}
},
"nullableLayer": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/layer"}]},
"point": {"type": "array", "minItems": 2, "maxItems": 2, "items": {"$ref": "#/$defs/int32"}},
"fields": {"type": "array", "items": {"$ref": "#/$defs/field"}},
"field": {
"type": "object", "required": ["tag", "name", "encoding", "value", "payload_hex"],
"properties": {
"tag": {"$ref": "#/$defs/uint16"}, "name": {"type": "string"},
"encoding": {"enum": ["xy", "uint16", "int16", "int32", "bits", "real8", "ascii", "none", "bytes"]},
"payload_hex": {"$ref": "#/$defs/hex"},
"value": {"type": ["array", "string", "null"]}
},
"allOf": [
{"if": {"properties": {"encoding": {"const": "xy"}}}, "then": {"properties": {"value": {"type": "array", "items": {"$ref": "#/$defs/point"}}}}},
{"if": {"properties": {"encoding": {"enum": ["uint16", "bits"]}}}, "then": {"properties": {"value": {"type": "array", "items": {"$ref": "#/$defs/uint16"}}}}},
{"if": {"properties": {"encoding": {"const": "int16"}}}, "then": {"properties": {"value": {"type": "array", "items": {"type": "integer", "minimum": -32768, "maximum": 32767}}}}},
{"if": {"properties": {"encoding": {"const": "int32"}}}, "then": {"properties": {"value": {"type": "array", "items": {"$ref": "#/$defs/int32"}}}}},
{"if": {"properties": {"encoding": {"const": "real8"}}}, "then": {"properties": {"value": {"type": "array", "items": {"type": ["number", "null"]}}}}},
{"if": {"properties": {"encoding": {"const": "ascii"}}}, "then": {"properties": {"value": {"type": ["string", "null"]}}}},
{"if": {"properties": {"encoding": {"enum": ["none", "bytes"]}}}, "then": {"properties": {"value": {"type": "null"}}}}
]
},
"input": {
"type": "object", "required": ["path", "path_encoded_hex", "present", "units"],
"properties": {
"path": {"type": ["string", "null"]},
"path_encoded_hex": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/hex"}]},
"present": {"type": ["boolean", "null"]},
"units": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/field"}]}
}
},
"summary": {
"type": "object", "required": ["counts", "changed_cells", "removed_objects", "added_objects", "layer_name_changes", "library_field_changes"],
"properties": {
"counts": {"enum": ["exact", "observed"]},
"changed_cells": {"$ref": "#/$defs/decimal"}, "removed_objects": {"$ref": "#/$defs/decimal"}, "added_objects": {"$ref": "#/$defs/decimal"},
"layer_name_changes": {"$ref": "#/$defs/decimal"}, "library_field_changes": {"$ref": "#/$defs/decimal"}
}
},
"selection": {
"type": "object", "required": ["cell", "layer", "max_objects", "truncated", "filtered_cells", "filtered_objects", "limited_objects", "emitted_objects"],
"properties": {
"cell": {"type": ["string", "null"]}, "layer": {"$ref": "#/$defs/nullableLayer"},
"max_objects": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/decimal"}]}, "truncated": {"type": "boolean"},
"filtered_cells": {"$ref": "#/$defs/decimal"}, "filtered_objects": {"$ref": "#/$defs/decimal"},
"limited_objects": {"$ref": "#/$defs/decimal"}, "emitted_objects": {"$ref": "#/$defs/decimal"}
}
},
"libraryChange": {
"oneOf": [
{
"type": "object", "required": ["field", "tag", "before", "after"],
"properties": {"field": {"const": "presence"}, "tag": {"type": "null"}, "before": {"type": "boolean"}, "after": {"type": "boolean"}}
},
{
"type": "object", "required": ["field", "tag", "before", "after"],
"properties": {"field": {"type": "string"}, "tag": {"$ref": "#/$defs/uint16"}, "before": {"$ref": "#/$defs/fields"}, "after": {"$ref": "#/$defs/fields"}}
}
]
},
"source": {
"type": "object", "required": ["side", "byte_offset", "end_offset"],
"properties": {"side": {"enum": ["old", "new"]}, "byte_offset": {"$ref": "#/$defs/decimal"}, "end_offset": {"$ref": "#/$defs/decimal"}}
},
"property": {
"type": "object", "required": ["attribute", "value", "payload_hex"],
"properties": {"attribute": {"$ref": "#/$defs/uint16"}, "value": {"type": ["string", "null"]}, "payload_hex": {"$ref": "#/$defs/hex"}}
},
"object": {
"type": "object", "required": ["id", "kind", "tag", "source", "layer", "bounds", "target", "origin", "width", "counts", "fields", "properties"],
"properties": {
"id": {"type": "string"}, "kind": {"type": "string"}, "tag": {"$ref": "#/$defs/uint16"}, "source": {"$ref": "#/$defs/source"},
"layer": {"$ref": "#/$defs/nullableLayer"},
"bounds": {"oneOf": [{"type": "null"}, {"type": "array", "minItems": 4, "maxItems": 4, "items": {"$ref": "#/$defs/int32"}}]},
"target": {"type": ["string", "null"]}, "origin": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/point"}]},
"width": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/int32"}]},
"counts": {"oneOf": [{"type": "null"}, {"type": "array", "minItems": 2, "maxItems": 2, "items": {"type": "integer", "minimum": 1, "maximum": 32767}}]},
"fields": {"$ref": "#/$defs/fields"}, "properties": {"type": "array", "items": {"$ref": "#/$defs/property"}}
}
},
"replacement": {
"type": "object", "required": ["removed", "added", "match_rule", "explanation", "field_changes", "properties_changed"],
"properties": {
"removed": {"type": "string"}, "added": {"type": "string"}, "match_rule": {"type": "string"}, "explanation": {"type": "string"}, "properties_changed": {"type": "boolean"},
"field_changes": {"type": "array", "items": {
"type": "object", "required": ["tag", "before", "after"],
"properties": {"tag": {"$ref": "#/$defs/uint16"}, "before": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/field"}]}, "after": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/field"}]}}
}}
}
},
"cellSide": {
"oneOf": [{"type": "null"}, {
"type": "object", "required": ["byte_offset", "attributes"],
"properties": {"byte_offset": {"$ref": "#/$defs/decimal"}, "attributes": {"$ref": "#/$defs/fields"}}
}]
},
"cellChange": {
"type": "object", "required": ["name", "before", "after", "attributes_changed", "removed", "added", "replacements"],
"properties": {
"name": {"type": "string"}, "before": {"$ref": "#/$defs/cellSide"}, "after": {"$ref": "#/$defs/cellSide"}, "attributes_changed": {"type": "boolean"},
"removed": {"type": "array", "items": {"$ref": "#/$defs/object"}}, "added": {"type": "array", "items": {"$ref": "#/$defs/object"}},
"replacements": {"type": "array", "items": {"$ref": "#/$defs/replacement"}}
}
},
"diagnostic": {
"type": "object", "required": ["code", "severity", "message", "side", "byte_offset", "cell", "layer", "target"],
"properties": {
"code": {"type": "string"}, "severity": {"const": "error"}, "message": {"type": "string"}, "side": {"enum": ["old", "new", null]},
"byte_offset": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/decimal"}]}, "cell": {"type": ["string", "null"]},
"layer": {"$ref": "#/$defs/nullableLayer"}, "target": {"type": ["string", "null"]}
}
},
"graph": {
"type": "object", "required": ["nodes", "edges"],
"properties": {
"nodes": {"type": "array", "items": {
"type": "object", "required": ["cell", "before", "after", "change"],
"properties": {
"cell": {"type": "string"}, "before": {"enum": ["included", "outside_scope", "unresolved", "absent"]}, "after": {"enum": ["included", "outside_scope", "unresolved", "absent"]},
"change": {"enum": ["direct", "affected", "unchanged"]}
}
}},
"edges": {"type": "array", "items": {
"type": "object", "required": ["parent", "target", "before_count", "after_count", "reference_changed"],
"properties": {"parent": {"type": "string"}, "target": {"type": "string"}, "before_count": {"$ref": "#/$defs/decimal"}, "after_count": {"$ref": "#/$defs/decimal"}, "reference_changed": {"type": "boolean"}}
}}
}
}
}
}

189
docs/diff-reports.md Normal file
View file

@ -0,0 +1,189 @@
# Machine-readable diff reports
```sh
pheon diff before.gds after.gds --format json > report.json
pheon diff before.gds after.gds --format json --hierarchy graph
pheon diff before.gds after.gds --format json --top CHIP --layer 1/0
```
The command writes one UTF-8 JSON document followed by a newline to stdout.
Comparison diagnostics belong to that document. Output write failures are
reported on stderr and return 2; interrupted output is not a valid report.
JSON output currently belongs to `diff`; `dump`, `hierarchy`, and the Git
external driver retain their existing text interfaces. No external process is
used to produce a report.
The [version 1 JSON Schema](diff-report-v1.schema.json) defines the structure.
[Golden reports](../tests/golden/report-geometry.json) illustrate complete
evidence; other `report-*.json` goldens cover equality, metadata, incomplete
comparison, and failure. Their producer version is replaced with `test` so
package version changes do not alter the fixtures.
## Versions and determinism
Pheon emits schema version 1 with producer name `pheon`. This schema has not
had a public release. The comparison profile remains `klamath-object-v2`, and
the `KLAMATH_LAYER_NAMES_V1` GDS marker retains its existing meaning.
`schema_version` describes the report structure. `comparison_profile` names the
equality rules, currently `klamath-object-v2`. `producer.version` identifies the
implementation. These versions are independent. Consumers interpreting equality
must understand the comparison profile as well as the schema.
Compatible additions may introduce optional fields. Consumers should ignore
unfamiliar additional fields and handle unfamiliar diagnostic codes and matching
rules without treating them as equality. Removed fields or changed meanings
require a new schema version. The schema intentionally permits additional fields.
For the same inputs, paths, options, and producer version, serialization is
deterministic. Cells, layer pairs, fields, properties, and graph edges are sorted.
Duplicate objects and properties remain separate occurrences. Reports contain
no generation timestamp or required content fingerprint.
## Result and exit status
| `status` | `result` | Exit code | Interpretation |
| --- | --- | --- | --- |
| `complete` | `equal` | 0 | Equal under the recorded profile and scope. |
| `complete` | `different` | 1 | Differences found. |
| `incomplete` | `different` | 2 | Definite differences found, with comparison limitations. |
| `incomplete` | `unknown` | 2 | Equality cannot be established. |
| `failed` | `unknown` | 2 | No comparison result is available. |
Unsupported records, future metadata versions, unresolved references, and
hierarchy cycles make the comparison incomplete. Malformed input, read errors,
invalid scopes, and invalid command arguments produce failed reports. CI must
check completeness as well as differences. An exit code of 1 is a normal
comparison outcome, including when stdout is redirected to a report file.
Library and cell timestamps are excluded from the comparison profile. A valid,
complete timestamp-only comparison returns 0. Raw record dumps remain available
for examining those timestamps.
`summary` counts the entire scoped comparison, before display selection. Its
`counts` is `exact` for a complete comparison and `observed` for an incomplete
one. Failed reports have a null summary and empty change arrays. Replacement
suggestions and affected ancestors never add to change counts.
## Scope, selection, and numbers
`scope` records the actual `top`, `cell`, and numeric `layer` selectors. Null
means unrestricted. The complete file is parsed before applying scope, so an
invalid record outside the selected subtree still fails the command.
`report_selection` records display-only `cell`, `layer`, and `max_objects`.
JSON has no default object limit. Explicit `--max-changes N` limits the total
number of emitted object occurrences across both sides. Removals precede
additions within each cell. `filtered_cells`, `filtered_objects`,
`limited_objects`, and `emitted_objects` explain evidence selection. `truncated`
is true if filtering or a limit omits any changed cell or object. Library and
layer-name changes, diagnostics, summaries, and the optional graph are retained.
A replacement is emitted only when both linked objects are included.
All aggregate counts, limits, and byte offsets are unsigned decimal **strings**.
This avoids loss of precision in JSON consumers using binary64 numbers.
Coordinates, numeric tags, layer/type pairs, widths, and array dimensions are
bounded integers represented as JSON numbers. Null means absent or unavailable;
zero and empty arrays do not imply absence.
`inputs.old` and `inputs.new` contain input paths, presence, and UNITS fields.
Presence is distinct from an empty library. The Rust API also supports absent
Git revisions using `Document::empty_like`; no units are invented for absent
inputs. Failed reports may have null presence and units. Argument failures can
lack input/selection context because the command could not be parsed.
Paths are UTF-8 when representable. Otherwise `path` is null and
`path_encoded_hex` preserves Rust's platform-native encoded path bytes, prefixed
with `0x`. This is platform-dependent evidence rather than a portable path name.
## Change evidence
`library_changes` records changed header fields as typed before/after arrays.
Library presence changes use the special field `presence`, a null tag, and
boolean before/after values. Units are not rescaled to a common grid.
`layer_name_changes` records numeric pairs with before/after names. A layer
pair is `{ "number": 1, "purpose": 0 }`, where purpose is DATATYPE, TEXTTYPE,
BOXTYPE, or NODETYPE according to the object kind. `layer_legend` contains
unchanged names available in the scope. Embedded annotation labels are excluded
from ordinary object changes. A metadata rename appears once.
Each `cell_changes` entry has its name, nullable before/after cell records,
attribute evidence, removed and added objects, and replacement suggestions.
A null cell side means the cell is absent in that scope. An existing empty
cell has a byte offset and an empty attribute array.
Each object retains:
- Its kind and numeric tag, numeric layer pair, target cell, and coordinate envelope.
- Its original source side and byte range `[byte_offset, end_offset)`.
- Typed field records and the sorted property multiset, including duplicates.
- Convenience fields for text/reference origin, path/text width, and reference
array dimensions. SREF dimensions are `[1, 1]`; the kind and retained fields
distinguish an SREF from a one-element AREF and explicit fields from omission.
Coordinates are cell-local integer database units. `bounds` contains
`[xmin, ymin, xmax, ymax]` of stored coordinates. It excludes path stroke width,
rendered text dimensions, and recursively transformed target geometry.
Equal envelopes do not establish geometric equality. Unit changes must be
considered before deriving physical movements or dimensions.
A retained field has a numeric `tag`, convenience `name`, `encoding`, decoded
`value`, and `payload_hex`. The numeric tag is authoritative; names are display
aids. XY values are arrays of `[x, y]` pairs. Other numeric fields are arrays
of their declared type. Unsupported encodings retain bytes with a null value.
String and property values are null if their bytes are not valid UTF-8;
`payload_hex` always preserves them without replacement characters.
Payloads follow the comparison profile: boundary/box rings use canonical start
and winding, string padding is removed, and fields/properties are sorted. They
are comparison evidence, not a verbatim serialization of the source records.
REAL8 payload encodings are retained exactly alongside their decoded values.
Explicit defaults and omitted fields remain distinct. Source ranges allow raw
record inspection when original encoding or order is needed.
Replacement suggestions link report-local removed/added IDs, with a `match_rule`,
typed `field_changes`, and `properties_changed`. Their explanation is optional
for consumers to display and must not be parsed. Current matching rules are
`unique_kind_layer_bounds`, `unique_kind_layer`, and `unique_kind_target`.
These are explanatory matches, not persistent identity or shape equivalence.
Ambiguous candidates stay independent removals and additions. IDs are unique
within a report and have no meaning across reports.
## Diagnostics and hierarchy
Diagnostics have `code`, `severity`, `message`, input `side`, original byte
offset, cell, layer, and target context. Unknown context is null. Messages are
for display; codes and context support automation. Current limitation codes are
`unsupported_record`, `unsupported_metadata_version`, `unresolved_reference`,
`hierarchy_cycle`, and `scope_mismatch`. Failure codes are `invalid_input`,
`io_error`, `invalid_scope`, and `command_error`. Fatal parser errors currently
retain their location in the human message; their structured byte offset is
null. Consumers must not depend on message wording.
`--hierarchy graph` includes the full scoped union graph of both revisions.
Otherwise `hierarchy` is null. Nodes are keyed by cell name, with per-side
states `included`, `outside_scope`, `unresolved`, or `absent`. Their `change`
is `direct`, `affected` through a descendant, or `unchanged`.
Edges record parent, target, before/after direct placement counts, and whether
the underlying reference records changed. AREF columns times rows contribute
symbolically; arrays are never expanded. Counts are direct edge multiplicities,
not recursively accumulated placements. Shared cells occur once. Removed edges
remain visible, and ancestors are computed over the union of both revisions.
Graph content is independent of display filters and object limits. Text depth
limits and ASCII/Mermaid choices do not apply to JSON graphs.
## Development
`cargo test --test review` checks report semantics, CLI behavior, and versioned
goldens. To intentionally regenerate report goldens after reviewing a contract
change, run:
```sh
PHEON_UPDATE_REPORT_GOLDENS=1 cargo test --test review machine_reports_match_versioned_goldens
```
Schema validators can validate the goldens or actual CLI output against
`diff-report-v1.schema.json`. Schema validation does not replace semantic checks
such as replacement links, summary totals, or status/exit-code agreement.

51
docs/releases.md Normal file
View file

@ -0,0 +1,51 @@
# Building and validating a release
The source archive, Python wheels and standalone CLI are separate artifacts.
Python wheels contain `pheon` and its shared library; Cargo installation contains
the CLI. Neither installation searches for the other.
Build the source archive and then the wheel from that archive:
```sh
python -m pip install build
python -m build
```
The default `build` invocation builds its wheel from the source archive. Both
carry the Cargo version, license and locked dependency resolution. A source build
requires Rust 1.88 or newer. The checkout selects current stable through
`rust-toolchain.toml`; `RUSTUP_TOOLCHAIN=1.88.0` selects the minimum compiler
explicitly for source-package builds. An installed wheel has no Rust runtime
requirement.
The package workflow builds the archive once, then uses cibuildwheel to build
from it and repair wheels for Linux x86-64/ARM64, macOS x86-64/ARM64 and Windows
x86-64. Repair uses the platform tools supplied by cibuildwheel. Wheels must keep
the `py3-none` interpreter/ABI tags and a platform tag, including an appropriate
manylinux tag for Linux releases. Local unrepaired `linux_*` wheels are development
artifacts, not portable Linux releases.
Each repaired wheel is tested on Python 3.11 through 3.14 without rebuilding it.
Tests run in isolated mode against the installed package and bundled library,
including an import that verifies integer packing does not import PyArrow. To
repeat that check locally after installing a wheel and PyArrow:
```sh
python -I /path/to/pheon/tools/check_installed.py
```
Unset `PHEON_LIBRARY` for artifact tests. It exists to select an explicit external
library during development, and version checks apply equally to that library.
The minimum Rust compiler and current stable compiler run native tests in both
debug and release modes. CLI artifacts contain the executable, license, README
and Git integration templates. They are tied to their build OS and architecture.
Workflows upload build artifacts only. They do not publish to PyPI, crates.io,
or a hosted release. The repository URL and checkout directory can be renamed
to `pheon` separately; no remote repository settings are changed by this work.
The project rename provides no Python import shim or old CLI alias. Companion
releases must migrate their imports and dependencies together. The Python C API
version and Arrow layout version are currently 1. CLI reports use schema version
1 and retain the `klamath-object-v2` comparison profile and existing GDS layer-name
metadata marker.

8
pheon/__init__.py Normal file
View file

@ -0,0 +1,8 @@
"""Native GDSII helpers. Install pheon[arrow] for the pheon.arrow readers."""
from ._native import PheonError as PheonError
from .basic import pack_int2 as pack_int2
from .basic import pack_int4 as pack_int4
__version__ = "0.3.0"

53
pheon/_ffi.h Normal file
View file

@ -0,0 +1,53 @@
#ifndef PHEON_H
#define PHEON_H
#include <stdint.h>
#include <stddef.h>
struct ArrowArray {
int64_t length;
int64_t null_count;
int64_t offset;
int64_t n_buffers;
int64_t n_children;
const void **buffers;
struct ArrowArray **children;
struct ArrowArray *dictionary;
void (*release)(struct ArrowArray *);
void *private_data;
};
struct ArrowSchema {
const char *format;
const char *name;
const char *metadata;
int64_t flags;
int64_t n_children;
struct ArrowSchema **children;
struct ArrowSchema *dictionary;
void (*release)(struct ArrowSchema *);
void *private_data;
};
uint32_t pheon_abi_version(void);
uint32_t pheon_arrow_schema_version(void);
int32_t read_path(const char *path, struct ArrowArray *array, struct ArrowSchema *schema);
int32_t read_bytes(const uint8_t *data, size_t size, struct ArrowArray *array, struct ArrowSchema *schema);
int32_t scan_bytes(const uint8_t *data, size_t size, struct ArrowArray *array, struct ArrowSchema *schema);
int32_t read_cells_bytes(const uint8_t *data, size_t size, const uint64_t *ranges, size_t range_count, struct ArrowArray *array, struct ArrowSchema *schema);
const char *last_error_message(void);
double f64_to_i16(double *data, size_t size);
double f64_to_i32(double *data, size_t size);
float f32_to_i16(float *data, size_t size);
float f32_to_i32(float *data, size_t size);
int64_t i64_to_i16(int64_t *data, size_t size);
int64_t i64_to_i32(int64_t *data, size_t size);
int32_t i32_to_i16(int32_t *data, size_t size);
int32_t i32_to_i32(int32_t *data, size_t size);
int16_t i16_to_i16(int16_t *data, size_t size);
uint64_t u64_to_i16(uint64_t *data, size_t size);
uint64_t u64_to_i32(uint64_t *data, size_t size);
uint32_t u32_to_i16(uint32_t *data, size_t size);
uint32_t u32_to_i32(uint32_t *data, size_t size);
uint16_t u16_to_i16(uint16_t *data, size_t size);
#endif

55
pheon/_native.py Normal file
View file

@ -0,0 +1,55 @@
"""Load a bundled or explicitly selected library through its stable C ABI."""
import os
from pathlib import Path
import sys
from cffi import FFI
ffi = FFI()
header = Path(__file__).with_name("_ffi.h").read_text()
ffi.cdef(
"\n".join(line for line in header.splitlines() if not line.lstrip().startswith("#"))
)
if sys.platform == "win32":
filename = "pheon.dll"
elif sys.platform == "darwin":
filename = "libpheon.dylib"
else:
filename = "libpheon.so"
# An explicit override supports source-tree development without copying binaries
# into the package. Installed wheels load only their bundled native library.
library = (
Path(os.environ["PHEON_LIBRARY"]).expanduser()
if "PHEON_LIBRARY" in os.environ
else Path(__file__).with_name(filename)
)
try:
lib = ffi.dlopen(str(library.resolve()))
except OSError as error:
raise ImportError(
f"Could not load Pheon library {library}: {error}. "
"Install a Pheon wheel or set PHEON_LIBRARY to a Cargo-built shared library."
) from error
ABI_VERSION = 1
ARROW_SCHEMA_VERSION = 1
try:
native_abi = lib.pheon_abi_version()
native_schema = lib.pheon_arrow_schema_version()
except AttributeError as error:
raise ImportError(
"The selected library does not expose the Pheon version API"
) from error
if (native_abi, native_schema) != (ABI_VERSION, ARROW_SCHEMA_VERSION):
raise ImportError(
f"Incompatible Pheon library: C ABI {native_abi}, Arrow schema {native_schema}; "
f"expected C ABI {ABI_VERSION}, Arrow schema {ARROW_SCHEMA_VERSION}"
)
class PheonError(ValueError):
"""A native GDSII parse or selection error."""

105
pheon/arrow.py Normal file
View file

@ -0,0 +1,105 @@
"""GDSII readers returning a one-row Arrow StructArray for the library.
The returned arrays own their buffers independently of the input. This module
requires the optional ``arrow`` extra; integer packing does not import PyArrow.
"""
from __future__ import annotations
from collections.abc import Sequence
import gzip
import os
from typing import Any, Callable
import numpy
import pyarrow
from ._native import PheonError, ffi, lib
def _export(call: Callable[[Any, Any], int]) -> pyarrow.StructArray:
array = ffi.new("struct ArrowArray *")
schema = ffi.new("struct ArrowSchema *")
try:
if call(array, schema) != 0:
error = lib.last_error_message()
message = (
ffi.string(error).decode("utf-8", errors="replace")
if error != ffi.NULL
else "GDSII read failed"
)
raise PheonError(message)
# PyArrow consumes the structures, setting their release callbacks to
# null. The finally block also covers failure during import.
return pyarrow.Array._import_from_c(
int(ffi.cast("uintptr_t", array)), int(ffi.cast("uintptr_t", schema))
)
finally:
if array.release != ffi.NULL:
array.release(array)
if schema.release != ffi.NULL:
schema.release(schema)
def read_path(path: str | os.PathLike[str]) -> pyarrow.StructArray:
"""Read a GDSII file, recognizing gzip by its magic bytes."""
filename = os.path.abspath(os.path.expanduser(os.fspath(path)))
with open(filename, "rb") as stream:
compressed = stream.read(2) == b"\x1f\x8b"
if compressed:
stream.seek(0)
with gzip.GzipFile(fileobj=stream) as source:
return read_bytes(source.read())
# The native Windows path API accepts UTF-8; Unix accepts filesystem bytes.
encoded = filename.encode("utf-8") if os.name == "nt" else os.fsencode(filename)
return _export(lambda array, schema: lib.read_path(encoded, array, schema))
def _read_buffer(
buffer: Any, call: Callable[[Any, int, Any, Any], int]
) -> pyarrow.StructArray:
with memoryview(buffer) as view:
if not view.c_contiguous:
raise ValueError("GDSII input must be a contiguous buffer")
with ffi.from_buffer("const uint8_t[]", view) as data:
return _export(lambda array, schema: call(data, view.nbytes, array, schema))
def read_bytes(buffer: Any) -> pyarrow.StructArray:
"""Read a complete GDSII library from a contiguous borrowed byte buffer."""
return _read_buffer(buffer, lib.read_bytes)
def scan_bytes(buffer: Any) -> pyarrow.StructArray:
"""Scan metadata, cell byte ranges and references without decoding geometry."""
return _read_buffer(buffer, lib.scan_bytes)
def read_cells_bytes(
buffer: Any, ranges: Sequence[Sequence[int]] | numpy.ndarray
) -> pyarrow.StructArray:
"""Read complete cells in the requested order from half-open byte ranges.
``ranges`` has shape (N, 2) and unsigned 64-bit integer offsets. Signed
integer inputs are accepted after checking that every offset is nonnegative.
An empty sequence requests metadata with no cells.
"""
values = numpy.asarray(ranges)
if values.shape == (0,):
values = numpy.empty((0, 2), dtype=numpy.uint64)
if values.ndim != 2 or values.shape[1] != 2:
raise ValueError("Cell ranges must have shape (N, 2)")
if values.dtype.kind not in "iu":
raise TypeError("Cell offsets must be integers")
if values.dtype.kind == "i" and numpy.any(values < 0):
raise ValueError("Cell offsets must be nonnegative")
values = numpy.require(
values, dtype=numpy.uint64, requirements=("C_CONTIGUOUS", "ALIGNED")
)
with ffi.from_buffer("const uint64_t[]", values) as offsets:
return _read_buffer(
buffer,
lambda data, size, array, schema: lib.read_cells_bytes(
data, size, offsets, len(values), array, schema
),
)

72
pheon/basic.py Normal file
View file

@ -0,0 +1,72 @@
from collections.abc import Sequence
from typing import Any
import numpy
from numpy.typing import NDArray
from ._native import lib, ffi
CONV_TABLE_i16 = {
numpy.float64: lib.f64_to_i16,
numpy.float32: lib.f32_to_i16,
numpy.int64: lib.i64_to_i16,
numpy.int32: lib.i32_to_i16,
numpy.int16: lib.i16_to_i16,
numpy.uint64: lib.u64_to_i16,
numpy.uint32: lib.u32_to_i16,
numpy.uint16: lib.u16_to_i16,
}
CONV_TABLE_i32 = {
numpy.float64: lib.f64_to_i32,
numpy.float32: lib.f32_to_i32,
numpy.int64: lib.i64_to_i32,
numpy.int32: lib.i32_to_i32,
numpy.uint64: lib.u64_to_i32,
numpy.uint32: lib.u32_to_i32,
}
def _pack_int(
data: NDArray[numpy.integer] | Sequence[int] | int,
width: int,
converters: dict[type[numpy.generic], Any],
) -> bytes:
arr = numpy.atleast_1d(data)
target_dtype = numpy.dtype(f">i{width}")
for dtype, convert in converters.items():
if arr.dtype != dtype:
continue
arr = numpy.require(
arr, requirements=("C_CONTIGUOUS", "ALIGNED", "WRITEABLE", "OWNDATA")
)
if arr is data:
arr = numpy.array(arr, copy=True)
with ffi.from_buffer(
ffi.typeof(convert).args[0], arr, require_writable=True
) as buf:
result = convert(buf, arr.size)
if result != 0:
raise ValueError(f"Invalid value for conversion to Int{width}: {result}")
return arr.reshape(-1).view(target_dtype)[:: arr.itemsize // width].tobytes()
if arr.dtype == target_dtype:
return arr.tobytes()
limit = 1 << (width * 8 - 1)
if (arr > limit - 1).any() or (arr < -limit).any():
raise Exception(f"int{width} data out of range: {arr}")
return arr.astype(target_dtype).tobytes()
def pack_int2(data: NDArray[numpy.integer] | Sequence[int] | int) -> bytes:
return _pack_int(data, 2, CONV_TABLE_i16)
def pack_int4(data: NDArray[numpy.integer] | Sequence[int] | int) -> bytes:
return _pack_int(data, 4, CONV_TABLE_i32)

0
pheon/py.typed Normal file
View file

Some files were not shown because too many files have changed in this diff Show more