hyperspace-sdk-ts 2.2.1 → 3.0.0

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.
package/dist/math.js ADDED
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+ /**
3
+ * HyperspaceDB Spatial and Cognitive Math SDK
4
+ * Provides hyperbolic math functions and Cognitive AI metrics for solving LLM hallucinations.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.dot = dot;
8
+ exports.normSq = normSq;
9
+ exports.norm = norm;
10
+ exports.mobiusAdd = mobiusAdd;
11
+ exports.expMap = expMap;
12
+ exports.logMap = logMap;
13
+ exports.parallelTransport = parallelTransport;
14
+ exports.frechetMean = frechetMean;
15
+ exports.lorentzProduct = lorentzProduct;
16
+ exports.lorentzDist = lorentzDist;
17
+ exports.lorentzToPoincare = lorentzToPoincare;
18
+ exports.poincareToLorentz = poincareToLorentz;
19
+ exports.projectToHyperboloid = projectToHyperboloid;
20
+ exports.localEntropy = localEntropy;
21
+ exports.lyapunovConvergence = lyapunovConvergence;
22
+ exports.koopmanExtrapolate = koopmanExtrapolate;
23
+ exports.contextResonance = contextResonance;
24
+ function dot(a, b) {
25
+ let sum = 0;
26
+ for (let i = 0; i < a.length; i++)
27
+ sum += a[i] * b[i];
28
+ return sum;
29
+ }
30
+ function normSq(v) {
31
+ return dot(v, v);
32
+ }
33
+ function norm(v) {
34
+ return Math.sqrt(Math.max(normSq(v), 0.0));
35
+ }
36
+ function projectToBall(x, c) {
37
+ const n = norm(x);
38
+ const maxN = (1.0 / Math.sqrt(c)) - 1e-9;
39
+ if (n <= maxN || n <= 1e-15)
40
+ return [...x];
41
+ const s = maxN / n;
42
+ return x.map(v => v * s);
43
+ }
44
+ function mobiusAdd(x, y, c = 1.0) {
45
+ if (x.length !== y.length)
46
+ throw new Error("Dimension mismatch");
47
+ if (c <= 0.0)
48
+ throw new Error("Curvature c must be > 0");
49
+ const xy = dot(x, y);
50
+ const x2 = normSq(x);
51
+ const y2 = normSq(y);
52
+ const numLeft = 1.0 + 2.0 * c * xy + c * y2;
53
+ const numRight = 1.0 - c * x2;
54
+ const den = 1.0 + 2.0 * c * xy + c * c * x2 * y2;
55
+ if (Math.abs(den) < 1e-15)
56
+ throw new Error("Möbius addition denominator too close to zero");
57
+ return x.map((xi, i) => (numLeft * xi + numRight * y[i]) / den);
58
+ }
59
+ function expMap(x, v, c = 1.0) {
60
+ if (x.length !== v.length)
61
+ throw new Error("Dimension mismatch");
62
+ if (c <= 0.0)
63
+ throw new Error("Curvature c must be > 0");
64
+ const x2 = normSq(x);
65
+ const vNorm = Math.sqrt(Math.max(normSq(v), 0.0));
66
+ if (vNorm < 1e-15)
67
+ return [...x];
68
+ const lambdaX = 2.0 / Math.max(1.0 - c * x2, 1e-15);
69
+ const scale = Math.tanh(Math.sqrt(c) * lambdaX * vNorm / 2.0) / (Math.sqrt(c) * vNorm);
70
+ const step = v.map(vi => scale * vi);
71
+ return mobiusAdd(x, step, c);
72
+ }
73
+ function logMap(x, y, c = 1.0) {
74
+ if (x.length !== y.length)
75
+ throw new Error("Dimension mismatch");
76
+ if (c <= 0.0)
77
+ throw new Error("Curvature c must be > 0");
78
+ const negX = x.map(xi => -xi);
79
+ const delta = mobiusAdd(negX, y, c);
80
+ const deltaNorm = Math.sqrt(Math.max(normSq(delta), 0.0));
81
+ if (deltaNorm < 1e-15)
82
+ return new Array(x.length).fill(0.0);
83
+ const x2 = normSq(x);
84
+ const lambdaX = 2.0 / Math.max(1.0 - c * x2, 1e-15);
85
+ const factor = (2.0 / (lambdaX * Math.sqrt(c))) * Math.atanh(Math.min(Math.sqrt(c) * deltaNorm, 1.0 - 1e-15));
86
+ return delta.map(di => factor * di / deltaNorm);
87
+ }
88
+ function gyro(u, v, w, c = 1.0) {
89
+ const uv = mobiusAdd(u, v, c);
90
+ const vw = mobiusAdd(v, w, c);
91
+ const left = mobiusAdd(u, vw, c);
92
+ const negUv = uv.map(z => -z);
93
+ return mobiusAdd(negUv, left, c);
94
+ }
95
+ function parallelTransport(x, y, v, c = 1.0) {
96
+ if (x.length !== y.length || x.length !== v.length)
97
+ throw new Error("Dimension mismatch");
98
+ if (c <= 0.0)
99
+ throw new Error("Curvature c must be > 0");
100
+ const negX = x.map(xi => -xi);
101
+ const gyr = gyro(y, negX, v, c);
102
+ const lambdaX = 2.0 / Math.max(1.0 - c * normSq(x), 1e-15);
103
+ const lambdaY = 2.0 / Math.max(1.0 - c * normSq(y), 1e-15);
104
+ const scale = lambdaX / lambdaY;
105
+ return gyr.map(gi => scale * gi);
106
+ }
107
+ function frechetMean(points, c = 1.0, maxIter = 32, tol = 1e-6) {
108
+ if (points.length === 0)
109
+ throw new Error("Points set cannot be empty");
110
+ if (c <= 0.0)
111
+ throw new Error("Curvature c must be > 0");
112
+ const dim = points[0].length;
113
+ let mu = projectToBall(points[0], c);
114
+ for (let iter = 0; iter < Math.max(1, maxIter); iter++) {
115
+ let grad = new Array(dim).fill(0.0);
116
+ for (const p of points) {
117
+ const lg = logMap(mu, p, c);
118
+ for (let i = 0; i < dim; i++)
119
+ grad[i] += lg[i];
120
+ }
121
+ const inv = 1.0 / points.length;
122
+ for (let i = 0; i < dim; i++)
123
+ grad[i] *= inv;
124
+ const gNorm = norm(grad);
125
+ if (gNorm <= Math.max(tol, 1e-15))
126
+ break;
127
+ mu = expMap(mu, grad, c);
128
+ mu = projectToBall(mu, c);
129
+ }
130
+ return mu;
131
+ }
132
+ // ==========================================
133
+ // Lorentz Model Math (Hyperboloid)
134
+ // ==========================================
135
+ /** Computes the Minkowski inner product (Lorentz product) between two vectors. */
136
+ function lorentzProduct(u, v) {
137
+ if (u.length === 0 || v.length === 0)
138
+ return 0.0;
139
+ let product = -u[0] * v[0];
140
+ for (let i = 1; i < u.length; i++)
141
+ product += u[i] * v[i];
142
+ return product;
143
+ }
144
+ /** Computes the Lorentz distance between two points on the hyperboloid. */
145
+ function lorentzDist(u, v) {
146
+ const inner = -lorentzProduct(u, v);
147
+ return Math.acosh(Math.max(inner, 1.0));
148
+ }
149
+ /** Converts a point from the Lorentz model (Hyperboloid) to the Poincaré Ball model (129 -> 128). */
150
+ function lorentzToPoincare(x) {
151
+ if (x.length === 0)
152
+ return [];
153
+ const denom = Math.max(1.0 + x[0], 1e-12);
154
+ const proj = [];
155
+ for (let i = 1; i < x.length; i++)
156
+ proj.push(x[i] / denom);
157
+ return proj;
158
+ }
159
+ /** Converts a point from the Poincaré Ball model to the Lorentz model (128 -> 129). */
160
+ function poincareToLorentz(p) {
161
+ const pSq = normSq(p);
162
+ const denom = Math.max(1.0 - pSq, 1e-12);
163
+ const x = [(1.0 + pSq) / denom];
164
+ for (const pi of p)
165
+ x.push((2.0 * pi) / denom);
166
+ return x;
167
+ }
168
+ /** Ensures a vector satisfies the Lorentz constraint -x0^2 + |x|^2 = -1 (stabilization). */
169
+ function projectToHyperboloid(v) {
170
+ if (v.length === 0)
171
+ return [];
172
+ const res = [...v];
173
+ let spatialNormSq = 0;
174
+ for (let i = 1; i < res.length; i++)
175
+ spatialNormSq += res[i] * res[i];
176
+ res[0] = Math.sqrt(1.0 + spatialNormSq);
177
+ return res;
178
+ }
179
+ // ==========================================
180
+ // Cognitive Math SDK (Spatial AI Engine)
181
+ // ==========================================
182
+ /**
183
+ * Calculates the spatial entropy (dispersion) of a `candidate` vector relative to its `neighbors`.
184
+ * Used to track LLM hallucinations (Task 2.3.1).
185
+ * Returns a value in [0, 1) where values approaching 1 imply high chaos (hallucination).
186
+ */
187
+ function localEntropy(candidate, neighbors, c = 1.0) {
188
+ if (neighbors.length === 0)
189
+ return 1.0;
190
+ let totalDeviation = 0.0;
191
+ for (const neighbor of neighbors) {
192
+ const diff = logMap(candidate, neighbor, c);
193
+ totalDeviation += norm(diff);
194
+ }
195
+ const meanDeviation = totalDeviation / neighbors.length;
196
+ return 1.0 - Math.exp(-meanDeviation);
197
+ }
198
+ /**
199
+ * Evaluates if a trajectory of vectors (e.g. Chain of Thought) converges to an attractor.
200
+ * Calculates the average energy derivative (Lyapunov function derivative).
201
+ * Negative values indicate convergence (stable), positive indicate divergence (chaos/hallucination).
202
+ */
203
+ function lyapunovConvergence(trajectory, c = 1.0) {
204
+ if (trajectory.length < 3)
205
+ throw new Error("Need at least 3 points");
206
+ const attractor = frechetMean(trajectory, c, 32, 1e-6);
207
+ let vDiffSum = 0.0;
208
+ for (let i = 0; i < trajectory.length - 1; i++) {
209
+ const vt0 = norm(logMap(attractor, trajectory[i], c));
210
+ const vt1 = norm(logMap(attractor, trajectory[i + 1], c));
211
+ vDiffSum += (vt1 - vt0);
212
+ }
213
+ return vDiffSum / (trajectory.length - 1);
214
+ }
215
+ /**
216
+ * Extrapolates the trajectory in linear space (Koopman linearization) by tracking the
217
+ * shift vector from `past` to `current` and projecting it forward.
218
+ */
219
+ function koopmanExtrapolate(past, current, steps, c = 1.0) {
220
+ const velocityAtPast = logMap(past, current, c);
221
+ const velocityAtCurrent = parallelTransport(past, current, velocityAtPast, c);
222
+ const futureVelocity = velocityAtCurrent.map(v => v * steps);
223
+ return expMap(current, futureVelocity, c);
224
+ }
225
+ /**
226
+ * Resonates a thought vector towards a global context vector (Phase-Locked Loop context synchronization).
227
+ * Pulls the thought towards the context along the geodesic by `resonanceFactor` [0, 1].
228
+ */
229
+ function contextResonance(thought, globalContext, resonanceFactor, c = 1.0) {
230
+ const pullDir = logMap(thought, globalContext, c);
231
+ const factor = Math.max(0.0, Math.min(1.0, resonanceFactor));
232
+ const appliedPull = pullDir.map(v => v * factor);
233
+ return expMap(thought, appliedPull, c);
234
+ }