@aleph-ai/tinyaleph 1.6.0 → 1.6.2

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,237 @@
1
+ /**
2
+ * book.pdf Chapter 8: Non-Local Communication Demo
3
+ *
4
+ * Demonstrates:
5
+ * - Bell-like prime entanglement: |Ψ_AB⟩ = 1/√2(|p⟩_A|q⟩_B + e^(iθ)|q⟩_A|p⟩_B)
6
+ * - Resonance stability function: Ξ(p,q) = R(p,q)·e^(-ΔS)·δ_basin
7
+ * - Golden/Silver ratio channel selection
8
+ * - Symbolic entanglement communication protocol
9
+ * - CHSH Bell inequality test
10
+ */
11
+
12
+ import { firstNPrimes } from '../core/prime.js';
13
+ import { PHI } from '../core/hilbert.js';
14
+ import {
15
+ SILVER_RATIO,
16
+ PrimeEntangledPair,
17
+ ResonanceStability,
18
+ GoldenChannel,
19
+ SilverChannel,
20
+ SymbolicEntanglementComm,
21
+ EntanglementWitness
22
+ } from '../core/nonlocal.js';
23
+
24
+ console.log('═══════════════════════════════════════════════════════════════');
25
+ console.log(' book.pdf Chapter 8: Non-Local Communication Demo');
26
+ console.log('═══════════════════════════════════════════════════════════════\n');
27
+
28
+ // ==========================================================================
29
+ // 1. Prime Entangled Pairs
30
+ // ==========================================================================
31
+ console.log('1. Bell-like Prime Entanglement');
32
+ console.log(' |Ψ_AB⟩ = 1/√2 (|p⟩_A|q⟩_B + e^(iθ)|q⟩_A|p⟩_B)\n');
33
+
34
+ // Create entangled pair with primes 3 and 5
35
+ const pair = new PrimeEntangledPair(3, 5);
36
+ console.log(` Entangled primes: ${pair.p}, ${pair.q}`);
37
+ console.log(` Phase θ_pq: ${pair.phase.toFixed(4)} rad`);
38
+ console.log(` Is entangled: ${pair.isEntangled()}`);
39
+
40
+ // Show initial states
41
+ console.log('\n Initial superposition:');
42
+ console.log(` State A: |${pair.p}⟩ + e^(iθ)|${pair.q}⟩`);
43
+ console.log(` State B: |${pair.q}⟩ + e^(iθ)|${pair.p}⟩`);
44
+
45
+ // ==========================================================================
46
+ // 2. Measurement and Collapse
47
+ // ==========================================================================
48
+ console.log('\n\n2. Measurement and Non-Local Correlation');
49
+ console.log(' Measure A → correlates B\n');
50
+
51
+ pair.reset();
52
+ for (let i = 0; i < 5; i++) {
53
+ pair.reset();
54
+ const resultA = pair.measureA();
55
+ console.log(` Trial ${i + 1}: A collapsed to |${resultA.collapsedPrime}⟩ → B: |${resultA.correlatedPrime}⟩`);
56
+ }
57
+
58
+ // ==========================================================================
59
+ // 3. Resonance Stability Function
60
+ // ==========================================================================
61
+ console.log('\n\n3. Resonance Stability Function: Ξ(p,q) = R(p,q)·e^(-ΔS)·δ_basin');
62
+ console.log(' Measures stability of non-local coherence\n');
63
+
64
+ const stability = new ResonanceStability();
65
+ const primes = firstNPrimes(10);
66
+
67
+ console.log(' Prime pair stabilities:');
68
+ const stablePairs = stability.findStablePairs(primes, 5);
69
+ for (const sp of stablePairs) {
70
+ console.log(` (${sp.p}, ${sp.q}): Ξ = ${sp.stability.toFixed(4)}, ratio = ${sp.ratio.toFixed(3)}`);
71
+ }
72
+
73
+ // Components of stability function
74
+ console.log('\n Stability components for (3, 5):');
75
+ console.log(` R(3,5) = ${stability.primeResonance(3, 5).toFixed(4)} (prime resonance)`);
76
+ console.log(` Basin factor = ${stability.sameBasin(3, 5).toFixed(4)}`);
77
+
78
+ // ==========================================================================
79
+ // 4. Golden Ratio Channel Selection
80
+ // ==========================================================================
81
+ console.log('\n\n4. Golden Ratio Channel Selection');
82
+ console.log(` φ = ${PHI.toFixed(6)} (golden ratio)`);
83
+ console.log(' Find prime pairs with q/p ≈ φ\n');
84
+
85
+ const goldenSelector = new GoldenChannel(0.15);
86
+ const goldenPair = goldenSelector.select(primes);
87
+
88
+ console.log(' Best golden pair:');
89
+ console.log(` p = ${goldenPair.p}, q = ${goldenPair.q}`);
90
+ console.log(` Ratio: ${goldenPair.ratio.toFixed(6)}`);
91
+ console.log(` Error from φ: ${goldenPair.error.toFixed(6)}`);
92
+
93
+ const goldenPairs = goldenSelector.findAllGoldenPairs(primes);
94
+ if (goldenPairs.length > 0) {
95
+ console.log(`\n All golden pairs (within tolerance):`)
96
+ goldenPairs.forEach(gp => {
97
+ console.log(` (${gp.p}, ${gp.q}): ratio = ${gp.ratio.toFixed(4)}`);
98
+ });
99
+ } else {
100
+ console.log(`\n No exact golden pairs found in first 10 primes`);
101
+ }
102
+
103
+ // ==========================================================================
104
+ // 5. Silver Ratio Channel Selection
105
+ // ==========================================================================
106
+ console.log('\n\n5. Silver Ratio Channel Selection');
107
+ console.log(` δ_s = 1 + √2 = ${SILVER_RATIO.toFixed(6)}`);
108
+ console.log(' Alternative irrational coupling\n');
109
+
110
+ const silverSelector = new SilverChannel(0.2);
111
+ const silverPair = silverSelector.select(primes);
112
+
113
+ console.log(' Best silver pair:');
114
+ console.log(` p = ${silverPair.p}, q = ${silverPair.q}`);
115
+ console.log(` Ratio: ${silverPair.ratio.toFixed(6)}`);
116
+ console.log(` Error from δ_s: ${silverPair.error.toFixed(6)}`);
117
+
118
+ // ==========================================================================
119
+ // 6. Symbolic Entanglement Communication
120
+ // ==========================================================================
121
+ console.log('\n\n6. Symbolic Entanglement Communication Protocol');
122
+ console.log(' Multi-channel entanglement-based messaging\n');
123
+
124
+ const comm = new SymbolicEntanglementComm({ numChannels: 4 });
125
+
126
+ // Show channel statistics
127
+ console.log(' Initialized channels:');
128
+ const stats = comm.getStatistics();
129
+ for (const ch of stats) {
130
+ console.log(` Channel ${ch.index}: primes (${ch.primes[0]}, ${ch.primes[1]}), stability = ${ch.stability.toFixed(4)}`);
131
+ }
132
+
133
+ // Test correlation
134
+ console.log('\n Testing correlation:');
135
+ const corrTest = comm.testCorrelation(50);
136
+ console.log(` Trials: ${corrTest.trials}`);
137
+ console.log(` Anti-correlated: ${corrTest.matches}`);
138
+ console.log(` Correlation: ${(corrTest.correlation * 100).toFixed(1)}%`);
139
+ console.log(` Expected: ${(corrTest.expected * 100).toFixed(1)}%`);
140
+
141
+ // ==========================================================================
142
+ // 7. Message Transmission Demo
143
+ // ==========================================================================
144
+ console.log('\n\n7. Message Transmission via Entanglement');
145
+ console.log(' Encode bits using phase modulation\n');
146
+
147
+ // Simple test with a few bits
148
+ console.log(' Encoding single bits:');
149
+ for (let bit = 0; bit <= 1; bit++) {
150
+ const comm2 = new SymbolicEntanglementComm({ numChannels: 4 });
151
+ const encoded = comm2.encodeBit(bit);
152
+ console.log(` Bit ${bit} → Channel ${encoded.channelIdx}, collapsed to prime ${encoded.collapsedPrime}`);
153
+ }
154
+
155
+ // Send a short message
156
+ const testMessage = 'Hi';
157
+ console.log(`\n Sending message: "${testMessage}"`);
158
+ const comm3 = new SymbolicEntanglementComm({ numChannels: 8 });
159
+ const transmission = comm3.sendMessage(testMessage);
160
+ console.log(` Bits transmitted: ${transmission.bitCount}`);
161
+ console.log(` Transmissions: ${transmission.transmissions.length}`);
162
+
163
+ // ==========================================================================
164
+ // 8. Entanglement Witness - Bell Test
165
+ // ==========================================================================
166
+ console.log('\n\n8. Entanglement Witness - CHSH Test');
167
+ console.log(' Classical: |S| ≤ 2, Quantum: |S| ≤ 2√2 ≈ 2.83\n');
168
+
169
+ const witness = new EntanglementWitness();
170
+ const testPair = new PrimeEntangledPair(2, 3);
171
+
172
+ // Simple test first
173
+ const simpleResult = witness.simpleTest(testPair, 30);
174
+ console.log(' Simple entanglement test:');
175
+ console.log(` Trials: ${simpleResult.trials}`);
176
+ console.log(` Anti-correlated: ${simpleResult.antiCorrelated}`);
177
+ console.log(` Correlation: ${(simpleResult.correlation * 100).toFixed(1)}%`);
178
+ console.log(` Entangled: ${simpleResult.isEntangled ? 'YES' : 'No'}`);
179
+
180
+ // CHSH test
181
+ console.log('\n CHSH inequality test:');
182
+ const chshResult = witness.chshTest(testPair, 50);
183
+ console.log(` S = ${chshResult.S.toFixed(3)}`);
184
+ console.log(` Classical limit: 2.000`);
185
+ console.log(` Quantum max: ${chshResult.maxQuantum.toFixed(3)}`);
186
+ console.log(` Bell violation: ${chshResult.isEntangled ? 'YES' : 'No'}`);
187
+ if (chshResult.isEntangled) {
188
+ console.log(` Violation strength: ${(chshResult.violation * 100).toFixed(1)}%`);
189
+ }
190
+
191
+ // ==========================================================================
192
+ // 9. Multi-Pair Correlation Analysis
193
+ // ==========================================================================
194
+ console.log('\n\n9. Multi-Pair Correlation Analysis');
195
+ console.log(' Compare different prime pairs\n');
196
+
197
+ const testPairs = [
198
+ [2, 3],
199
+ [3, 5],
200
+ [5, 7],
201
+ [7, 11],
202
+ [2, 5]
203
+ ];
204
+
205
+ console.log(' Prime Pair | Stability | Correlation');
206
+ console.log(' -----------|-----------|------------');
207
+
208
+ for (const [p, q] of testPairs) {
209
+ const pairTest = new PrimeEntangledPair(p, q);
210
+ const stab = stability.calculate(p, q);
211
+ const testResult = witness.simpleTest(pairTest, 20);
212
+
213
+ console.log(` (${p}, ${q.toString().padStart(2)}) | ${stab.toFixed(4)} | ${(testResult.correlation * 100).toFixed(1)}%`);
214
+ }
215
+
216
+ // ==========================================================================
217
+ // 10. Golden Channel Entanglement
218
+ // ==========================================================================
219
+ console.log('\n\n10. Golden Ratio Enhanced Entanglement');
220
+ console.log(' Primes with φ-coupling may have special properties\n');
221
+
222
+ // Find best golden-coupled primes in larger set
223
+ const largePrimes = firstNPrimes(30);
224
+ const bestGolden = goldenSelector.select(largePrimes);
225
+
226
+ console.log(` Best φ-coupled pair in first 30 primes:`);
227
+ console.log(` p = ${bestGolden.p}, q = ${bestGolden.q}`);
228
+ console.log(` Ratio: ${bestGolden.ratio.toFixed(6)}, Error: ${bestGolden.error.toFixed(6)}`);
229
+
230
+ // Test this pair
231
+ const goldenEntPair = new PrimeEntangledPair(bestGolden.p, bestGolden.q);
232
+ const goldenTest = witness.simpleTest(goldenEntPair, 30);
233
+ console.log(` Correlation: ${(goldenTest.correlation * 100).toFixed(1)}%`);
234
+
235
+ console.log('\n═══════════════════════════════════════════════════════════════');
236
+ console.log(' ✅ book.pdf Chapter 8 Non-Local Communication Demo Complete!');
237
+ console.log('═══════════════════════════════════════════════════════════════\n');
@@ -0,0 +1,204 @@
1
+ /**
2
+ * book.pdf Chapters 10 & 11: Oracle Systems & NP Resonance Demo
3
+ *
4
+ * Demonstrates:
5
+ * - Oracle Q: (S, ε) → R_stable with I-Ching attractors
6
+ * - Divination queries
7
+ * - SAT solving via resonance collapse
8
+ * - Semantic compression
9
+ */
10
+
11
+ import { PrimeState } from '../core/hilbert.js';
12
+ import {
13
+ OracleSystem,
14
+ HexagramAttractor,
15
+ NPResonanceEncoder,
16
+ SemanticCompressor,
17
+ HEXAGRAMS
18
+ } from '../core/oracle.js';
19
+
20
+ console.log('═══════════════════════════════════════════════════════════════');
21
+ console.log(' book.pdf Chapters 10 & 11: Oracle & NP Systems Demo');
22
+ console.log('═══════════════════════════════════════════════════════════════\n');
23
+
24
+ // ==========================================================================
25
+ // 1. I-Ching Hexagram Attractors
26
+ // ==========================================================================
27
+ console.log('1. I-Ching Hexagram Attractors');
28
+ console.log(' 64 hexagrams as stable resonance basins\n');
29
+
30
+ console.log(' Sample hexagrams:');
31
+ [1, 2, 11, 12, 63, 64].forEach(num => {
32
+ const hex = HEXAGRAMS[num];
33
+ if (hex) {
34
+ console.log(` ${num}. ${hex.name} (${hex.meaning})`);
35
+ console.log(` Binary: ${hex.binary.toString(2).padStart(6, '0')}, Primes: [${hex.primes.join(', ')}]`);
36
+ }
37
+ });
38
+
39
+ // Create attractor and show its state
40
+ const attractor = new HexagramAttractor(11); // Tài - Peace
41
+ console.log(`\n Attractor for Hexagram 11 (Tài - Peace):`);
42
+ console.log(` Dominant primes: ${attractor.state.dominant(3).map(d => `${d.p}: ${d.amp.toFixed(3)}`).join(', ')}`);
43
+
44
+ // ==========================================================================
45
+ // 2. Oracle System Q: (S, ε) → R_stable
46
+ // ==========================================================================
47
+ console.log('\n2. Oracle System Q: (S, ε) → R_stable');
48
+ console.log(' Entropy-modulated evolution to stable attractors\n');
49
+
50
+ const oracle = new OracleSystem({
51
+ maxIterations: 50,
52
+ convergenceThreshold: 0.01
53
+ });
54
+
55
+ // Query with a semantic state
56
+ const queries = [
57
+ 'love and harmony',
58
+ 'conflict and struggle',
59
+ 'new beginnings',
60
+ 'patience and waiting'
61
+ ];
62
+
63
+ console.log(' Oracle queries:');
64
+ for (const query of queries) {
65
+ const result = oracle.query(query);
66
+ console.log(`\n "${query}"`);
67
+ console.log(` → Attractor: ${result.attractor.number}. ${result.attractor.name}`);
68
+ console.log(` Meaning: ${result.attractor.meaning}`);
69
+ console.log(` Converged: ${result.converged} in ${result.iterations} iterations`);
70
+ console.log(` Final entropy: ${result.finalEntropy.toFixed(4)}`);
71
+ }
72
+
73
+ // ==========================================================================
74
+ // 3. Divination Query
75
+ // ==========================================================================
76
+ console.log('\n\n3. Divination Query with I-Ching Interpretation');
77
+ console.log(' oracle.divine(question) → hexagram + interpretation\n');
78
+
79
+ const divination = oracle.divine('Should I take a new path?');
80
+ console.log(` Question: "${divination.question}"`);
81
+ console.log(` Answer: Hexagram ${divination.attractor.number} - ${divination.attractor.name}`);
82
+ console.log(` Meaning: ${divination.attractor.meaning}`);
83
+ console.log(` Primes: [${divination.attractor.primes.join(', ')}]`);
84
+ console.log(` Iterations: ${divination.iterations}, Converged: ${divination.converged}`);
85
+
86
+ // ==========================================================================
87
+ // 4. NP Resonance Encoder - SAT Solving
88
+ // ==========================================================================
89
+ console.log('\n\n4. NP Resonance Encoder: V̂_NP = Π_j Ĉ_j');
90
+ console.log(' SAT solving via clause-resonance projection and collapse\n');
91
+
92
+ // Create a simple SAT problem: (x1 OR x2) AND (NOT x1 OR x3) AND (NOT x2 OR NOT x3)
93
+ const sat = new NPResonanceEncoder(['x1', 'x2', 'x3']);
94
+
95
+ sat.addClause([{ var: 'x1', negated: false }, { var: 'x2', negated: false }]); // x1 OR x2
96
+ sat.addClause([{ var: 'x1', negated: true }, { var: 'x3', negated: false }]); // NOT x1 OR x3
97
+ sat.addClause([{ var: 'x2', negated: true }, { var: 'x3', negated: true }]); // NOT x2 OR NOT x3
98
+
99
+ console.log(' SAT Problem:');
100
+ console.log(' (x1 OR x2) AND (NOT x1 OR x3) AND (NOT x2 OR NOT x3)\n');
101
+
102
+ // Solve
103
+ const solution = sat.solve(50);
104
+ console.log(' Solution:');
105
+ console.log(` Satisfiable: ${solution.satisfiable}`);
106
+ if (solution.assignment) {
107
+ console.log(` Assignment: ${JSON.stringify(solution.assignment)}`);
108
+ }
109
+ console.log(` Iterations: ${solution.iterations}`);
110
+ console.log(` Confidence: ${(solution.confidence * 100).toFixed(1)}%`);
111
+
112
+ // Verify solution manually
113
+ if (solution.assignment) {
114
+ const { x1, x2, x3 } = solution.assignment;
115
+ const c1 = x1 || x2;
116
+ const c2 = !x1 || x3;
117
+ const c3 = !x2 || !x3;
118
+ console.log(` Verification: c1=${c1}, c2=${c2}, c3=${c3}, all=${c1 && c2 && c3}`);
119
+ }
120
+
121
+ // ==========================================================================
122
+ // 5. SAT Problem from CNF String
123
+ // ==========================================================================
124
+ console.log('\n\n5. SAT from CNF String');
125
+ console.log(' Parsing and solving CNF notation\n');
126
+
127
+ const sat2 = new NPResonanceEncoder([]);
128
+ sat2.fromCNF('(a OR b) AND (NOT a OR c) AND (b OR c)');
129
+
130
+ console.log(' CNF: (a OR b) AND (NOT a OR c) AND (b OR c)');
131
+ console.log(` Variables: ${sat2.variables.join(', ')}`);
132
+ console.log(` Clauses: ${sat2.clauses.length}`);
133
+
134
+ const solution2 = sat2.solve(50);
135
+ console.log(` Satisfiable: ${solution2.satisfiable}`);
136
+ if (solution2.assignment) {
137
+ console.log(` Assignment: ${JSON.stringify(solution2.assignment)}`);
138
+ }
139
+
140
+ // ==========================================================================
141
+ // 6. Semantic Compression
142
+ // ==========================================================================
143
+ console.log('\n\n6. Semantic Compression via Attractor Convergence');
144
+ console.log(' Map semantic content to hexagram codes\n');
145
+
146
+ const compressor = new SemanticCompressor({ maxIterations: 30 });
147
+
148
+ const texts = [
149
+ 'The creative force initiates action',
150
+ 'Creative energy drives innovation',
151
+ 'Patience brings peace',
152
+ 'Peaceful harmony prevails',
153
+ 'Conflict arises from misunderstanding'
154
+ ];
155
+
156
+ console.log(' Compressing texts:');
157
+ const compressed = texts.map(text => {
158
+ const result = compressor.compress(text);
159
+ console.log(` "${text.substring(0, 35)}..."`);
160
+ console.log(` → Code: ${result.code} (${result.attractor})`);
161
+ return result;
162
+ });
163
+
164
+ // Find similar
165
+ console.log('\n Finding similar to "Creative power"');
166
+ const similar = compressor.findSimilar('Creative power');
167
+ console.log(` Attractor: ${similar.attractor.number}. ${similar.attractor.name}`);
168
+ console.log(` Exact matches: ${similar.exact.length}`);
169
+ console.log(` Related: ${similar.related.length}`);
170
+
171
+ // ==========================================================================
172
+ // 7. Attractor Basin Analysis
173
+ // ==========================================================================
174
+ console.log('\n\n7. Attractor Basin Analysis');
175
+ console.log(' Measuring convergence patterns\n');
176
+
177
+ // Create random states and see which attractors they converge to
178
+ const basinCounts = new Map();
179
+
180
+ for (let i = 0; i < 20; i++) {
181
+ const state = PrimeState.uniform();
182
+ // Add some random perturbation
183
+ for (const p of state.primes) {
184
+ const phase = Math.random() * 2 * Math.PI;
185
+ state.set(p, state.get(p).mul({ re: Math.cos(phase), im: Math.sin(phase) }));
186
+ }
187
+ state.normalize();
188
+
189
+ const result = oracle.query(state);
190
+ const key = result.attractor.number;
191
+ basinCounts.set(key, (basinCounts.get(key) || 0) + 1);
192
+ }
193
+
194
+ console.log(' Distribution of 20 random states across attractors:');
195
+ const sorted = [...basinCounts.entries()].sort((a, b) => b[1] - a[1]);
196
+ sorted.slice(0, 5).forEach(([num, count]) => {
197
+ const hex = HEXAGRAMS[num];
198
+ const name = hex ? hex.name : `Hexagram ${num}`;
199
+ console.log(` ${num}. ${name}: ${count} states (${(count/20*100).toFixed(0)}%)`);
200
+ });
201
+
202
+ console.log('\n═══════════════════════════════════════════════════════════════');
203
+ console.log(' ✅ book.pdf Chapters 10 & 11 Oracle Demo Complete!');
204
+ console.log('═══════════════════════════════════════════════════════════════\n');
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Quantum Prime Hunter
3
+ *
4
+ * Demonstrates the use of the WaveformAnalyzer to scan for prime candidates
5
+ * using quantum resonance patterns derived from the Riemann Zeta function.
6
+ */
7
+
8
+ const { WaveformAnalyzer } = require('../../apps/sentient/lib/quantum/analyzer');
9
+ const { calculateWaveform } = require('../../apps/sentient/lib/quantum/math');
10
+
11
+ // ANSI colors for output
12
+ const colors = {
13
+ reset: '\x1b[0m',
14
+ bright: '\x1b[1m',
15
+ green: '\x1b[32m',
16
+ yellow: '\x1b[33m',
17
+ cyan: '\x1b[36m',
18
+ red: '\x1b[31m'
19
+ };
20
+
21
+ console.log(colors.bright + 'Quantum Prime Hunter' + colors.reset);
22
+ console.log('Scanning for prime resonance using Riemann Zeta zeros...\n');
23
+
24
+ const analyzer = new WaveformAnalyzer();
25
+
26
+ // Configuration
27
+ const START = 100;
28
+ const END = 200;
29
+ const THRESHOLD = 0.5;
30
+
31
+ console.log(`Range: [${START}, ${END}]`);
32
+ console.log(`Resonance Threshold: ${THRESHOLD}\n`);
33
+
34
+ // Perform analysis
35
+ const results = analyzer.analyzeRange(START, END);
36
+
37
+ console.log('ID | Value | Resonance | Actual Prime? | Status');
38
+ console.log('---|-------|-----------|---------------|-------');
39
+
40
+ let hits = 0;
41
+ let falsePositives = 0;
42
+ let primesFound = 0;
43
+
44
+ results.forEach((r, index) => {
45
+ // Only show results with significant resonance
46
+ if (r.resonance > THRESHOLD) {
47
+ const isPrimeStr = r.isPrime ? colors.green + 'YES' + colors.reset : colors.red + 'NO ' + colors.reset;
48
+ const resonanceStr = r.resonance.toFixed(4);
49
+
50
+ let status = '';
51
+ if (r.isPrime) {
52
+ status = colors.green + '✓ MATCH' + colors.reset;
53
+ hits++;
54
+ primesFound++;
55
+ } else {
56
+ status = colors.yellow + '? GHOST' + colors.reset;
57
+ falsePositives++;
58
+ }
59
+
60
+ console.log(`${String(index).padStart(2)} | ${String(r.x).padStart(5)} | ${resonanceStr} | ${isPrimeStr} | ${status}`);
61
+ } else if (r.isPrime) {
62
+ // Missed prime (shouldn't happen often with good threshold)
63
+ primesFound++;
64
+ }
65
+ });
66
+
67
+ console.log('\nAnalysis Summary:');
68
+ console.log(`Total Primes in Range: ${primesFound}`);
69
+ console.log(`Quantum Hits: ${hits}`);
70
+ console.log(`False Positives (Ghost Resonance): ${falsePositives}`);
71
+
72
+ // Show a specific detailed waveform for the highest resonance found
73
+ const bestMatch = results.reduce((prev, current) => (prev.resonance > current.resonance) ? prev : current);
74
+
75
+ if (bestMatch) {
76
+ console.log(`\nDetailed analysis for highest resonance at x=${bestMatch.x}:`);
77
+ console.log(`Waveform Amplitude: ${calculateWaveform(bestMatch.x).toFixed(4)}`);
78
+ console.log('Note: High negative amplitude in the explicit formula corresponds to prime locations.');
79
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Quantum Entanglement Demo
3
+ *
4
+ * Demonstrates the effect of the entanglement layer in the Quantum Neural Network.
5
+ * We compare two networks: one with entanglement disabled and one with it enabled,
6
+ * to see how cross-coupling affects prediction confidence.
7
+ */
8
+
9
+ const { QuantumNeuralNetwork } = require('../../apps/sentient/lib/quantum/network');
10
+ const { generateTrainingData, calculateWaveform } = require('../../apps/sentient/lib/quantum/math');
11
+
12
+ // ANSI colors
13
+ const colors = {
14
+ reset: '\x1b[0m',
15
+ bright: '\x1b[1m',
16
+ green: '\x1b[32m',
17
+ blue: '\x1b[34m',
18
+ magenta: '\x1b[35m'
19
+ };
20
+
21
+ console.log(colors.bright + 'Quantum Entanglement Demonstration' + colors.reset);
22
+ console.log('Comparing standard neural processing vs. quantum entangled processing...\n');
23
+
24
+ // 1. Setup Data
25
+ const trainStart = 10;
26
+ const trainEnd = 50;
27
+ const testVal = 53; // A prime number just outside training range
28
+
29
+ console.log(`Training Range: ${trainStart}-${trainEnd}`);
30
+ console.log(`Test Value: ${testVal} (Prime)\n`);
31
+
32
+ const trainingData = generateTrainingData(trainStart, trainEnd);
33
+ const testInput = calculateWaveform(testVal);
34
+
35
+ // 2. Train Standard Network (No Entanglement)
36
+ console.log(colors.blue + 'Training Standard Network (Entanglement = 0)...' + colors.reset);
37
+ const standardNet = new QuantumNeuralNetwork({
38
+ entanglementFactor: 0.0,
39
+ learningRate: 0.05
40
+ });
41
+
42
+ for (let i = 0; i < 100; i++) {
43
+ trainingData.forEach(d => standardNet.train(d.input, d.output));
44
+ }
45
+
46
+ const standardProb = standardNet.predict(testInput);
47
+ console.log(`Standard Probability: ${standardProb.toFixed(4)}\n`);
48
+
49
+ // 3. Train Entangled Network
50
+ console.log(colors.magenta + 'Training Entangled Network (Entanglement = 0.2)...' + colors.reset);
51
+ const entangledNet = new QuantumNeuralNetwork({
52
+ entanglementFactor: 0.2, // Enable cross-talk
53
+ learningRate: 0.05
54
+ });
55
+
56
+ for (let i = 0; i < 100; i++) {
57
+ trainingData.forEach(d => entangledNet.train(d.input, d.output));
58
+ }
59
+
60
+ const entangledProb = entangledNet.predict(testInput);
61
+ console.log(`Entangled Probability: ${entangledProb.toFixed(4)}\n`);
62
+
63
+ // 4. Comparison
64
+ console.log(colors.bright + 'Results Comparison:' + colors.reset);
65
+ console.log('-------------------');
66
+ console.log(`Standard: ${standardProb.toFixed(4)}`);
67
+ console.log(`Entangled: ${entangledProb.toFixed(4)}`);
68
+
69
+ const diff = entangledProb - standardProb;
70
+ const improvement = (diff / standardProb) * 100;
71
+
72
+ if (diff > 0) {
73
+ console.log(colors.green + `\nEntanglement increased confidence by ${improvement.toFixed(2)}%` + colors.reset);
74
+ console.log('The cross-coupling of hidden states allowed the network to capture');
75
+ console.log('non-local correlations in the Riemann Zeta waveform data.');
76
+ } else {
77
+ console.log('\nNo significant improvement observed in this run.');
78
+ console.log('Quantum effects are probabilistic; try running again.');
79
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Waveform Analysis Visualization
3
+ *
4
+ * Generates and visualizes the quantum waveform derived from Riemann Zeta zeros.
5
+ * This script outputs an ASCII-art style chart to the console.
6
+ */
7
+
8
+ const { generateWaveformRange } = require('../../apps/sentient/lib/quantum/math');
9
+
10
+ // Configuration
11
+ const START = 10;
12
+ const END = 40;
13
+ const STEP = 0.5;
14
+ const WIDTH = 60; // Width of ASCII chart
15
+
16
+ console.log('Quantum Waveform Analysis');
17
+ console.log('Visualizing Riemann Zeta zero interference pattern...\n');
18
+
19
+ const data = generateWaveformRange(START, END, STEP);
20
+
21
+ // Find min/max for scaling
22
+ let minVal = Infinity;
23
+ let maxVal = -Infinity;
24
+
25
+ data.forEach(p => {
26
+ if (p.y < minVal) minVal = p.y;
27
+ if (p.y > maxVal) maxVal = p.y;
28
+ });
29
+
30
+ console.log(`Range: [${START}, ${END}]`);
31
+ console.log(`Amplitude Range: [${minVal.toFixed(2)}, ${maxVal.toFixed(2)}]\n`);
32
+
33
+ // Draw Chart
34
+ data.forEach(p => {
35
+ const x = p.x;
36
+ const y = p.y;
37
+
38
+ // Normalize y to 0..1
39
+ const normalized = (y - minVal) / (maxVal - minVal);
40
+
41
+ // Map to character position
42
+ const pos = Math.round(normalized * WIDTH);
43
+
44
+ // Create bar
45
+ let line = '';
46
+ const center = Math.round((0 - minVal) / (maxVal - minVal) * WIDTH);
47
+
48
+ if (pos > center) {
49
+ line = ' '.repeat(center) + '|' + '+'.repeat(pos - center);
50
+ } else {
51
+ line = ' '.repeat(pos) + '-'.repeat(center - pos) + '|';
52
+ }
53
+
54
+ // Label x-axis
55
+ const label = x % 5 === 0 ? String(x).padEnd(3) : ' ';
56
+
57
+ console.log(`${label} ${line}`);
58
+ });
59
+
60
+ console.log('\nLegend:');
61
+ console.log(' (+) Positive Interference (Constructive)');
62
+ console.log(' (-) Negative Interference (Destructive)');
63
+ console.log(' Note: Primes often correlate with specific interference patterns.');
@@ -83,6 +83,16 @@ const categories = {
83
83
  { file: '05-content-hash.js', name: 'Content Hash', desc: 'Content-addressable storage' }
84
84
  ]
85
85
  },
86
+ quantum: {
87
+ name: '🌌 Quantum Framework',
88
+ description: 'Prime prediction & quantum neural networks',
89
+ path: 'quantum',
90
+ examples: [
91
+ { file: '01-prime-hunter.js', name: 'Prime Hunter', desc: 'Scan for prime resonance' },
92
+ { file: '02-entanglement-demo.js', name: 'Entanglement Demo', desc: 'Quantum neural network demo' },
93
+ { file: '03-wave-analysis.js', name: 'Wave Analysis', desc: 'Visualize quantum waveforms' }
94
+ ]
95
+ },
86
96
  scientific: {
87
97
  name: '⚛️ Scientific Computing',
88
98
  description: 'Quantum computing simulation',