File size: 15,847 Bytes
bee08ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
"""Transparent five-axis tensor carrier and 32-coefficient mixed-jet algebra.

This is a reference experiment, not an audio-compression breakthrough. WAV stores
compressed bytes as a PCM data payload; custom psri metadata makes decoding exact.
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass
import hashlib
import itertools
import json
import math
from pathlib import Path
import platform
import struct
import time
import zlib
import numpy as np

DIM = 5
SIZE = 1 << DIM

@dataclass
class Jet5:
    c: np.ndarray

    def __post_init__(self):
        self.c = np.asarray(self.c, dtype=np.float64)
        if self.c.shape != (SIZE,):
            raise ValueError('Jet5 requires exactly 32 real coefficients')

    @classmethod
    def scalar(cls, x: float):
        c = np.zeros(SIZE); c[0] = x
        return cls(c)

    @classmethod
    def variable(cls, x: float, axis: int, speed: float = 1.0):
        if axis not in range(DIM):
            raise ValueError('axis must be 0,1,2,3,4')
        z = cls.scalar(x); z.c[1 << axis] = speed
        return z

    def __add__(self, other):
        if not isinstance(other, Jet5): other = Jet5.scalar(other)
        return Jet5(self.c + other.c)
    __radd__ = __add__

    def __neg__(self): return Jet5(-self.c)
    def __sub__(self, other): return self + (-other if isinstance(other, Jet5) else -float(other))

    def __mul__(self, other):
        if not isinstance(other, Jet5): return Jet5(self.c * float(other))
        out = np.zeros(SIZE)
        for a in range(SIZE):
            remaining = (SIZE - 1) ^ a
            b = remaining
            while True:
                out[a | b] += self.c[a] * other.c[b]
                if b == 0: break
                b = (b - 1) & remaining
        return Jet5(out)
    __rmul__ = __mul__

    def exp(self):
        n = self.c.copy(); n[0] = 0
        n = Jet5(n)
        term = Jet5.scalar(1.0)
        out = Jet5.scalar(1.0)
        for k in range(1, DIM + 1):
            term = term * n * (1.0 / k)
            out = out + term
        return out * math.exp(self.c[0])

    def inverse(self):
        if self.c[0] == 0: raise ZeroDivisionError('Jet inverse needs nonzero scalar part')
        q = self.c.copy(); q[0] = 0
        q = Jet5(-q / self.c[0])
        term = Jet5.scalar(1); out = Jet5.scalar(1)
        for _ in range(1, DIM + 1):
            term = term * q; out = out + term
        return out * (1.0 / self.c[0])


def _chunk(tag: bytes, body: bytes) -> bytes:
    if len(tag) != 4: raise ValueError('RIFF chunk identifier must be four bytes')
    return tag + struct.pack('<I', len(body)) + body + b'\x00' * (len(body) % 2)


def encode_wav(tensor: np.ndarray, path: Path, sample_rate: int = 48000,
               axes=None, quantization=None) -> dict:
    """Losslessly encode an integer tensor; any prior float quantization is separate."""
    tensor = np.asarray(tensor)
    if tensor.ndim != 5 or tensor.dtype.kind != 'i' or tensor.dtype.itemsize != 2:
        raise ValueError('codec domain is a five-dimensional signed-int16 tensor')
    if not (1 <= sample_rate <= 1_000_000): raise ValueError('unsupported sample rate')
    tensor = np.ascontiguousarray(tensor, dtype='<i2')
    raw = tensor.tobytes(order='C')
    comp = zlib.compress(raw, level=9)
    metadata = {
        'format': 'phase-shift-carrier-v1', 'shape': list(tensor.shape),
        'dtype': '<i2', 'order': 'C', 'encoding': 'zlib',
        'raw_bytes': len(raw), 'compressed_bytes': len(comp),
        'raw_sha256': hashlib.sha256(raw).hexdigest(),
        'compressed_sha256': hashlib.sha256(comp).hexdigest(),
        'axes': axes or ['u','v','layer','scale','successor'],
        'interpretation': 'digital tensor indices; non-auditory data carrier',
        'quantization': quantization if quantization is not None else 'none within codec; input int16 is preserved exactly'
    }
    # The data chunk is padded internally to a complete 16-bit PCM word. Its exact
    # compressed payload length is in psri metadata; standard RIFF chunk padding
    # and this PCM word padding have separate purposes.
    pcm_bytes = comp + b'\x00' * (len(comp) % 2)
    fmt = struct.pack('<HHIIHH', 1, 1, sample_rate, sample_rate * 2, 2, 16)
    body = (b'WAVE' + _chunk(b'fmt ', fmt)
            + _chunk(b'psri', json.dumps(metadata, sort_keys=True, separators=(',', ':')).encode())
            + _chunk(b'data', pcm_bytes))
    container = b'RIFF' + struct.pack('<I', len(body)) + body
    path = Path(path); path.write_bytes(container)
    return {**metadata, 'wav_bytes': len(container), 'sample_rate': sample_rate,
            'nominal_duration_seconds': len(pcm_bytes) / (2 * sample_rate)}


def read_chunks(path: Path) -> dict:
    blob = Path(path).read_bytes()
    if blob[:4] != b'RIFF' or blob[8:12] != b'WAVE': raise ValueError('not a RIFF WAVE file')
    if len(blob) != 8 + struct.unpack('<I', blob[4:8])[0]: raise ValueError('RIFF size mismatch')
    cursor = 12; chunks = {}
    while cursor < len(blob):
        if cursor + 8 > len(blob): raise ValueError('truncated chunk header')
        tag = blob[cursor:cursor+4]; length = struct.unpack('<I', blob[cursor+4:cursor+8])[0]
        start = cursor+8; stop = start+length
        if stop > len(blob): raise ValueError('truncated chunk body')
        if tag in chunks: raise ValueError('duplicate chunk identifier')
        chunks[tag] = blob[start:stop]
        cursor = stop + length % 2
    return chunks


def decode_wav(path: Path) -> tuple[np.ndarray, dict]:
    chunks = read_chunks(path)
    meta = json.loads(chunks[b'psri'])
    if meta['format'] != 'phase-shift-carrier-v1' or meta['dtype'] != '<i2':
        raise ValueError('unsupported tensor codec')
    if len(meta['shape']) != 5 or any(type(n) is not int or n <= 0 for n in meta['shape']):
        raise ValueError('invalid tensor shape')
    if math.prod(meta['shape']) * 2 != meta['raw_bytes']: raise ValueError('shape length mismatch')
    encoded = chunks[b'data'][:meta['compressed_bytes']]
    if hashlib.sha256(encoded).hexdigest() != meta['compressed_sha256']:
        raise ValueError('compressed payload checksum failed')
    raw = zlib.decompress(encoded)
    if len(raw) != meta['raw_bytes'] or hashlib.sha256(raw).hexdigest() != meta['raw_sha256']:
        raise ValueError('decoded payload checksum failed')
    return np.frombuffer(raw, dtype='<i2').reshape(meta['shape']).copy(), meta


def heat5(field: np.ndarray, time_value: float, rates: np.ndarray) -> np.ndarray:
    """Periodic five-axis discrete heat semigroup, with anisotropic rates."""
    x = np.asarray(field, dtype=float); rates = np.asarray(rates, dtype=float)
    if x.ndim != 5 or rates.shape != (5,) or np.any(rates < 0) or time_value < 0:
        raise ValueError('heat5 needs 5D input, five nonnegative rates and nonnegative time')
    eigenvalue = np.zeros(x.shape)
    for axis, n in enumerate(x.shape):
        shape = [1]*5; shape[axis] = n
        eigenvalue += rates[axis] * (4*np.sin(np.pi*np.fft.fftfreq(n))**2).reshape(shape)
    return np.fft.ifftn(np.fft.fftn(x) * np.exp(-time_value*eigenvalue)).real


def finite_mixed(function, x: np.ndarray, axes: list[int], h: float) -> float:
    answer = 0.0
    for signs in itertools.product([-1,1], repeat=len(axes)):
        q = x.copy()
        for axis, sign in zip(axes, signs): q[axis] += sign*h
        answer += np.prod(signs) * function(q)
    return answer/(2*h)**len(axes)


def run_demo(directory: Path, seed: int = 640291) -> dict:
    directory = Path(directory); directory.mkdir(parents=True, exist_ok=True)
    rng = np.random.default_rng(seed)
    x = np.array([0.2, -0.3, 0.4, 0.1, -0.2])
    a = np.array([0.4, -0.7, 0.8, 0.3, -0.5])
    speeds = np.array([1., .5, 2., .75, 1.25])
    variables = [Jet5.variable(x[i], i, speeds[i]) for i in range(5)]
    expr = sum((a[i]*variables[i] for i in range(5)), Jet5.scalar(0)).exp()
    product = Jet5.scalar(1)
    for v in variables: product = product*v
    expr = expr + product
    expected = np.zeros(32)
    for mask in range(32):
        selected = [i for i in range(5) if mask & (1<<i)]
        remaining = [i for i in range(5) if not mask & (1<<i)]
        expected[mask] = ((math.exp(float(a@x)) * math.prod(a[i] for i in selected)
                           + math.prod(x[i] for i in remaining))
                          * math.prod(speeds[i] for i in selected))
    algebra_error = float(np.max(np.abs(expr.c-expected)))
    assert algebra_error < 1e-12
    comm_err=0.; assoc_err=0.; inv_err=0.; nilpotence_err=0.
    for _ in range(50):
        j,k,l = [Jet5(rng.normal(size=32)) for _ in range(3)]
        comm_err=max(comm_err, float(np.max(np.abs((j*k).c-(k*j).c))))
        assoc_err=max(assoc_err, float(np.max(np.abs(((j*k)*l).c-(j*(k*l)).c))))
        j.c[0] = 2.0
        inv_err=max(inv_err,float(np.max(np.abs((j*j.inverse()).c-Jet5.scalar(1).c))))
        j.c[0] = 0
        power = Jet5.scalar(1)
        for _ in range(6): power=power*j
        nilpotence_err=max(nilpotence_err,float(np.max(np.abs(power.c))))
    assert max(comm_err,assoc_err,inv_err,nilpotence_err)<1e-10
    function=lambda q: math.exp(float(a@q))+float(np.prod(q))
    fd=[]
    for axes in [[0],[0,1],list(range(5))]:
        mask=sum(1<<i for i in axes)
        true=expected[mask]/math.prod(speeds[i] for i in axes)
        for h in [1e-1,1e-2,1e-3,1e-4]:
            estimate=finite_mixed(function,x,axes,h)
            fd.append({'order':len(axes),'step':h,'estimate':estimate,'analytic':true,'absolute_error':abs(estimate-true)})
    # Direct hypernumber-to-WAV path: the 32 coefficients are addressed by five
    # binary mask axes. Quantization is explicit, bounded, and stored in metadata.
    jet_delta=1/4096
    jet_integers=np.rint(expr.c/jet_delta).astype('<i2').reshape((2,2,2,2,2))
    assert np.max(np.abs(expr.c/jet_delta)) < 32767
    jet_metadata=encode_wav(jet_integers,directory/'jet_coefficients.wav',
        axes=['epsilon_4','epsilon_3','epsilon_2','epsilon_1','epsilon_0'],
        quantization={'kind':'round-to-nearest','step':jet_delta,'offset':0.0,
                      'source':'32 real Jet5 coefficients','interpretation':'binary axis values select the five-generator subset mask'})
    jet_back,jet_back_metadata=decode_wav(directory/'jet_coefficients.wav')
    jet_recovered=jet_back.ravel()*jet_back_metadata['quantization']['step']
    jet_carrier_error=float(np.max(np.abs(jet_recovered-expr.c)))
    assert np.array_equal(jet_back,jet_integers) and jet_carrier_error <= jet_delta/2+1e-14
    jet_carrier={'path':'jet_coefficients.wav','shape':[2,2,2,2,2],
                 'axis_order':['epsilon_4','epsilon_3','epsilon_2','epsilon_1','epsilon_0'],
                 'quantization_step':jet_delta,'max_absolute_error':jet_carrier_error,'proved_bound':jet_delta/2,
                 'exact_integer_roundtrip':True,'wav_bytes':jet_metadata['wav_bytes'],
                 'raw_integer_bytes':jet_metadata['raw_bytes'],'raw_sha256':jet_metadata['raw_sha256'],
                 'recovered_coefficients':jet_recovered.tolist()}
    # A deliberately structured field and a maximum-range discrete uniform control.
    shape=(12,10,8,6,4)
    grid=np.indices(shape)
    field=(np.sin(2*np.pi*grid[0]/shape[0])+.5*np.cos(2*np.pi*grid[1]/shape[1])
           +.25*np.sin(2*np.pi*(grid[2]/shape[2]+grid[3]/shape[3]))+.1*grid[4])
    structured=np.rint(32*field).astype('<i2')
    random_tensor=rng.integers(-32768,32768,size=shape,dtype=np.int16)
    codec_results=[]
    for name, tensor in [('structured', structured),('uniform_random',random_tensor)]:
        t0=time.perf_counter()
        row=encode_wav(tensor,directory/(name+'.wav'))
        decoded,metadata=decode_wav(directory/(name+'.wav'))
        elapsed=time.perf_counter()-t0
        assert np.array_equal(tensor,decoded)
        row.update(name=name, exact_roundtrip=True, max_integer_error=int(np.max(np.abs(tensor.astype(int)-decoded.astype(int)))),
                   compressed_over_raw=row['compressed_bytes']/row['raw_bytes'],wav_over_raw=row['wav_bytes']/row['raw_bytes'],elapsed_seconds=elapsed)
        codec_results.append(row)
    rate_rows=[]
    baseline_chunks=None
    for rate in [24000,48000,96000]:
        path=directory/f'structured_{rate}Hz.wav'
        row=encode_wav(structured,path,rate)
        chunks=read_chunks(path)
        if baseline_chunks is None: baseline_chunks=chunks
        assert chunks[b'data']==baseline_chunks[b'data'] and chunks[b'psri']==baseline_chunks[b'psri']
        rate_rows.append({'sample_rate':rate,'wav_bytes':row['wav_bytes'],'nominal_duration_seconds':row['nominal_duration_seconds'],
                          'identical_pcm_bytes':True,'identical_tensor_metadata':True,'raw_sha256':row['raw_sha256']})
    # Quantization bound and semigroup law are distinct from lossless transport.
    delta=1/32
    quant=np.rint(field/delta)*delta
    quant_error=float(np.max(np.abs(field-quant)))
    assert quant_error<=delta/2+1e-14
    rates=np.array([.4,.8,1.2,1.6,2.])
    noise=rng.normal(size=shape)
    mixed=field+.6*noise+.3*heat5(noise,1.2,rates)
    heat_rows=[]
    for t in [0,.1,.3,1,3,10]:
        y=heat5(mixed,t,rates)
        heat_rows.append({'time':t,'mean':float(y.mean()),'centered_l2_norm':float(np.linalg.norm(y-y.mean()))})
    semigroup_error=float(np.max(np.abs(heat5(heat5(mixed,.7,rates),1.3,rates)-heat5(mixed,2.,rates))))
    assert semigroup_error<1e-12
    assert all(heat_rows[i+1]['centered_l2_norm'] <= heat_rows[i]['centered_l2_norm']+1e-12 for i in range(len(heat_rows)-1))
    report={
      'seed':seed,'environment':{'python':platform.python_version(),'numpy':np.__version__,'platform':platform.platform()},
      'jet':{'function':'exp(sum(a_i*x_i)) + product(x_i)','a':a.tolist(),'x':x.tolist(),'axis_speeds':speeds.tolist(),
             'coefficients':expr.c.tolist(),'analytic_coefficients':expected.tolist(),'max_absolute_error':algebra_error,
             'random_algebra_trials':50,'commutativity_error':comm_err,'associativity_error':assoc_err,'inverse_error':inv_err,'nilpotence_order_6_error':nilpotence_err,
             'finite_difference_controls':fd},
      'codec':codec_results,'jet_wav_carrier':jet_carrier,'sample_rate_control':rate_rows,
      'heat':{'axis_rates':rates.tolist(),'semigroup_max_error':semigroup_error,'progression':heat_rows},
      'quantization':{'step':delta,'max_absolute_error':quant_error,'proved_bound':delta/2},
      'interpretation':{'five_dimensions':'five digital tensor axes, not physical dimensions',
                        'hypernumbers':'standard tensor product of five dual-number algebras, not a new number system',
                        'compression':'zlib finds redundancy; WAV adds container overhead',
                        'rsi_scope':'representation verification only; these tests do not demonstrate model intelligence gains'}
    }
    (directory/'metrics.json').write_text(json.dumps(report,indent=2)+'\n')
    np.savez_compressed(directory/'reference_tensors.npz',structured=structured,random=random_tensor,continuous_field=field)
    return report

if __name__=='__main__':
    parser=argparse.ArgumentParser()
    parser.add_argument('--out',type=Path,default=Path(__file__).resolve().parent/'results')
    parser.add_argument('--seed',type=int,default=640291)
    args=parser.parse_args()
    result=run_demo(args.out,args.seed)
    print(json.dumps({'jet_error':result['jet']['max_absolute_error'],'heat_semigroup_error':result['heat']['semigroup_max_error'],
                      'codec':[{k:r[k] for k in ['name','raw_bytes','compressed_bytes','wav_bytes','wav_over_raw','exact_roundtrip']} for r in result['codec']],
                      'quantization':result['quantization'],'jet_wav_carrier':result['jet_wav_carrier']},indent=2))