rahuketu 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ permissions:
11
+ id-token: write
12
+ contents: read
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: "3.12"
18
+ - name: Build distributions
19
+ run: |
20
+ python -m pip install --upgrade build
21
+ python -m build
22
+ - name: Publish to PyPI
23
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,12 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .eggs/
5
+ build/
6
+ dist/
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ .venv/
10
+ venv/
11
+ *.onnx
12
+ *.pt
@@ -0,0 +1,14 @@
1
+ cff-version: 1.2.0
2
+ message: "If you use this software, please cite it as below."
3
+ title: "rahuketu: a zero-free encoding framework"
4
+ authors:
5
+ - family-names: Ramakrishnan
6
+ email: human@setc.dev
7
+ orcid: "https://orcid.org/0009-0006-0905-7275"
8
+ version: 0.1.0
9
+ license: Apache-2.0
10
+ repository-code: "https://github.com/DecipherPunk/rahuketu"
11
+ keywords:
12
+ - encoding
13
+ - bijective-numeration
14
+ - arithmetic-coding
rahuketu-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Ramakrishnan
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
rahuketu-0.1.0/NOTICE ADDED
@@ -0,0 +1,14 @@
1
+ rahuketu
2
+ Copyright 2026 Ramakrishnan
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Original Rahu-Ketu software framing and implementation by Ramakrishnan. This
11
+ package uses classical signed and bijective numeration and arithmetic coding
12
+ inside a zero-free log-space API. Those underlying methods are not claimed as
13
+ new. The specific Rahu-Ketu framing and this implementation are original. No
14
+ third-party source code is included.
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: rahuketu
3
+ Version: 0.1.0
4
+ Summary: Zero-free encoding framework: signed bijective numeration (Rahu) and arithmetic coding (Ketu).
5
+ Project-URL: Homepage, https://github.com/DecipherPunk/rahuketu
6
+ Author-email: Ramakrishnan <human@setc.dev>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: arithmetic-coding,bijective-numeration,encoding,rahuketu
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Scientific/Engineering
13
+ Requires-Python: >=3.10
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest; extra == 'dev'
16
+ Requires-Dist: ruff; extra == 'dev'
17
+ Description-Content-Type: text/markdown
18
+
19
+ # rahuketu
20
+
21
+ rahuketu is a small zero-free encoding package. It combines a signed bijective
22
+ number path (Rahu) with an arithmetic-coding path (Ketu), and records both as a
23
+ log-space trace. Pure Python, no dependencies.
24
+
25
+ ## Install
26
+
27
+ ```
28
+ pip install rahuketu
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ ```python
34
+ from rahuketu import Alphabet, roundtrip, trace
35
+
36
+ ab = Alphabet.lowercase()
37
+
38
+ r = roundtrip("hello", ab)
39
+ assert r["agrees"] # encode -> decode is lossless
40
+
41
+ steps = trace("hello", ab)
42
+ last = steps[-1]
43
+ print(last.tau, last.upsilon, last.redundancy)
44
+ ```
45
+
46
+ ## Components
47
+
48
+ - `Alphabet` - no-zero symbol/digit mapping (digits in `[1, b]`).
49
+ - `Rahu` - signed bijective numeration (`RahuState`, `rahu_encode`, `rahu_decode`).
50
+ - `Ketu` - arithmetic coding as `(midpoint, scale)` (`KetuState`, `ketu_encode`, `ketu_decode`).
51
+ - `trace` - records `(tau, upsilon, a)` over the input.
52
+ - `roundtrip` - checks lossless encode/decode.
53
+
54
+ ## Provenance / AI assistance
55
+
56
+ Built by Ramakrishnan (ORCID 0009-0006-0905-7275). Signed and bijective
57
+ numeration and arithmetic coding are classical methods. The zero-free Rahu-Ketu
58
+ framing and this implementation are original. AI tools helped with tests,
59
+ automation, and QA. The idea and direction are the author's.
60
+
61
+ ## License
62
+
63
+ Apache-2.0. See `LICENSE` and `NOTICE`.
@@ -0,0 +1,45 @@
1
+ # rahuketu
2
+
3
+ rahuketu is a small zero-free encoding package. It combines a signed bijective
4
+ number path (Rahu) with an arithmetic-coding path (Ketu), and records both as a
5
+ log-space trace. Pure Python, no dependencies.
6
+
7
+ ## Install
8
+
9
+ ```
10
+ pip install rahuketu
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```python
16
+ from rahuketu import Alphabet, roundtrip, trace
17
+
18
+ ab = Alphabet.lowercase()
19
+
20
+ r = roundtrip("hello", ab)
21
+ assert r["agrees"] # encode -> decode is lossless
22
+
23
+ steps = trace("hello", ab)
24
+ last = steps[-1]
25
+ print(last.tau, last.upsilon, last.redundancy)
26
+ ```
27
+
28
+ ## Components
29
+
30
+ - `Alphabet` - no-zero symbol/digit mapping (digits in `[1, b]`).
31
+ - `Rahu` - signed bijective numeration (`RahuState`, `rahu_encode`, `rahu_decode`).
32
+ - `Ketu` - arithmetic coding as `(midpoint, scale)` (`KetuState`, `ketu_encode`, `ketu_decode`).
33
+ - `trace` - records `(tau, upsilon, a)` over the input.
34
+ - `roundtrip` - checks lossless encode/decode.
35
+
36
+ ## Provenance / AI assistance
37
+
38
+ Built by Ramakrishnan (ORCID 0009-0006-0905-7275). Signed and bijective
39
+ numeration and arithmetic coding are classical methods. The zero-free Rahu-Ketu
40
+ framing and this implementation are original. AI tools helped with tests,
41
+ automation, and QA. The idea and direction are the author's.
42
+
43
+ ## License
44
+
45
+ Apache-2.0. See `LICENSE` and `NOTICE`.
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "rahuketu"
7
+ version = "0.1.0"
8
+ description = "Zero-free encoding framework: signed bijective numeration (Rahu) and arithmetic coding (Ketu)."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Ramakrishnan", email = "human@setc.dev" }]
14
+ keywords = ["encoding", "bijective-numeration", "arithmetic-coding", "rahuketu"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Intended Audience :: Science/Research",
18
+ "Topic :: Scientific/Engineering",
19
+ ]
20
+ dependencies = []
21
+
22
+ [project.optional-dependencies]
23
+ dev = ["pytest", "ruff"]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/DecipherPunk/rahuketu"
27
+
28
+ [tool.hatch.build.targets.wheel]
29
+ packages = ["src/rahuketu"]
30
+
31
+ [tool.ruff]
32
+ line-length = 100
@@ -0,0 +1,6 @@
1
+ iniconfig==2.3.0
2
+ packaging==26.2
3
+ pluggy==1.6.0
4
+ Pygments==2.20.0
5
+ pytest==9.1.1
6
+ ruff==0.15.18
@@ -0,0 +1,26 @@
1
+ """RahuKetu: a zero-free encoding framework.
2
+
3
+ Signed bijective numeration (Rahu, ascending) and arithmetic coding
4
+ (Ketu, descending), unified by a (tau, upsilon, a) log-space trajectory.
5
+ """
6
+
7
+ from .alphabet import Alphabet
8
+ from .ketu import KetuState, cdf, ketu_decode, ketu_encode
9
+ from .rahu import RahuState, rahu_decode, rahu_encode
10
+ from .trace import Step, roundtrip, trace
11
+
12
+ __version__ = "0.1.0"
13
+
14
+ __all__ = [
15
+ "Alphabet",
16
+ "RahuState",
17
+ "rahu_encode",
18
+ "rahu_decode",
19
+ "KetuState",
20
+ "ketu_encode",
21
+ "ketu_decode",
22
+ "cdf",
23
+ "Step",
24
+ "trace",
25
+ "roundtrip",
26
+ ]
@@ -0,0 +1,28 @@
1
+ """No-zero alphabet: maps symbols to digits in [1, b]."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Iterable
6
+
7
+
8
+ class Alphabet:
9
+ def __init__(self, symbols: Iterable[str]):
10
+ syms = list(symbols)
11
+ if not syms:
12
+ raise ValueError("alphabet cannot be empty")
13
+ if len(set(syms)) != len(syms):
14
+ raise ValueError("alphabet symbols must be unique")
15
+ self.symbols = syms
16
+ self.b = len(syms)
17
+ self._to_digit = {s: i + 1 for i, s in enumerate(syms)}
18
+ self._to_symbol = {i + 1: s for i, s in enumerate(syms)}
19
+
20
+ def to_digits(self, s: str) -> list[int]:
21
+ return [self._to_digit[c] for c in s]
22
+
23
+ def from_digits(self, digits: Iterable[int]) -> str:
24
+ return "".join(self._to_symbol[d] for d in digits)
25
+
26
+ @classmethod
27
+ def lowercase(cls) -> "Alphabet":
28
+ return cls([chr(ord("a") + i) for i in range(26)])
@@ -0,0 +1,97 @@
1
+ """Ketu: descending arithmetic coding as (midpoint, scale). Zero-free interval."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from fractions import Fraction
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class KetuState:
12
+ midpoint: Fraction
13
+ scale: Fraction
14
+
15
+ @classmethod
16
+ def initial(cls) -> "KetuState":
17
+ return cls(midpoint=Fraction(1, 2), scale=Fraction(1))
18
+
19
+ def step(self, digit: int, table: list[Fraction]) -> "KetuState":
20
+ if not (1 <= digit < len(table)):
21
+ raise ValueError(f"digit {digit} outside [1,{len(table) - 1}]")
22
+ w = self.scale
23
+ low = self.midpoint - w / 2
24
+ new_low = low + w * table[digit - 1]
25
+ new_scale = w * (table[digit] - table[digit - 1])
26
+ new_midpoint = new_low + new_scale / 2
27
+ return KetuState(midpoint=new_midpoint, scale=new_scale)
28
+
29
+ @property
30
+ def low(self) -> Fraction:
31
+ return self.midpoint - self.scale / 2
32
+
33
+ @property
34
+ def high(self) -> Fraction:
35
+ return self.midpoint + self.scale / 2
36
+
37
+ @property
38
+ def width(self) -> Fraction:
39
+ return self.scale
40
+
41
+ @property
42
+ def upsilon(self) -> float:
43
+ """Shrink-as-growth coordinate: -log2 of scale. Finite, positive after step 1.
44
+
45
+ Computed as log2(den) - log2(num) on the exact Fraction. math.log2 accepts
46
+ big ints, so this stays valid for long sequences where float(scale) would
47
+ underflow to 0.0 (and -log2(0.0) is undefined)."""
48
+ return math.log2(self.scale.denominator) - math.log2(self.scale.numerator)
49
+
50
+
51
+ def cdf(probs: list[Fraction]) -> list[Fraction]:
52
+ out = [Fraction(0)] * (len(probs) + 1)
53
+ for i, p in enumerate(probs):
54
+ if p <= 0:
55
+ raise ValueError("probabilities must be strictly positive (no zero)")
56
+ out[i + 1] = out[i] + p
57
+ if out[-1] != 1:
58
+ raise ValueError(f"probabilities must sum to 1, got {out[-1]}")
59
+ return out
60
+
61
+
62
+ def ketu_encode(digits: list[int], probs: list[Fraction], sigma: int = +1) -> KetuState:
63
+ """Encode digits into a Ketu interval. sigma=-1 processes right-to-left."""
64
+ if sigma not in (-1, +1):
65
+ raise ValueError("sigma must be +1 or -1 (no zero)")
66
+ table = cdf(probs)
67
+ b = len(probs)
68
+ stream = digits if sigma == +1 else list(reversed(digits))
69
+ state = KetuState.initial()
70
+ for d in stream:
71
+ if not (1 <= d <= b):
72
+ raise ValueError(f"digit {d} outside [1,{b}]")
73
+ state = state.step(d, table)
74
+ return state
75
+
76
+
77
+ def ketu_decode(point: Fraction, length: int, probs: list[Fraction], sigma: int = +1) -> list[int]:
78
+ """Recover digits in original order from a point inside the interval."""
79
+ if sigma not in (-1, +1):
80
+ raise ValueError("sigma must be +1 or -1 (no zero)")
81
+ table = cdf(probs)
82
+ b = len(probs)
83
+ state = KetuState.initial()
84
+ decoded: list[int] = []
85
+ for _ in range(length):
86
+ w = state.scale
87
+ low = state.low
88
+ for d in range(1, b + 1):
89
+ lo_d = low + w * table[d - 1]
90
+ hi_d = low + w * table[d]
91
+ if lo_d <= point < hi_d:
92
+ decoded.append(d)
93
+ state = state.step(d, table)
94
+ break
95
+ else:
96
+ raise ValueError(f"point {point} outside the current interval")
97
+ return decoded if sigma == +1 else list(reversed(decoded))
@@ -0,0 +1,71 @@
1
+ """Rahu: ascending signed bijective numeration. Zero-free integer state."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class RahuState:
11
+ magnitude: int
12
+ sigma: int
13
+ length: int
14
+
15
+ @classmethod
16
+ def seed(cls, digit: int, sigma: int) -> "RahuState":
17
+ if sigma not in (-1, +1):
18
+ raise ValueError("sigma must be +1 or -1 (no zero)")
19
+ if digit < 1:
20
+ raise ValueError("digit must be >= 1 (no zero)")
21
+ return cls(magnitude=digit, sigma=sigma, length=1)
22
+
23
+ def step(self, digit: int, b: int) -> "RahuState":
24
+ if not (1 <= digit <= b):
25
+ raise ValueError(f"digit {digit} outside [1,{b}]")
26
+ return RahuState(
27
+ magnitude=self.magnitude * b + digit,
28
+ sigma=self.sigma,
29
+ length=self.length + 1,
30
+ )
31
+
32
+ @property
33
+ def signed_value(self) -> int:
34
+ return self.sigma * self.magnitude
35
+
36
+ @property
37
+ def tau(self) -> float:
38
+ """Growth coordinate: log2 of magnitude. Finite, strictly positive."""
39
+ return math.log2(self.magnitude)
40
+
41
+
42
+ def rahu_encode(digits: list[int], b: int, sigma: int = +1) -> int:
43
+ if b < 1:
44
+ raise ValueError("base must be >= 1")
45
+ if not digits:
46
+ raise ValueError("empty string has no bijective encoding")
47
+ for d in digits:
48
+ if not (1 <= d <= b):
49
+ raise ValueError(f"digit {d} outside [1,{b}]")
50
+ state = RahuState.seed(digits[0], sigma)
51
+ for d in digits[1:]:
52
+ state = state.step(d, b)
53
+ return state.signed_value
54
+
55
+
56
+ def rahu_decode(n: int, b: int) -> tuple[list[int], int]:
57
+ if b < 1:
58
+ raise ValueError("base must be >= 1")
59
+ if n == 0:
60
+ raise ValueError("0 is not in the image of rahu_encode")
61
+ sigma = 1 if n > 0 else -1
62
+ x = abs(n)
63
+ digits: list[int] = []
64
+ while x > 0:
65
+ x, r = divmod(x, b)
66
+ if r == 0: # bijective base-b: remainder 0 maps to digit b, borrow 1
67
+ r = b
68
+ x -= 1
69
+ digits.append(r)
70
+ digits.reverse()
71
+ return digits, sigma
@@ -0,0 +1,135 @@
1
+ """Compound map: the (tau, upsilon, a) log-space trajectory and roundtrip."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from fractions import Fraction
8
+
9
+ from .alphabet import Alphabet
10
+ from .ketu import KetuState, cdf, ketu_decode, ketu_encode
11
+ from .rahu import RahuState, rahu_decode, rahu_encode
12
+
13
+
14
+ @dataclass
15
+ class Step:
16
+ k: int
17
+ symbol: str
18
+ digit: int
19
+ rahu_value: int
20
+ tau: float
21
+ upsilon: float
22
+ a: float
23
+ ketu_midpoint: Fraction
24
+ ketu_scale: Fraction
25
+
26
+ @property
27
+ def ketu_low(self) -> Fraction:
28
+ return self.ketu_midpoint - self.ketu_scale / 2
29
+
30
+ @property
31
+ def ketu_high(self) -> Fraction:
32
+ return self.ketu_midpoint + self.ketu_scale / 2
33
+
34
+ @property
35
+ def ketu_width(self) -> Fraction:
36
+ return self.ketu_scale
37
+
38
+ @property
39
+ def redundancy(self) -> float:
40
+ """tau - upsilon: cumulative redundancy of bijective vs arithmetic coding."""
41
+ return self.tau - self.upsilon
42
+
43
+
44
+ def trace(
45
+ s: str,
46
+ alphabet: Alphabet,
47
+ probs: list[Fraction] | None = None,
48
+ sigma_rahu: int = +1,
49
+ sigma_ketu: int = +1,
50
+ ) -> list[Step]:
51
+ """Per-step (tau, upsilon, a) trajectory.
52
+
53
+ Rahu always advances in forward string order, so each Step's symbol/digit/
54
+ rahu_value/tau are forward-indexed. With sigma_ketu=-1 the Ketu stream is
55
+ processed in reverse, so that step's a (info term) and upsilon refer to the
56
+ reverse-order position, NOT the same original index as the Rahu fields. With
57
+ the default sigma_ketu=+1 the two align.
58
+ """
59
+ if sigma_rahu not in (-1, +1) or sigma_ketu not in (-1, +1):
60
+ raise ValueError("sigmas must be +1 or -1 (no zero)")
61
+ if not s:
62
+ raise ValueError("empty string has no trajectory")
63
+ digits = alphabet.to_digits(s)
64
+ b = alphabet.b
65
+ if probs is None:
66
+ probs = [Fraction(1, b)] * b
67
+ if len(probs) != b:
68
+ raise ValueError("probs length must match alphabet size")
69
+ table = cdf(probs)
70
+
71
+ ketu_stream = digits if sigma_ketu == +1 else list(reversed(digits))
72
+ rahu = RahuState.seed(digits[0], sigma_rahu)
73
+ ketu = KetuState.initial().step(ketu_stream[0], table)
74
+ log2_b = math.log2(b)
75
+
76
+ def info(digit: int) -> float:
77
+ return -math.log2(float(probs[digit - 1])) / log2_b
78
+
79
+ def snapshot(k: int, sym: str, d_rahu: int, d_ketu: int) -> Step:
80
+ return Step(
81
+ k=k,
82
+ symbol=sym,
83
+ digit=d_rahu,
84
+ rahu_value=rahu.signed_value,
85
+ tau=rahu.tau,
86
+ upsilon=ketu.upsilon,
87
+ a=info(d_ketu),
88
+ ketu_midpoint=ketu.midpoint,
89
+ ketu_scale=ketu.scale,
90
+ )
91
+
92
+ steps = [snapshot(1, s[0], digits[0], ketu_stream[0])]
93
+ for k, ((sym, d_rahu), d_ketu) in enumerate(
94
+ zip(zip(s[1:], digits[1:]), ketu_stream[1:]), start=2
95
+ ):
96
+ rahu = rahu.step(d_rahu, b)
97
+ ketu = ketu.step(d_ketu, table)
98
+ steps.append(snapshot(k, sym, d_rahu, d_ketu))
99
+ return steps
100
+
101
+
102
+ def roundtrip(
103
+ s: str,
104
+ alphabet: Alphabet,
105
+ probs: list[Fraction] | None = None,
106
+ sigma_rahu: int = +1,
107
+ sigma_ketu: int = +1,
108
+ ) -> dict:
109
+ digits = alphabet.to_digits(s)
110
+ b = alphabet.b
111
+
112
+ n = rahu_encode(digits, b, sigma=sigma_rahu)
113
+ rahu_digits, sigma_back = rahu_decode(n, b)
114
+ rahu_s = alphabet.from_digits(rahu_digits)
115
+
116
+ if probs is None:
117
+ probs = [Fraction(1, b)] * b
118
+ ketu_state = ketu_encode(digits, probs, sigma=sigma_ketu)
119
+ ketu_digits = ketu_decode(ketu_state.midpoint, len(digits), probs, sigma=sigma_ketu)
120
+ ketu_s = alphabet.from_digits(ketu_digits)
121
+
122
+ return {
123
+ "input": s,
124
+ "rahu_integer": n,
125
+ "rahu_decoded": rahu_s,
126
+ "rahu_sigma_recovered": sigma_back,
127
+ "ketu_interval": (ketu_state.low, ketu_state.high),
128
+ "ketu_width": ketu_state.width,
129
+ "ketu_midpoint": ketu_state.midpoint,
130
+ "ketu_decoded": ketu_s,
131
+ "tau_final": math.log2(abs(n)),
132
+ "upsilon_final": (math.log2(ketu_state.scale.denominator)
133
+ - math.log2(ketu_state.scale.numerator)),
134
+ "agrees": rahu_s == s and ketu_s == s and sigma_back == sigma_rahu,
135
+ }
@@ -0,0 +1,201 @@
1
+ import math
2
+ from fractions import Fraction
3
+
4
+ import pytest
5
+
6
+ from rahuketu import (
7
+ Alphabet,
8
+ KetuState,
9
+ RahuState,
10
+ Step,
11
+ cdf,
12
+ ketu_decode,
13
+ ketu_encode,
14
+ rahu_decode,
15
+ rahu_encode,
16
+ roundtrip,
17
+ trace,
18
+ )
19
+
20
+
21
+ def test_alphabet_lowercase_mapping_is_one_based_and_roundtrips():
22
+ ab = Alphabet.lowercase()
23
+ assert ab.b == 26
24
+ assert ab.to_digits("az") == [1, 26]
25
+ assert ab.from_digits([1, 26]) == "az"
26
+ assert ab.from_digits(ab.to_digits("rahuketu")) == "rahuketu"
27
+
28
+
29
+ def test_alphabet_rejects_empty_and_duplicate_symbols():
30
+ with pytest.raises(ValueError):
31
+ Alphabet([])
32
+ with pytest.raises(ValueError):
33
+ Alphabet(["a", "a"])
34
+
35
+
36
+ def test_alphabet_rejects_unknown_symbol_or_digit():
37
+ ab = Alphabet.lowercase()
38
+ with pytest.raises(KeyError):
39
+ ab.to_digits("A")
40
+ with pytest.raises(KeyError):
41
+ ab.from_digits([0])
42
+ with pytest.raises(KeyError):
43
+ ab.from_digits([27])
44
+
45
+
46
+ def test_rahu_state_seed_step_tau_and_signed_value():
47
+ state = RahuState.seed(2, -1)
48
+ assert state.magnitude == 2
49
+ assert state.sigma == -1
50
+ assert state.length == 1
51
+ assert state.signed_value == -2
52
+ assert state.tau == math.log2(2)
53
+ state = state.step(3, 10)
54
+ assert state.magnitude == 23
55
+ assert state.sigma == -1
56
+ assert state.length == 2
57
+ assert state.signed_value == -23
58
+
59
+
60
+ def test_rahu_state_rejects_zero_and_invalid_sigma():
61
+ with pytest.raises(ValueError):
62
+ RahuState.seed(0, 1)
63
+ with pytest.raises(ValueError):
64
+ RahuState.seed(1, 0)
65
+ with pytest.raises(ValueError):
66
+ RahuState.seed(1, 2)
67
+ with pytest.raises(ValueError):
68
+ RahuState.seed(1, 1).step(0, 10)
69
+ with pytest.raises(ValueError):
70
+ RahuState.seed(1, 1).step(11, 10)
71
+
72
+
73
+ def test_rahu_encode_decode_roundtrip_positive_negative_and_boundary_digits():
74
+ for digits in ([1], [26], [1, 26], [26, 26], [18, 1, 8, 21]):
75
+ n = rahu_encode(list(digits), 26)
76
+ back, sigma = rahu_decode(n, 26)
77
+ assert back == list(digits)
78
+ assert sigma == 1
79
+ n = rahu_encode(list(digits), 26, sigma=-1)
80
+ back, sigma = rahu_decode(n, 26)
81
+ assert back == list(digits)
82
+ assert sigma == -1
83
+
84
+
85
+ def test_rahu_encode_decode_rejects_invalid_values():
86
+ with pytest.raises(ValueError):
87
+ rahu_encode([], 26)
88
+ with pytest.raises(ValueError):
89
+ rahu_decode(0, 26)
90
+ with pytest.raises(ValueError):
91
+ rahu_encode([0], 26)
92
+ with pytest.raises(ValueError):
93
+ rahu_encode([27], 26)
94
+ with pytest.raises(ValueError):
95
+ rahu_encode([1], 26, sigma=0)
96
+ with pytest.raises(ValueError):
97
+ rahu_decode(1, 0)
98
+
99
+
100
+ def test_cdf_builds_exact_distribution_and_rejects_invalid_probabilities():
101
+ probs = [Fraction(1, 4)] * 4
102
+ assert cdf(probs) == [Fraction(0), Fraction(1, 4), Fraction(1, 2), Fraction(3, 4), Fraction(1)]
103
+ with pytest.raises(ValueError):
104
+ cdf([Fraction(0), Fraction(1)])
105
+ with pytest.raises(ValueError):
106
+ cdf([Fraction(1, 3), Fraction(1, 3)])
107
+
108
+
109
+ def test_ketu_initial_state_and_step_interval_properties():
110
+ table = cdf([Fraction(1, 2), Fraction(1, 2)])
111
+ state = KetuState.initial()
112
+ assert state.midpoint == Fraction(1, 2)
113
+ assert state.scale == Fraction(1)
114
+ assert state.low == Fraction(0)
115
+ assert state.high == Fraction(1)
116
+ assert state.width == Fraction(1)
117
+ state = state.step(2, table)
118
+ assert state.low == Fraction(1, 2)
119
+ assert state.high == Fraction(1)
120
+ assert state.midpoint == Fraction(3, 4)
121
+ assert state.scale == Fraction(1, 2)
122
+ assert state.width == Fraction(1, 2)
123
+ assert state.upsilon == 1.0
124
+ with pytest.raises(ValueError):
125
+ state.step(0, table)
126
+ with pytest.raises(ValueError):
127
+ state.step(3, table)
128
+
129
+
130
+ def test_ketu_encode_decode_uniform_and_skewed_roundtrip():
131
+ uniform = [Fraction(1, 4)] * 4
132
+ assert ketu_decode(ketu_encode([1, 4, 2], uniform).midpoint, 3, uniform) == [1, 4, 2]
133
+ skewed = [Fraction(1, 2), Fraction(1, 4), Fraction(1, 8), Fraction(1, 8)]
134
+ encoded = ketu_encode([1, 2, 4, 3], skewed)
135
+ assert ketu_decode(encoded.midpoint, 4, skewed) == [1, 2, 4, 3]
136
+ assert encoded.low < encoded.midpoint < encoded.high
137
+
138
+
139
+ def test_ketu_sigma_minus_processes_reverse_stream_but_decodes_original_order():
140
+ probs = [Fraction(1, 4)] * 4
141
+ digits = [1, 2, 3, 4]
142
+ fwd = ketu_encode(digits, probs, sigma=1)
143
+ rev = ketu_encode(digits, probs, sigma=-1)
144
+ assert fwd.midpoint != rev.midpoint
145
+ assert ketu_decode(rev.midpoint, len(digits), probs, sigma=-1) == digits
146
+
147
+
148
+ def test_ketu_rejects_invalid_sigma_digit_and_outside_point():
149
+ probs = [Fraction(1, 2), Fraction(1, 2)]
150
+ with pytest.raises(ValueError):
151
+ ketu_encode([1], probs, sigma=0)
152
+ with pytest.raises(ValueError):
153
+ ketu_decode(Fraction(1, 2), 1, probs, sigma=0)
154
+ with pytest.raises(ValueError):
155
+ ketu_encode([3], probs)
156
+ with pytest.raises(ValueError):
157
+ ketu_decode(Fraction(2), 1, probs)
158
+
159
+
160
+ def test_trace_reports_one_step_per_symbol_and_roundtrip_agrees():
161
+ ab = Alphabet.lowercase()
162
+ steps = trace("hello", ab)
163
+ assert len(steps) == 5
164
+ assert isinstance(steps[0], Step)
165
+ assert [s.k for s in steps] == [1, 2, 3, 4, 5]
166
+ assert [s.symbol for s in steps] == list("hello")
167
+ assert [s.digit for s in steps] == ab.to_digits("hello")
168
+ assert steps[-1].ketu_low < steps[-1].ketu_midpoint < steps[-1].ketu_high
169
+ assert steps[-1].ketu_width == steps[-1].ketu_scale
170
+ assert steps[-1].redundancy == pytest.approx(steps[-1].tau - steps[-1].upsilon)
171
+ assert roundtrip("hello", ab)["agrees"]
172
+
173
+
174
+ def test_trace_supports_nonuniform_information_coordinate():
175
+ ab = Alphabet(["a", "b"])
176
+ probs = [Fraction(3, 4), Fraction(1, 4)]
177
+ steps = trace("ab", ab, probs=probs)
178
+ assert steps[0].a == pytest.approx(-math.log2(3 / 4) / math.log2(2))
179
+ assert steps[1].a == pytest.approx(2.0)
180
+
181
+
182
+ def test_trace_and_roundtrip_respect_sigma_choices():
183
+ ab = Alphabet.lowercase()
184
+ rt = roundtrip("abc", ab, sigma_rahu=-1, sigma_ketu=-1)
185
+ assert rt["agrees"]
186
+ assert rt["rahu_integer"] < 0
187
+ assert rt["rahu_sigma_recovered"] == -1
188
+ steps = trace("abc", ab, sigma_rahu=-1, sigma_ketu=-1)
189
+ assert all(s.rahu_value < 0 for s in steps)
190
+
191
+
192
+ def test_trace_rejects_invalid_inputs():
193
+ ab = Alphabet.lowercase()
194
+ with pytest.raises(ValueError):
195
+ trace("", ab)
196
+ with pytest.raises(ValueError):
197
+ trace("a", ab, sigma_rahu=0)
198
+ with pytest.raises(ValueError):
199
+ trace("a", ab, sigma_ketu=0)
200
+ with pytest.raises(ValueError):
201
+ trace("a", ab, probs=[Fraction(1)])