@aleph-ai/tinyaleph 1.3.0 → 1.4.1

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,655 @@
1
+ /**
2
+ * Topological Invariants Module
3
+ *
4
+ * From 108bio.pdf - "Twist Eigenstates and Topological Morphogenesis"
5
+ *
6
+ * Implements knot-theoretic invariants for deriving physical constants
7
+ * from topological structure. The Trefoil Knot (3₁) is identified as
8
+ * the minimal non-trivial stable structure whose complexity number
9
+ * combined with the 108 invariant yields fundamental constants.
10
+ *
11
+ * Key concepts:
12
+ * - Knot invariants: crossing number, stick number, bridge number, unknotting number
13
+ * - Trefoil complexity: T = s·c - b + u = 17
14
+ * - Mass ratio derivation: 17 × 108 = 1836 (proton/electron)
15
+ * - Fine structure constant: α⁻¹ = 108 + 29 = 137
16
+ */
17
+
18
+ const { TWIST_108, factorize, isPrime } = require('./prime');
19
+
20
+ // ============================================================================
21
+ // KNOT INVARIANTS
22
+ // ============================================================================
23
+
24
+ /**
25
+ * Knot class representing a mathematical knot with topological invariants
26
+ */
27
+ class Knot {
28
+ /**
29
+ * Create a knot with specified invariants
30
+ * @param {Object} invariants - Knot invariants
31
+ * @param {number} invariants.crossings - Crossing number (c)
32
+ * @param {number} invariants.sticks - Stick number (s) - minimum edges in polygonal representation
33
+ * @param {number} invariants.bridge - Bridge number (b) - minimum bridges in bridge presentation
34
+ * @param {number} invariants.unknotting - Unknotting number (u) - minimum crossing changes to unknot
35
+ * @param {string} [invariants.name] - Knot name (e.g., "Trefoil", "Figure-8")
36
+ * @param {string} [invariants.notation] - Alexander-Briggs notation (e.g., "3_1")
37
+ */
38
+ constructor(invariants) {
39
+ this.crossings = invariants.crossings || 0;
40
+ this.sticks = invariants.sticks || 0;
41
+ this.bridge = invariants.bridge || 1;
42
+ this.unknotting = invariants.unknotting || 0;
43
+ this.name = invariants.name || 'unknown';
44
+ this.notation = invariants.notation || '';
45
+ }
46
+
47
+ /**
48
+ * Compute the complexity number T (equation from paper)
49
+ * T = s·c - b + u
50
+ *
51
+ * This complexity captures the topological "difficulty" of the knot
52
+ * and is used to derive physical constants.
53
+ *
54
+ * @returns {number} Complexity number
55
+ */
56
+ complexity() {
57
+ return this.sticks * this.crossings - this.bridge + this.unknotting;
58
+ }
59
+
60
+ /**
61
+ * Derive mass ratio using the 108 invariant
62
+ * mass_ratio = complexity × 108
63
+ *
64
+ * For the Trefoil: 17 × 108 = 1836 (proton/electron mass ratio)
65
+ *
66
+ * @returns {number} Derived mass ratio
67
+ */
68
+ deriveMassRatio() {
69
+ return this.complexity() * TWIST_108.value;
70
+ }
71
+
72
+ /**
73
+ * Check if this knot is topologically prime
74
+ * A prime knot cannot be decomposed as a connected sum
75
+ *
76
+ * Heuristic: crossings < 10 and bridge = 2 suggests prime knot
77
+ * @returns {boolean} True if likely prime knot
78
+ */
79
+ isPrimeKnot() {
80
+ // Simple heuristic based on small crossing number
81
+ return this.crossings <= 8 && this.bridge <= 2;
82
+ }
83
+
84
+ /**
85
+ * Compute the genus of the knot (lower bound)
86
+ * genus ≥ (c - b + 1) / 2
87
+ *
88
+ * @returns {number} Estimated genus lower bound
89
+ */
90
+ genusLowerBound() {
91
+ return Math.floor((this.crossings - this.bridge + 1) / 2);
92
+ }
93
+
94
+ /**
95
+ * Get knot descriptor object
96
+ */
97
+ toJSON() {
98
+ return {
99
+ name: this.name,
100
+ notation: this.notation,
101
+ crossings: this.crossings,
102
+ sticks: this.sticks,
103
+ bridge: this.bridge,
104
+ unknotting: this.unknotting,
105
+ complexity: this.complexity(),
106
+ massRatio: this.deriveMassRatio(),
107
+ isPrime: this.isPrimeKnot(),
108
+ genusLowerBound: this.genusLowerBound()
109
+ };
110
+ }
111
+
112
+ toString() {
113
+ return `${this.name} (${this.notation}): T=${this.complexity()}`;
114
+ }
115
+ }
116
+
117
+ // ============================================================================
118
+ // STANDARD KNOTS
119
+ // ============================================================================
120
+
121
+ /**
122
+ * The Unknot (trivial knot)
123
+ */
124
+ const UNKNOT = new Knot({
125
+ name: 'Unknot',
126
+ notation: '0_1',
127
+ crossings: 0,
128
+ sticks: 3, // Minimum for a triangle
129
+ bridge: 1,
130
+ unknotting: 0
131
+ });
132
+
133
+ /**
134
+ * The Trefoil Knot (3₁) - The fundamental stable structure
135
+ *
136
+ * The Trefoil is the simplest non-trivial knot and appears throughout
137
+ * nature as the minimal stable topological configuration.
138
+ *
139
+ * Invariants:
140
+ * - Crossing number c = 3
141
+ * - Stick number s = 6
142
+ * - Bridge number b = 2
143
+ * - Unknotting number u = 1
144
+ *
145
+ * Complexity: T = 6·3 - 2 + 1 = 17
146
+ * Mass ratio: 17 × 108 = 1836 (exact proton/electron mass ratio)
147
+ */
148
+ const TREFOIL = new Knot({
149
+ name: 'Trefoil',
150
+ notation: '3_1',
151
+ crossings: 3,
152
+ sticks: 6,
153
+ bridge: 2,
154
+ unknotting: 1
155
+ });
156
+
157
+ /**
158
+ * The Figure-Eight Knot (4₁)
159
+ */
160
+ const FIGURE_EIGHT = new Knot({
161
+ name: 'Figure-Eight',
162
+ notation: '4_1',
163
+ crossings: 4,
164
+ sticks: 7,
165
+ bridge: 2,
166
+ unknotting: 1
167
+ });
168
+
169
+ /**
170
+ * The Cinquefoil Knot (5₁)
171
+ */
172
+ const CINQUEFOIL = new Knot({
173
+ name: 'Cinquefoil',
174
+ notation: '5_1',
175
+ crossings: 5,
176
+ sticks: 8,
177
+ bridge: 2,
178
+ unknotting: 2
179
+ });
180
+
181
+ /**
182
+ * The Three-Twist Knot (5₂)
183
+ */
184
+ const THREE_TWIST = new Knot({
185
+ name: 'Three-Twist',
186
+ notation: '5_2',
187
+ crossings: 5,
188
+ sticks: 8,
189
+ bridge: 2,
190
+ unknotting: 1
191
+ });
192
+
193
+ /**
194
+ * Collection of standard knots
195
+ */
196
+ const STANDARD_KNOTS = {
197
+ unknot: UNKNOT,
198
+ trefoil: TREFOIL,
199
+ figureEight: FIGURE_EIGHT,
200
+ cinquefoil: CINQUEFOIL,
201
+ threeTwist: THREE_TWIST
202
+ };
203
+
204
+ // ============================================================================
205
+ // PHYSICAL CONSTANT DERIVATION
206
+ // ============================================================================
207
+
208
+ /**
209
+ * PhysicalConstants class for deriving constants from topological invariants
210
+ *
211
+ * The central thesis of 108bio.pdf is that physical constants are
212
+ * topological invariants arising from twist operations in 3D space.
213
+ */
214
+ class PhysicalConstants {
215
+ /**
216
+ * Derive the proton-electron mass ratio
217
+ * Uses Trefoil complexity (17) × 108 invariant = 1836
218
+ *
219
+ * Matches experimental value: m_p/m_e = 1836.15267343(11)
220
+ *
221
+ * @returns {Object} Derived ratio with comparison to experimental
222
+ */
223
+ static protonElectronRatio() {
224
+ const derived = TREFOIL.complexity() * TWIST_108.value;
225
+ const experimental = 1836.15267343;
226
+
227
+ return {
228
+ derived,
229
+ experimental,
230
+ error: Math.abs(derived - experimental),
231
+ relativeError: Math.abs(derived - experimental) / experimental,
232
+ formula: `${TREFOIL.complexity()} × ${TWIST_108.value} = ${derived}`,
233
+ interpretation: 'Trefoil complexity × 108 invariant'
234
+ };
235
+ }
236
+
237
+ /**
238
+ * Derive the fine structure constant inverse
239
+ * α⁻¹ = 108 + 29 = 137
240
+ *
241
+ * Where 29 is the prime sieve boundary (mod-30 pattern)
242
+ *
243
+ * Matches experimental value: α⁻¹ = 137.035999084(21)
244
+ *
245
+ * @returns {Object} Derived value with comparison
246
+ */
247
+ static fineStructureInverse() {
248
+ const derived = TWIST_108.value + TWIST_108.mod30Boundary;
249
+ const experimental = 137.035999084;
250
+
251
+ return {
252
+ derived,
253
+ experimental,
254
+ error: Math.abs(derived - experimental),
255
+ relativeError: Math.abs(derived - experimental) / experimental,
256
+ formula: `${TWIST_108.value} + ${TWIST_108.mod30Boundary} = ${derived}`,
257
+ interpretation: '108 invariant + prime sieve boundary'
258
+ };
259
+ }
260
+
261
+ /**
262
+ * Predict Higgs boson mass
263
+ * m_H = 5³ = 125 GeV
264
+ *
265
+ * Where 5 is the first prime outside the minimal twist set {2, 3}
266
+ *
267
+ * Matches experimental value: m_H = 125.25 ± 0.17 GeV
268
+ *
269
+ * @returns {Object} Derived mass with comparison
270
+ */
271
+ static higgsMass() {
272
+ const derived = Math.pow(5, 3);
273
+ const experimental = 125.25;
274
+
275
+ return {
276
+ derived,
277
+ experimental,
278
+ unit: 'GeV',
279
+ error: Math.abs(derived - experimental),
280
+ relativeError: Math.abs(derived - experimental) / experimental,
281
+ formula: '5³ = 125',
282
+ interpretation: 'First prime outside minimal twist set, cubed'
283
+ };
284
+ }
285
+
286
+ /**
287
+ * Get all derived physical constants
288
+ */
289
+ static all() {
290
+ return {
291
+ protonElectronRatio: this.protonElectronRatio(),
292
+ fineStructureInverse: this.fineStructureInverse(),
293
+ higgsMass: this.higgsMass()
294
+ };
295
+ }
296
+
297
+ /**
298
+ * Validate the framework by checking error margins
299
+ * @returns {Object} Validation results
300
+ */
301
+ static validate() {
302
+ const constants = this.all();
303
+ const results = {
304
+ protonElectron: {
305
+ matches: constants.protonElectronRatio.relativeError < 0.001,
306
+ accuracy: 1 - constants.protonElectronRatio.relativeError
307
+ },
308
+ fineStructure: {
309
+ matches: constants.fineStructureInverse.relativeError < 0.001,
310
+ accuracy: 1 - constants.fineStructureInverse.relativeError
311
+ },
312
+ higgs: {
313
+ matches: constants.higgsMass.relativeError < 0.01,
314
+ accuracy: 1 - constants.higgsMass.relativeError
315
+ }
316
+ };
317
+
318
+ results.overallValid = results.protonElectron.matches &&
319
+ results.fineStructure.matches &&
320
+ results.higgs.matches;
321
+
322
+ return results;
323
+ }
324
+ }
325
+
326
+ // ============================================================================
327
+ // OBSERVER HIERARCHY
328
+ // ============================================================================
329
+
330
+ /**
331
+ * Observer Hierarchy from 108bio.pdf Table 1
332
+ *
333
+ * Each level represents an observer differing only by scale and complexity
334
+ * of coherence. Observation is universal and recursive.
335
+ */
336
+ const OBSERVER_HIERARCHY = [
337
+ {
338
+ scale: 'Quantum',
339
+ constituentOscillators: 'Wavefunctions',
340
+ entropyGradient: 'Vacuum entropy',
341
+ observableBehavior: 'Collapse of state',
342
+ typicalComplexity: 1,
343
+ primeRange: [2, 3, 5, 7] // Fundamental primes
344
+ },
345
+ {
346
+ scale: 'Molecular',
347
+ constituentOscillators: 'Atomic bonds',
348
+ entropyGradient: 'Thermal flux',
349
+ observableBehavior: 'Chemical organization',
350
+ typicalComplexity: 10,
351
+ primeRange: [2, 3, 5, 7, 11, 13, 17, 19, 23]
352
+ },
353
+ {
354
+ scale: 'Biological',
355
+ constituentOscillators: 'Metabolic cycles',
356
+ entropyGradient: 'Chemical potential',
357
+ observableBehavior: 'Life and adaptation',
358
+ typicalComplexity: 100,
359
+ primeRange: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
360
+ },
361
+ {
362
+ scale: 'Cognitive',
363
+ constituentOscillators: 'Neuronal fields',
364
+ entropyGradient: 'Sensory entropy',
365
+ observableBehavior: 'Awareness and thought',
366
+ typicalComplexity: 1000,
367
+ primeRange: null // Full prime spectrum
368
+ },
369
+ {
370
+ scale: 'Planetary',
371
+ constituentOscillators: 'Biospheric systems',
372
+ entropyGradient: 'Solar entropy',
373
+ observableBehavior: 'Ecological balance',
374
+ typicalComplexity: 10000,
375
+ primeRange: null // Full prime spectrum
376
+ },
377
+ {
378
+ scale: 'Cosmic',
379
+ constituentOscillators: 'Field harmonics',
380
+ entropyGradient: 'Vacuum entropy',
381
+ observableBehavior: 'Gravitational curvature',
382
+ typicalComplexity: 100000,
383
+ primeRange: null // Full prime spectrum
384
+ }
385
+ ];
386
+
387
+ /**
388
+ * Get observer level by scale name
389
+ * @param {string} scale - Scale name
390
+ * @returns {Object|null} Observer level or null
391
+ */
392
+ function getObserverLevel(scale) {
393
+ return OBSERVER_HIERARCHY.find(h => h.scale.toLowerCase() === scale.toLowerCase()) || null;
394
+ }
395
+
396
+ /**
397
+ * Estimate observer capacity from complexity
398
+ * C_obs = α·N_osc·K̄·τ⁻¹
399
+ *
400
+ * @param {number} oscillatorCount - Number of oscillators
401
+ * @param {number} meanCoupling - Mean coupling strength
402
+ * @param {number} coherenceTime - Characteristic coherence time
403
+ * @param {number} alpha - Scaling constant (default 1.0)
404
+ * @returns {number} Observer capacity
405
+ */
406
+ function observerCapacity(oscillatorCount, meanCoupling, coherenceTime, alpha = 1.0) {
407
+ if (coherenceTime <= 0) return 0;
408
+ return alpha * oscillatorCount * meanCoupling / coherenceTime;
409
+ }
410
+
411
+ // ============================================================================
412
+ // GAUGE SYMMETRY FROM 108
413
+ // ============================================================================
414
+
415
+ /**
416
+ * Derive gauge group structure from the 108 invariant
417
+ *
418
+ * 108 = 2² × 3³ generates:
419
+ * - 3³ → SU(3) color symmetry (ternary, 120° twist)
420
+ * - 2² → SU(2) weak symmetry (binary, 180° twist)
421
+ * - Full 108 → U(1) electromagnetic (360° complete rotation)
422
+ */
423
+ class GaugeSymmetry {
424
+ /**
425
+ * Get the SU(3) contribution (color)
426
+ * Generated by 3³ = 27, with 120° twist angle
427
+ */
428
+ static su3() {
429
+ return {
430
+ name: 'SU(3)',
431
+ type: 'Color',
432
+ generator: Math.pow(3, 3),
433
+ twistAngle: 360 / 3,
434
+ symmetryType: 'ternary',
435
+ description: 'Strong force color symmetry'
436
+ };
437
+ }
438
+
439
+ /**
440
+ * Get the SU(2) contribution (weak)
441
+ * Generated by 2² = 4, with 180° twist angle
442
+ */
443
+ static su2() {
444
+ return {
445
+ name: 'SU(2)',
446
+ type: 'Weak',
447
+ generator: Math.pow(2, 2),
448
+ twistAngle: 360 / 2,
449
+ symmetryType: 'binary',
450
+ description: 'Weak force isospin symmetry'
451
+ };
452
+ }
453
+
454
+ /**
455
+ * Get the U(1) contribution (electromagnetic)
456
+ * Generated by full 108, with 360° complete rotation
457
+ */
458
+ static u1() {
459
+ return {
460
+ name: 'U(1)',
461
+ type: 'Electromagnetic',
462
+ generator: TWIST_108.value,
463
+ twistAngle: 360,
464
+ symmetryType: 'unitary',
465
+ description: 'Electromagnetic phase symmetry'
466
+ };
467
+ }
468
+
469
+ /**
470
+ * Get the full Standard Model gauge group
471
+ * SU(3) × SU(2) × U(1)
472
+ */
473
+ static standardModel() {
474
+ return {
475
+ name: 'SU(3) × SU(2) × U(1)',
476
+ components: [this.su3(), this.su2(), this.u1()],
477
+ generator: TWIST_108.value,
478
+ factorization: `${TWIST_108.value} = ${TWIST_108.binary} × ${TWIST_108.ternary}`,
479
+ description: 'Complete Standard Model gauge group from 108 invariant'
480
+ };
481
+ }
482
+
483
+ /**
484
+ * Verify that a number exhibits the gauge structure
485
+ * @param {number} n - Number to check
486
+ * @returns {Object} Gauge decomposition
487
+ */
488
+ static decompose(n) {
489
+ const factors = factorize(n);
490
+
491
+ return {
492
+ value: n,
493
+ factors,
494
+ su3Strength: Math.pow(3, factors[3] || 0),
495
+ su2Strength: Math.pow(2, factors[2] || 0),
496
+ u1Strength: Object.keys(factors)
497
+ .filter(p => p !== '2' && p !== '3')
498
+ .reduce((prod, p) => prod * Math.pow(parseInt(p), factors[p]), 1),
499
+ is108Resonant: TWIST_108.resonates(n)
500
+ };
501
+ }
502
+ }
503
+
504
+ // ============================================================================
505
+ // FREE ENERGY DYNAMICS
506
+ // ============================================================================
507
+
508
+ /**
509
+ * Free Energy Principle (FEP) dynamics from 108bio.pdf Section 4.2
510
+ *
511
+ * Consciousness modeled as minimization of epistemic surprise via
512
+ * the cubic dynamics: dψ/dt = αψ + βψ² + γψ³
513
+ *
514
+ * This describes the collapse of modal superpositions into stable "now".
515
+ */
516
+ class FreeEnergyDynamics {
517
+ /**
518
+ * Create FEP dynamics with specified coefficients
519
+ * @param {number} alpha - Linear term coefficient (drift)
520
+ * @param {number} beta - Quadratic term coefficient (bifurcation)
521
+ * @param {number} gamma - Cubic term coefficient (stabilization)
522
+ */
523
+ constructor(alpha = 0.1, beta = -0.5, gamma = -0.1) {
524
+ this.alpha = alpha;
525
+ this.beta = beta;
526
+ this.gamma = gamma;
527
+ }
528
+
529
+ /**
530
+ * Compute derivative dψ/dt
531
+ * @param {number} psi - Current state
532
+ * @returns {number} Rate of change
533
+ */
534
+ derivative(psi) {
535
+ return this.alpha * psi + this.beta * psi * psi + this.gamma * psi * psi * psi;
536
+ }
537
+
538
+ /**
539
+ * Evolve state by one time step (Euler method)
540
+ * @param {number} psi - Current state
541
+ * @param {number} dt - Time step
542
+ * @returns {number} New state
543
+ */
544
+ step(psi, dt = 0.01) {
545
+ return psi + this.derivative(psi) * dt;
546
+ }
547
+
548
+ /**
549
+ * Find fixed points of the dynamics
550
+ * Roots of αψ + βψ² + γψ³ = 0
551
+ * ψ(α + βψ + γψ²) = 0
552
+ *
553
+ * @returns {Array<Object>} Fixed points with stability info
554
+ */
555
+ fixedPoints() {
556
+ const points = [{ value: 0, stability: 'depends on α' }];
557
+
558
+ // Quadratic formula for ψ² + (β/γ)ψ + (α/γ) = 0
559
+ if (this.gamma !== 0) {
560
+ const a = this.gamma;
561
+ const b = this.beta;
562
+ const c = this.alpha;
563
+
564
+ const discriminant = b * b - 4 * a * c;
565
+
566
+ if (discriminant >= 0) {
567
+ const sqrtD = Math.sqrt(discriminant);
568
+ const psi1 = (-b + sqrtD) / (2 * a);
569
+ const psi2 = (-b - sqrtD) / (2 * a);
570
+
571
+ // Stability from derivative of dψ/dt
572
+ const stability1 = this.stabilityAt(psi1);
573
+ const stability2 = this.stabilityAt(psi2);
574
+
575
+ points.push({ value: psi1, stability: stability1 });
576
+ points.push({ value: psi2, stability: stability2 });
577
+ }
578
+ }
579
+
580
+ return points;
581
+ }
582
+
583
+ /**
584
+ * Determine stability at a point
585
+ * Stable if d(dψ/dt)/dψ < 0
586
+ */
587
+ stabilityAt(psi) {
588
+ const dfdpsi = this.alpha + 2 * this.beta * psi + 3 * this.gamma * psi * psi;
589
+ if (dfdpsi < -0.001) return 'stable';
590
+ if (dfdpsi > 0.001) return 'unstable';
591
+ return 'marginal';
592
+ }
593
+
594
+ /**
595
+ * Compute potential function V(ψ) where dψ/dt = -dV/dψ
596
+ * V = -αψ²/2 - βψ³/3 - γψ⁴/4
597
+ */
598
+ potential(psi) {
599
+ return -(this.alpha * psi * psi / 2 +
600
+ this.beta * psi * psi * psi / 3 +
601
+ this.gamma * psi * psi * psi * psi / 4);
602
+ }
603
+
604
+ /**
605
+ * Simulate trajectory from initial condition
606
+ * @param {number} psi0 - Initial state
607
+ * @param {number} duration - Simulation duration
608
+ * @param {number} dt - Time step
609
+ * @returns {Array<Object>} Trajectory points
610
+ */
611
+ simulate(psi0, duration = 10, dt = 0.01) {
612
+ const trajectory = [];
613
+ let psi = psi0;
614
+ let t = 0;
615
+
616
+ while (t < duration) {
617
+ trajectory.push({ t, psi, potential: this.potential(psi) });
618
+ psi = this.step(psi, dt);
619
+ t += dt;
620
+ }
621
+
622
+ return trajectory;
623
+ }
624
+ }
625
+
626
+ // ============================================================================
627
+ // EXPORTS
628
+ // ============================================================================
629
+
630
+ module.exports = {
631
+ // Knot classes
632
+ Knot,
633
+
634
+ // Standard knots
635
+ UNKNOT,
636
+ TREFOIL,
637
+ FIGURE_EIGHT,
638
+ CINQUEFOIL,
639
+ THREE_TWIST,
640
+ STANDARD_KNOTS,
641
+
642
+ // Physical constants
643
+ PhysicalConstants,
644
+
645
+ // Observer hierarchy
646
+ OBSERVER_HIERARCHY,
647
+ getObserverLevel,
648
+ observerCapacity,
649
+
650
+ // Gauge symmetry
651
+ GaugeSymmetry,
652
+
653
+ // Free energy dynamics
654
+ FreeEnergyDynamics
655
+ };