warpsz 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
warpsz/__init__.py ADDED
@@ -0,0 +1,38 @@
1
+ """Error-bounded, seam-free lossy compression of registration displacement fields.
2
+
3
+ The format is the `warpsz` codec: one array (a "chunk") per encoded buffer,
4
+ with a per-sample error bound, a tighter bound on the chunk faces (so errors do
5
+ not jump across chunk boundaries) and, optionally, preserved Jacobian
6
+ determinants. Nothing here depends on zarr:
7
+
8
+ - `encode` / `decode` code one array;
9
+ - `encode_tiles` / `decode_tiles` code a large array tile by tile, into and out
10
+ of any mapping (a dict, a directory, a database, ...);
11
+ - `zarr-warpsz` registers the same format as a zarr v3 codec.
12
+
13
+ The Rust implementation (`warpsz-rs`) is used automatically when installed;
14
+ it produces identical streams and bit-identical decoded values.
15
+ """
16
+
17
+ from warpsz.core import (
18
+ Config,
19
+ JacobianConfig,
20
+ WarpSZSpecError,
21
+ decode,
22
+ encode,
23
+ )
24
+ from warpsz.format import WarpSZFormatError
25
+ from warpsz.tiles import TileIndex, decode_tiles, encode_tiles, tile_grid
26
+
27
+ __all__ = [
28
+ "Config",
29
+ "JacobianConfig",
30
+ "TileIndex",
31
+ "WarpSZFormatError",
32
+ "WarpSZSpecError",
33
+ "decode",
34
+ "decode_tiles",
35
+ "encode",
36
+ "encode_tiles",
37
+ "tile_grid",
38
+ ]
warpsz/_backend.py ADDED
@@ -0,0 +1,40 @@
1
+ """Choose between the Rust extension (`warpsz_rs`) and the numpy reference.
2
+
3
+ Both produce identical code streams and bit-identical decoded values. The Rust
4
+ backend is used automatically when the extension is installed
5
+ (`pip install warpsz-rs`, or `warpsz[fast]`); set
6
+ `WARPSZ_BACKEND=python` to force the reference, or pass `backend=` to
7
+ `encode` / `decode`. (`WARPFIELD_BACKEND` and `ZARR_WARPFIELD_BACKEND` are still
8
+ read, for older setups.)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+
15
+ try: # pragma: no cover - depends on the environment
16
+ import warpsz_rs as rs
17
+ except ImportError: # pragma: no cover
18
+ rs = None
19
+
20
+ BACKENDS = ("auto", "rust", "python")
21
+
22
+
23
+ def available() -> bool:
24
+ return rs is not None
25
+
26
+
27
+ def resolve(backend: str | None) -> str:
28
+ b = (
29
+ backend
30
+ or os.environ.get("WARPSZ_BACKEND")
31
+ or os.environ.get("WARPFIELD_BACKEND")
32
+ or os.environ.get("ZARR_WARPFIELD_BACKEND", "auto")
33
+ )
34
+ if b not in BACKENDS:
35
+ raise ValueError(f"backend must be one of {BACKENDS}, not {b!r}")
36
+ if b == "auto":
37
+ return "rust" if rs is not None else "python"
38
+ if b == "rust" and rs is None:
39
+ raise ImportError("the Rust backend needs the warpsz-rs package")
40
+ return b
warpsz/adversary.py ADDED
@@ -0,0 +1,139 @@
1
+ """An adversarial field for the Jacobian guarantee across chunk faces.
2
+
3
+ Every chunk is easy on its own: inside a chunk the field is smooth. All the
4
+ difficulty sits on the cells that straddle chunk faces, which two chunks code
5
+ independently.
6
+
7
+ - On every chunk face (between samples kT - 1 and kT along axis a) the normal
8
+ component steps, so that a straddling cell's normal derivative, and with it
9
+ its det J, is a prescribed d. Along the face d sweeps smoothly,
10
+ d = level + A sin(...), so every margin from -A to +A occurs. The step only
11
+ shifts the rest of the array by a slowly varying amount, so chunks stay
12
+ smooth inside.
13
+ - A is given in units of g = 2 * face_error_bound / spacing, the largest change
14
+ of a straddling cell's normal derivative that face-bound errors on both sides
15
+ can cause. Cells within ~1 g of a threshold can be broken by the two chunks'
16
+ ordinary quantization errors.
17
+ - Each face gets one level: `min_det` (cells just above it must stay above it;
18
+ those just below must stay positive), zero (cells just above must not fold;
19
+ those just below are folded and must stay folded), or a safe control.
20
+ - Where faces of two or three axes meet, the factors multiply, so the cells
21
+ shared by 4 or 8 chunks are hit too.
22
+ - A smooth tangential slip across every face adds off-diagonal Jacobian terms.
23
+ They leave det J unchanged but enlarge the worst-case bound, which shows how
24
+ conservative that bound is.
25
+ - Hash noise of `noise * error_bound` decorrelates the quantization errors of
26
+ neighbouring face samples. It moves a straddling cell's det J by up to
27
+ 4 * noise * g / (4 * face_error_bound / error_bound), so keep it small.
28
+
29
+ The field is an analytic function of global sample coordinates, like
30
+ `warpsz.synth`, but it targets one chunking: the faces of `chunks`.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import numpy as np
36
+
37
+ from warpsz.synth import _hash_noise
38
+
39
+ CATEGORIES = {
40
+ 0: "inside a chunk",
41
+ 1: "above min_det, must stay above",
42
+ 2: "in (0, min_det], must stay positive",
43
+ 3: "folded, must stay folded",
44
+ 4: "safe control",
45
+ 5: "chunk edge or corner (2-3 faces)",
46
+ }
47
+ LEVELS = ("min_det", "zero", "safe")
48
+
49
+
50
+ def _face_level(a: int, kf: int, seed: int) -> str:
51
+ h = _hash_noise(np.array([a]), np.array([kf]), seed=seed)[0]
52
+ return LEVELS[int(np.floor((h + 1.0) * 1.5)) % 3]
53
+
54
+
55
+ def _face_det(a, kf, tang, period, amp, min_det, seed):
56
+ level = {"min_det": min_det, "zero": 0.0, "safe": 0.5 + min_det}[_face_level(a, kf, seed)]
57
+ ph = np.pi * (_hash_noise(np.array([a]), np.array([kf]), seed=seed + 1)[0] + 1.0)
58
+ t = sum(x / (period * (1.0 + 0.37 * i)) for i, x in enumerate(tang))
59
+ return level + amp * np.sin(2.0 * np.pi * t + ph)
60
+
61
+
62
+ def chunk_face_adversary(
63
+ shape: tuple[int, ...],
64
+ chunks: tuple[int, ...],
65
+ *,
66
+ spacing: float = 4.0,
67
+ error_bound: float = 0.25,
68
+ face_error_bound: float | None = None,
69
+ min_det: float = 0.1,
70
+ amplitude: float = 4.0,
71
+ period: float = 24.0,
72
+ shear: float = 0.3,
73
+ noise: float = 0.05,
74
+ seed: int = 0,
75
+ ):
76
+ """(u, labels, target).
77
+
78
+ `u` has shape (*shape, k), float32, component c along spatial axis c.
79
+ `labels` (cell shape: one less along each axis) is the category of every
80
+ cell, and `target` its designed det J (NaN inside chunks). `amplitude` is
81
+ in units of g.
82
+ """
83
+ k = len(shape)
84
+ if len(chunks) != k:
85
+ raise ValueError("chunks must give one extent per spatial axis")
86
+ eps_face = error_bound / 4 if face_error_bound is None else face_error_bound
87
+ amp = amplitude * 2.0 * eps_face / spacing
88
+ idx = np.meshgrid(*(np.arange(n) for n in shape), indexing="ij")
89
+
90
+ u = np.zeros((*shape, k), dtype=np.float64)
91
+ # smooth background: |du/dx| <~ 0.005, so interior cells have det J ~ 1
92
+ for c in range(k):
93
+ for a in range(k):
94
+ L = 40.0 + 13.0 * ((a + 2 * c) % 3)
95
+ u[..., c] += 0.03 * spacing * np.sin(2 * np.pi * idx[a] / L + c)
96
+ for a in range(k):
97
+ T = chunks[a]
98
+ tang = [idx[b] for b in range(k) if b != a]
99
+ for kf in range(1, -(-shape[a] // T)):
100
+ past = idx[a] >= kf * T
101
+ d = _face_det(a, kf, tang, period, amp, min_det, seed)
102
+ u[..., a] += np.where(past, (d - 1.0) * spacing, 0.0)
103
+ for b in range(k):
104
+ if b == a:
105
+ continue
106
+ # varies only along the third axis (if any), so it adds J[b][c]
107
+ # terms but never changes the diagonal
108
+ others = [idx[c] for c in range(k) if c not in (a, b)]
109
+ phase = 2 * np.pi * others[0] / (1.7 * period) if others else 0.0
110
+ slip = shear * spacing * np.cos(phase + kf + b)
111
+ u[..., b] += np.where(past, slip, 0.0)
112
+ u += (
113
+ noise
114
+ * error_bound
115
+ * np.stack([_hash_noise(*idx, seed=seed + 7 + c) for c in range(k)], axis=-1)
116
+ )
117
+
118
+ cells = tuple(n - 1 for n in shape)
119
+ cidx = np.meshgrid(*(np.arange(n) for n in cells), indexing="ij")
120
+ labels = np.zeros(cells, dtype=np.int8)
121
+ target = np.full(cells, np.nan)
122
+ hits = np.zeros(cells, dtype=np.int8)
123
+ for a in range(k):
124
+ T = chunks[a]
125
+ tang = [cidx[b] for b in range(k) if b != a]
126
+ for kf in range(1, -(-shape[a] // T)):
127
+ on = cidx[a] == kf * T - 1
128
+ d = _face_det(a, kf, tang, period, amp, min_det, seed)
129
+ level = _face_level(a, kf, seed)
130
+ cat = np.where(
131
+ level == "safe",
132
+ 4,
133
+ np.where(d > min_det, 1, np.where(d > 0, 2, 3)),
134
+ )
135
+ labels = np.where(on, cat, labels)
136
+ target = np.where(on, np.where(np.isnan(target), d, target * d), target)
137
+ hits += on
138
+ labels = np.where(hits > 1, 5, labels).astype(np.int8)
139
+ return u.astype(np.float32), labels, target
warpsz/chunked.py ADDED
@@ -0,0 +1,71 @@
1
+ """Encode and decode a whole array chunk by chunk, without zarr.
2
+
3
+ Edge chunks are padded the way zarr pads them (with `fill_value`), so sizes and
4
+ errors match what a zarr array with this codec stores.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import itertools
10
+ import time
11
+ from dataclasses import dataclass
12
+
13
+ import numpy as np
14
+
15
+ from warpsz.core import Config, decode, encode
16
+
17
+
18
+ @dataclass
19
+ class ChunkedResult:
20
+ decoded: np.ndarray
21
+ classes: np.ndarray # per-sample error class (0 interior, 1 face, 2 tight, 3 verbatim)
22
+ nbytes: int
23
+ n_chunks: int
24
+ jacobian_rounds: int
25
+ encode_seconds: float = 0.0
26
+ decode_seconds: float = 0.0
27
+
28
+ def ratio(self, original: np.ndarray) -> float:
29
+ return original.nbytes / self.nbytes
30
+
31
+
32
+ def chunk_slices(shape: tuple[int, ...], chunks: tuple[int, ...]):
33
+ for idx in itertools.product(
34
+ *[range(-(-s // c)) for s, c in zip(shape, chunks, strict=True)]
35
+ ):
36
+ yield tuple(
37
+ slice(i * c, min((i + 1) * c, s))
38
+ for i, c, s in zip(idx, chunks, shape, strict=True)
39
+ )
40
+
41
+
42
+ def roundtrip(
43
+ arr: np.ndarray,
44
+ chunks: tuple[int, ...],
45
+ cfg: Config,
46
+ fill_value: float = 0.0,
47
+ schedule: tuple[float, float] | None = None,
48
+ effort: str = "fast",
49
+ ):
50
+ out = np.empty_like(arr)
51
+ cls = np.empty(arr.shape, dtype=np.uint8)
52
+ total = 0
53
+ n = 0
54
+ rounds = 0
55
+ te = td = 0.0
56
+ for sl in chunk_slices(arr.shape, chunks):
57
+ block = np.full(chunks, fill_value, dtype=arr.dtype)
58
+ inner = tuple(slice(0, s.stop - s.start) for s in sl)
59
+ block[inner] = arr[sl]
60
+ t0 = time.perf_counter()
61
+ buf, st, c = encode(block, cfg, stats=True, schedule=schedule, effort=effort)
62
+ t1 = time.perf_counter()
63
+ dec = decode(buf, chunks, arr.dtype, cfg)
64
+ te += t1 - t0
65
+ td += time.perf_counter() - t1
66
+ out[sl] = dec[inner]
67
+ cls[sl] = c[inner]
68
+ total += len(buf)
69
+ n += 1
70
+ rounds = max(rounds, st.jacobian_rounds)
71
+ return ChunkedResult(out, cls, total, n, rounds, te, td)