@aleph-ai/tinyaleph 1.5.7 → 1.6.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/core/alexander-module.js +1469 -0
- package/core/arithmetic-link-kernel.js +1338 -0
- package/core/index.js +95 -2
- package/examples/01-hello-world.js +69 -0
- package/examples/02-basic-hash.js +90 -0
- package/examples/02-observer-stack.js +385 -0
- package/examples/03-quantum-coin.js +136 -0
- package/examples/05-symbolic-resonance.js +146 -0
- package/examples/06-symbol-database.js +150 -0
- package/examples/07-semantic-inference.js +223 -0
- package/examples/08-compound-symbols.js +219 -0
- package/examples/README.md +170 -0
- package/examples/ai/01-embeddings.js +155 -0
- package/examples/ai/02-semantic-memory.js +243 -0
- package/examples/ai/03-reasoning.js +243 -0
- package/examples/ai/04-knowledge-graph.js +279 -0
- package/examples/ai/05-llm-integration.js +333 -0
- package/examples/ai/06-agent.js +294 -0
- package/examples/ai/07-hybrid-ai.js +223 -0
- package/examples/ai/08-entropy-reasoning.js +259 -0
- package/examples/ai/09-concept-learning.js +271 -0
- package/examples/ai/10-prompt-primes.js +312 -0
- package/examples/ai/11-rag.js +332 -0
- package/examples/ai/12-neuro-symbolic.js +321 -0
- package/examples/ai/README.md +80 -0
- package/examples/arithmetic-topology/01-legendre-symbol.js +78 -0
- package/examples/arithmetic-topology/02-redei-symbol.js +126 -0
- package/examples/arithmetic-topology/03-alk-kuramoto.js +138 -0
- package/examples/arithmetic-topology/04-alexander-module.js +117 -0
- package/examples/arithmetic-topology/05-signature-memory.js +118 -0
- package/examples/arithmetic-topology/README.md +291 -0
- package/examples/bioinformatics/01-dna-encoding.js +108 -0
- package/examples/bioinformatics/02-central-dogma.js +162 -0
- package/examples/bioinformatics/03-protein-folding.js +206 -0
- package/examples/bioinformatics/04-dna-computing.js +192 -0
- package/examples/bioinformatics/05-molecular-binding.js +209 -0
- package/examples/chat.js +105 -0
- package/examples/crt-homology/01-residue-encoding.js +87 -0
- package/examples/crt-homology/02-birkhoff-attention.js +100 -0
- package/examples/crt-homology/03-homology-loss.js +132 -0
- package/examples/crt-homology/04-crt-resoformer.js +132 -0
- package/examples/crt-homology/README.md +67 -0
- package/examples/crypto/01-password-hash.js +210 -0
- package/examples/crypto/02-key-derivation.js +210 -0
- package/examples/crypto/03-hmac.js +229 -0
- package/examples/crypto/04-file-integrity.js +263 -0
- package/examples/crypto/05-content-hash.js +263 -0
- package/examples/crypto/README.md +99 -0
- package/examples/demo-modular.js +223 -0
- package/examples/demo-two-layer.js +196 -0
- package/examples/discrete/01-integer-sine-table.js +120 -0
- package/examples/discrete/02-codebook-tunneling.js +118 -0
- package/examples/discrete/03-canonical-fusion.js +135 -0
- package/examples/discrete/04-tick-gate.js +139 -0
- package/examples/discrete/README.md +142 -0
- package/examples/formal-semantics/01-typed-terms.js +156 -0
- package/examples/formal-semantics/02-reduction.js +202 -0
- package/examples/formal-semantics/03-lambda-translation.js +206 -0
- package/examples/formal-semantics/04-enochian-language.js +257 -0
- package/examples/formal-semantics/README.md +98 -0
- package/examples/math/01-quaternions.js +237 -0
- package/examples/math/02-octonions.js +192 -0
- package/examples/math/03-prime-factorization.js +215 -0
- package/examples/math/04-vector-spaces.js +210 -0
- package/examples/math/05-gaussian-primes.js +234 -0
- package/examples/math/README.md +93 -0
- package/examples/physics/01-oscillator.js +177 -0
- package/examples/physics/02-lyapunov.js +201 -0
- package/examples/physics/03-collapse.js +183 -0
- package/examples/physics/04-kuramoto.js +212 -0
- package/examples/physics/05-entropy.js +226 -0
- package/examples/physics/05-sync-models.js +298 -0
- package/examples/physics/06-primeon-ladder.js +233 -0
- package/examples/physics/07-kuramoto-coupled-ladder.js +298 -0
- package/examples/physics/README.md +126 -0
- package/examples/resonance/01-prime-hilbert-space.js +140 -0
- package/examples/resonance/02-prime-resonance-network.js +221 -0
- package/examples/resonance/03-resoformer.js +349 -0
- package/examples/resonance/04-resoformer-training.js +329 -0
- package/examples/resonance/05-language-model.js +484 -0
- package/examples/resonance/README.md +238 -0
- package/examples/run-examples.js +417 -0
- package/examples/scientific/01-single-qubit.js +185 -0
- package/examples/scientific/02-two-qubit.js +209 -0
- package/examples/scientific/03-quantum-circuits.js +270 -0
- package/examples/scientific/04-measurement.js +229 -0
- package/examples/scientific/05-algorithms.js +245 -0
- package/examples/scientific/06-random.js +225 -0
- package/examples/scientific/07-wavefunction.js +192 -0
- package/examples/scientific/README.md +118 -0
- package/examples/semantic/01-vocabulary.js +186 -0
- package/examples/semantic/02-similarity.js +263 -0
- package/examples/semantic/03-word-algebra.js +295 -0
- package/examples/semantic/04-clustering.js +348 -0
- package/examples/semantic/05-classification.js +386 -0
- package/examples/semantic/06-dna-encoding.js +228 -0
- package/examples/semantic/07-search.js +304 -0
- package/examples/semantic/08-qa-system.js +278 -0
- package/examples/semantic/README.md +116 -0
- package/examples/topology/01-108-invariant.js +81 -0
- package/examples/topology/02-trefoil-constants.js +112 -0
- package/examples/topology/03-gauge-symmetry.js +112 -0
- package/examples/topology/04-free-energy-dynamics.js +124 -0
- package/examples/topology/README.md +129 -0
- package/index.js +32 -0
- package/modular.js +63 -2
- package/package.json +8 -3
- package/physics/alk-kuramoto.js +817 -0
- package/physics/index.js +23 -2
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @example Molecular Binding
|
|
3
|
+
* @description Analyze molecular binding affinity using spectral coherence
|
|
4
|
+
*
|
|
5
|
+
* This example demonstrates how TinyAleph calculates binding affinity
|
|
6
|
+
* between molecules using spectral coherence of their hypercomplex states.
|
|
7
|
+
* Higher coherence = stronger binding affinity.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const { BioinformaticsBackend } = require('../../modular');
|
|
11
|
+
|
|
12
|
+
// Import encoding functions directly for protein encoding
|
|
13
|
+
const encoding = require('../../backends/bioinformatics/encoding');
|
|
14
|
+
|
|
15
|
+
// ===========================================
|
|
16
|
+
// SETUP
|
|
17
|
+
// ===========================================
|
|
18
|
+
|
|
19
|
+
const backend = new BioinformaticsBackend();
|
|
20
|
+
|
|
21
|
+
// ===========================================
|
|
22
|
+
// SEQUENCE SIMILARITY
|
|
23
|
+
// ===========================================
|
|
24
|
+
|
|
25
|
+
console.log('TinyAleph Molecular Binding Example');
|
|
26
|
+
console.log('====================================\n');
|
|
27
|
+
|
|
28
|
+
console.log('SEQUENCE SIMILARITY ANALYSIS');
|
|
29
|
+
console.log('----------------------------\n');
|
|
30
|
+
|
|
31
|
+
// Compare similar and different sequences
|
|
32
|
+
const sequences = [
|
|
33
|
+
{ name: 'Seq A', seq: 'ATGCATGC' },
|
|
34
|
+
{ name: 'Seq B', seq: 'ATGCATGC' }, // Identical to A
|
|
35
|
+
{ name: 'Seq C', seq: 'ATGGATGC' }, // One mutation from A
|
|
36
|
+
{ name: 'Seq D', seq: 'TACGTACG' }, // Complement of A
|
|
37
|
+
{ name: 'Seq E', seq: 'GGGGCCCC' }, // Completely different
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
// Encode all sequences
|
|
41
|
+
const states = sequences.map(s => ({
|
|
42
|
+
...s,
|
|
43
|
+
primes: backend.encode(s.seq),
|
|
44
|
+
state: backend.primesToState(backend.encode(s.seq))
|
|
45
|
+
}));
|
|
46
|
+
|
|
47
|
+
console.log('Sequences:');
|
|
48
|
+
sequences.forEach(s => console.log(` ${s.name}: ${s.seq}`));
|
|
49
|
+
|
|
50
|
+
console.log('\nSimilarity Matrix (based on sequence similarity):');
|
|
51
|
+
console.log(' ' + sequences.map(s => s.name.padEnd(7)).join(''));
|
|
52
|
+
console.log(' ' + sequences.map(() => '-------').join(''));
|
|
53
|
+
|
|
54
|
+
for (let i = 0; i < states.length; i++) {
|
|
55
|
+
let row = states[i].name + ': ';
|
|
56
|
+
for (let j = 0; j < states.length; j++) {
|
|
57
|
+
const sim = backend.similarity(states[i].primes, states[j].primes);
|
|
58
|
+
row += (typeof sim === 'number' ? Math.abs(sim).toFixed(3) : 'N/A').padEnd(8);
|
|
59
|
+
}
|
|
60
|
+
console.log(row);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ===========================================
|
|
64
|
+
// PROTEIN-DNA BINDING
|
|
65
|
+
// ===========================================
|
|
66
|
+
|
|
67
|
+
console.log('\n\nPROTEIN-DNA BINDING AFFINITY');
|
|
68
|
+
console.log('----------------------------\n');
|
|
69
|
+
|
|
70
|
+
// Define a DNA binding site and different proteins
|
|
71
|
+
const dnaBindingSite = 'ATGCATGC';
|
|
72
|
+
|
|
73
|
+
// Proteins with different binding preferences (simplified)
|
|
74
|
+
const proteins = [
|
|
75
|
+
{ name: 'Protein 1', seq: 'MHLA' }, // Hypothetical DNA-binding protein
|
|
76
|
+
{ name: 'Protein 2', seq: 'WFIV' }, // Hydrophobic - unlikely to bind DNA
|
|
77
|
+
{ name: 'Protein 3', seq: 'KRKR' }, // Positively charged - binds DNA backbone
|
|
78
|
+
];
|
|
79
|
+
|
|
80
|
+
console.log('DNA Binding Site:', dnaBindingSite);
|
|
81
|
+
console.log('\nProtein Binding Affinities:');
|
|
82
|
+
|
|
83
|
+
const dnaPrimes = backend.encode(dnaBindingSite);
|
|
84
|
+
|
|
85
|
+
for (const protein of proteins) {
|
|
86
|
+
// Encode protein using the encoding module
|
|
87
|
+
const proteinPrimes = encoding.encodeProtein(protein.seq);
|
|
88
|
+
const result = backend.bindingAffinity(dnaPrimes, proteinPrimes);
|
|
89
|
+
const affinity = result.affinity || result;
|
|
90
|
+
|
|
91
|
+
// Classify affinity
|
|
92
|
+
let classification;
|
|
93
|
+
const absAffinity = Math.abs(affinity);
|
|
94
|
+
if (absAffinity > 0.5) classification = 'Strong';
|
|
95
|
+
else if (absAffinity > 0.2) classification = 'Moderate';
|
|
96
|
+
else classification = 'Weak';
|
|
97
|
+
|
|
98
|
+
console.log(`\n ${protein.name} (${protein.seq}):`);
|
|
99
|
+
console.log(` Affinity score: ${(typeof affinity === 'number' ? affinity : 0).toFixed(4)}`);
|
|
100
|
+
console.log(` Classification: ${classification}`);
|
|
101
|
+
if (result.goldenPairs) {
|
|
102
|
+
console.log(` Golden pairs: ${result.goldenPairs}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ===========================================
|
|
107
|
+
// COMPLEMENTARY STRAND BINDING
|
|
108
|
+
// ===========================================
|
|
109
|
+
|
|
110
|
+
console.log('\n\nCOMPLEMENTARY STRAND BINDING');
|
|
111
|
+
console.log('-----------------------------\n');
|
|
112
|
+
|
|
113
|
+
const strand1 = 'ATGCATGC';
|
|
114
|
+
const COMPLEMENT = { 'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G' };
|
|
115
|
+
const complement = strand1.split('').map(b => COMPLEMENT[b]).join('');
|
|
116
|
+
const mismatch = 'TACGAAAA'; // Partial mismatch
|
|
117
|
+
|
|
118
|
+
console.log('Template strand: ', strand1);
|
|
119
|
+
console.log('True complement: ', complement);
|
|
120
|
+
console.log('Mismatched strand: ', mismatch);
|
|
121
|
+
|
|
122
|
+
const templatePrimes = backend.encode(strand1);
|
|
123
|
+
const complementPrimes = backend.encode(complement);
|
|
124
|
+
const mismatchPrimes = backend.encode(mismatch);
|
|
125
|
+
|
|
126
|
+
const perfectResult = backend.bindingAffinity(templatePrimes, complementPrimes);
|
|
127
|
+
const imperfectResult = backend.bindingAffinity(templatePrimes, mismatchPrimes);
|
|
128
|
+
|
|
129
|
+
const perfectBinding = perfectResult.affinity || perfectResult;
|
|
130
|
+
const imperfectBinding = imperfectResult.affinity || imperfectResult;
|
|
131
|
+
|
|
132
|
+
console.log('\nBinding affinities:');
|
|
133
|
+
console.log(` Perfect complement: ${(typeof perfectBinding === 'number' ? perfectBinding : 0).toFixed(4)}`);
|
|
134
|
+
console.log(` Mismatched strand: ${(typeof imperfectBinding === 'number' ? imperfectBinding : 0).toFixed(4)}`);
|
|
135
|
+
|
|
136
|
+
// ===========================================
|
|
137
|
+
// DRUG-TARGET INTERACTION (CONCEPTUAL)
|
|
138
|
+
// ===========================================
|
|
139
|
+
|
|
140
|
+
console.log('\n\nDRUG-TARGET INTERACTION MODEL');
|
|
141
|
+
console.log('------------------------------\n');
|
|
142
|
+
|
|
143
|
+
// Model a drug molecule as a short peptide
|
|
144
|
+
const targetProtein = 'MWLKFVIER';
|
|
145
|
+
const drugs = [
|
|
146
|
+
{ name: 'Drug A', seq: 'FW' }, // Aromatic - may bind hydrophobic pocket
|
|
147
|
+
{ name: 'Drug B', seq: 'KR' }, // Charged - binds surface
|
|
148
|
+
{ name: 'Drug C', seq: 'LI' }, // Hydrophobic - binds core
|
|
149
|
+
];
|
|
150
|
+
|
|
151
|
+
console.log('Target protein:', targetProtein);
|
|
152
|
+
console.log('\nDrug screening results:');
|
|
153
|
+
|
|
154
|
+
const targetPrimes = encoding.encodeProtein(targetProtein);
|
|
155
|
+
|
|
156
|
+
for (const drug of drugs) {
|
|
157
|
+
const drugPrimes = encoding.encodeProtein(drug.seq);
|
|
158
|
+
const result = backend.bindingAffinity(targetPrimes, drugPrimes);
|
|
159
|
+
const score = result.affinity || result;
|
|
160
|
+
|
|
161
|
+
let verdict;
|
|
162
|
+
const absScore = Math.abs(typeof score === 'number' ? score : 0);
|
|
163
|
+
if (absScore > 0.4) verdict = '★★★ Lead candidate';
|
|
164
|
+
else if (absScore > 0.2) verdict = '★★ Further study';
|
|
165
|
+
else verdict = '★ Low priority';
|
|
166
|
+
|
|
167
|
+
console.log(`\n ${drug.name} (${drug.seq}):`);
|
|
168
|
+
console.log(` Binding score: ${(typeof score === 'number' ? score : 0).toFixed(4)}`);
|
|
169
|
+
console.log(` Verdict: ${verdict}`);
|
|
170
|
+
if (result.interactions) {
|
|
171
|
+
console.log(` Interactions: ${result.interactions.length}`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// ===========================================
|
|
176
|
+
// BINDING MECHANICS
|
|
177
|
+
// ===========================================
|
|
178
|
+
|
|
179
|
+
console.log('\n\nBINDING MECHANICS (Prime Resonance)');
|
|
180
|
+
console.log('------------------------------------\n');
|
|
181
|
+
|
|
182
|
+
console.log('How binding affinity is calculated:');
|
|
183
|
+
console.log('');
|
|
184
|
+
console.log(' 1. Each molecule encoded as hypercomplex state');
|
|
185
|
+
console.log(' - Nucleotides/amino acids → prime numbers');
|
|
186
|
+
console.log(' - Primes → oscillator frequencies');
|
|
187
|
+
console.log(' - Frequencies → sedenion components');
|
|
188
|
+
console.log('');
|
|
189
|
+
console.log(' 2. Binding affinity = spectral coherence');
|
|
190
|
+
console.log(' - Inner product of normalized states');
|
|
191
|
+
console.log(' - Higher coherence = more resonance');
|
|
192
|
+
console.log(' - Resonance implies favorable interaction');
|
|
193
|
+
console.log('');
|
|
194
|
+
console.log(' 3. Physical interpretation:');
|
|
195
|
+
console.log(' - Shape complementarity → frequency matching');
|
|
196
|
+
console.log(' - Electrostatic fit → prime product harmony');
|
|
197
|
+
console.log(' - Hydrophobic matching → low-frequency resonance');
|
|
198
|
+
|
|
199
|
+
// ===========================================
|
|
200
|
+
// KEY TAKEAWAYS
|
|
201
|
+
// ===========================================
|
|
202
|
+
|
|
203
|
+
console.log('\n====================================');
|
|
204
|
+
console.log('KEY TAKEAWAYS:');
|
|
205
|
+
console.log('1. Binding affinity modeled as spectral coherence');
|
|
206
|
+
console.log('2. Complementary sequences show high coherence');
|
|
207
|
+
console.log('3. Can screen for protein-DNA and drug-target interactions');
|
|
208
|
+
console.log('4. Prime resonance captures molecular compatibility');
|
|
209
|
+
console.log('5. Simple model captures key binding principles');
|
package/examples/chat.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Aleph Chat Client
|
|
3
|
+
* Command-line interface to converse with Aleph
|
|
4
|
+
*
|
|
5
|
+
* Updated to use modular architecture.
|
|
6
|
+
*/
|
|
7
|
+
const readline = require('readline');
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const { createEngine, SemanticBackend } = require('../modular');
|
|
11
|
+
|
|
12
|
+
// Configuration
|
|
13
|
+
const semanticConfig = {
|
|
14
|
+
dimension: 16,
|
|
15
|
+
vocabulary: require('../data.json').vocabulary,
|
|
16
|
+
ontology: require('../data.json').ontology || {},
|
|
17
|
+
transforms: require('../data.json').transforms || []
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const engine = createEngine('semantic', semanticConfig);
|
|
21
|
+
|
|
22
|
+
// Watch for changes in data.json
|
|
23
|
+
const DATA_FILE = path.join(__dirname, '../data.json');
|
|
24
|
+
fs.watchFile(DATA_FILE, (curr, prev) => {
|
|
25
|
+
if (curr.mtime !== prev.mtime) {
|
|
26
|
+
console.log('\n[System] data.json changed. Reloading...');
|
|
27
|
+
try {
|
|
28
|
+
delete require.cache[require.resolve('../data.json')];
|
|
29
|
+
const newData = require('../data.json');
|
|
30
|
+
|
|
31
|
+
// Create new backend with updated vocabulary
|
|
32
|
+
const newBackend = new SemanticBackend({
|
|
33
|
+
dimension: 16,
|
|
34
|
+
vocabulary: newData.vocabulary,
|
|
35
|
+
ontology: newData.ontology || {},
|
|
36
|
+
transforms: newData.transforms || []
|
|
37
|
+
});
|
|
38
|
+
engine.setBackend(newBackend);
|
|
39
|
+
|
|
40
|
+
console.log(`[System] Reloaded. Vocabulary size: ${Object.keys(newData.vocabulary).length}`);
|
|
41
|
+
rl.prompt();
|
|
42
|
+
} catch (e) {
|
|
43
|
+
console.error(`[System] Failed to reload: ${e.message}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const rl = readline.createInterface({
|
|
49
|
+
input: process.stdin,
|
|
50
|
+
output: process.stdout,
|
|
51
|
+
prompt: 'Aleph> '
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
console.log('🔮 Aleph Chat v2.0 (Modular Architecture)');
|
|
55
|
+
console.log('Type "exit" to quit, "info" for system stats.');
|
|
56
|
+
console.log('-------------------------------------------');
|
|
57
|
+
|
|
58
|
+
rl.prompt();
|
|
59
|
+
|
|
60
|
+
rl.on('line', async (line) => {
|
|
61
|
+
const input = line.trim();
|
|
62
|
+
|
|
63
|
+
if (!input) {
|
|
64
|
+
rl.prompt();
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (input === 'exit') {
|
|
69
|
+
console.log('Goodbye.');
|
|
70
|
+
process.exit(0);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (input === 'info') {
|
|
74
|
+
const state = engine.getPhysicsState();
|
|
75
|
+
const info = engine.getBackendInfo();
|
|
76
|
+
console.log(`H=${state.entropy.toFixed(3)} C=${state.coherence.toFixed(3)} λ=${state.lyapunov.toFixed(3)}`);
|
|
77
|
+
console.log(`Backend: ${info.name} | Dim: ${info.dimension} | Order: ${state.orderParameter.toFixed(3)}`);
|
|
78
|
+
rl.prompt();
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
try {
|
|
83
|
+
// Process input through engine
|
|
84
|
+
const r = engine.run(input);
|
|
85
|
+
displayResponse(r);
|
|
86
|
+
} catch (e) {
|
|
87
|
+
console.error('Error:', e.message);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
rl.prompt();
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
function displayResponse(r) {
|
|
94
|
+
// Show internal state
|
|
95
|
+
const primes = r.inputPrimes.slice(0, 5).join(',');
|
|
96
|
+
console.log(` [${primes}...]`);
|
|
97
|
+
console.log(` H=${r.entropy.toFixed(2)} C=${r.coherence.toFixed(2)} ${r.stability}`);
|
|
98
|
+
|
|
99
|
+
if (r.fieldBased) {
|
|
100
|
+
console.log(` 🔬 Field-based (${r.evolutionSteps} steps, order=${r.bestFrameOrder.toFixed(2)})`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Show output
|
|
104
|
+
console.log(`\n${r.output}\n`);
|
|
105
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Example 01: Residue Encoding with CRT
|
|
4
|
+
*
|
|
5
|
+
* Demonstrates encoding a hidden vector into K residue distributions
|
|
6
|
+
* over coprime moduli, then reconstructing via Chinese Remainder Theorem.
|
|
7
|
+
*
|
|
8
|
+
* Key concepts:
|
|
9
|
+
* - r_k = softmax(W_k h + b_k) ∈ Δ(ℤ/p_k) for each prime p_k
|
|
10
|
+
* - L̂ = Σ_k E[r_k] * M_k * M_k^{-1} mod P (CRT reconstruction)
|
|
11
|
+
* - Kernel detection: Ker(ℛ) ≈ { r | ε(r) > τ }
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
'use strict';
|
|
15
|
+
|
|
16
|
+
const {
|
|
17
|
+
ResidueEncoder,
|
|
18
|
+
CRTReconstructor,
|
|
19
|
+
DEFAULT_PRIMES_SMALL
|
|
20
|
+
} = require('../../core/crt-homology');
|
|
21
|
+
|
|
22
|
+
console.log('=== CRT Residue Encoding Example ===\n');
|
|
23
|
+
|
|
24
|
+
// Use first 4 primes as moduli: [2, 3, 5, 7]
|
|
25
|
+
// Product P = 210
|
|
26
|
+
const primes = DEFAULT_PRIMES_SMALL;
|
|
27
|
+
const hiddenDim = 16;
|
|
28
|
+
|
|
29
|
+
console.log(`Moduli (primes): ${primes}`);
|
|
30
|
+
console.log(`Product P = ${primes.reduce((a, b) => a * b, 1)}`);
|
|
31
|
+
console.log(`Hidden dimension: ${hiddenDim}\n`);
|
|
32
|
+
|
|
33
|
+
// Create encoder and reconstructor
|
|
34
|
+
const encoder = new ResidueEncoder(primes, hiddenDim, { initScale: 0.1 });
|
|
35
|
+
const crt = new CRTReconstructor(primes);
|
|
36
|
+
|
|
37
|
+
// Create a sample hidden vector
|
|
38
|
+
const h = new Float64Array(hiddenDim);
|
|
39
|
+
for (let i = 0; i < hiddenDim; i++) {
|
|
40
|
+
h[i] = Math.sin(i * 0.5) * 0.5 + 0.5; // Values in [0, 1]
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
console.log('Input hidden vector (first 8 dims):');
|
|
44
|
+
console.log(' h =', Array.from(h.slice(0, 8)).map(x => x.toFixed(3)).join(', '), '...\n');
|
|
45
|
+
|
|
46
|
+
// Encode to residue distributions
|
|
47
|
+
const residues = encoder.encode(h);
|
|
48
|
+
const expectedResidues = encoder.expectedResidues(residues);
|
|
49
|
+
|
|
50
|
+
console.log('Residue distributions:');
|
|
51
|
+
for (let k = 0; k < primes.length; k++) {
|
|
52
|
+
const p = primes[k];
|
|
53
|
+
const r = residues[k];
|
|
54
|
+
console.log(` mod ${p}: [${Array.from(r).map(x => x.toFixed(3)).join(', ')}]`);
|
|
55
|
+
console.log(` E[r_${k}] = ${expectedResidues[k].toFixed(4)}`);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// CRT reconstruction
|
|
59
|
+
const L = crt.reconstruct(expectedResidues);
|
|
60
|
+
const error = crt.reconstructionError(expectedResidues);
|
|
61
|
+
const validation = crt.validate(expectedResidues);
|
|
62
|
+
|
|
63
|
+
console.log('\n=== CRT Reconstruction ===');
|
|
64
|
+
console.log(` Reconstructed L̂ = ${L.toFixed(4)}`);
|
|
65
|
+
console.log(` Reconstruction error ε(r) = ${error.toFixed(6)}`);
|
|
66
|
+
console.log(` In kernel: ${validation.inKernel}`);
|
|
67
|
+
console.log(` Valid (not in kernel): ${validation.valid}`);
|
|
68
|
+
|
|
69
|
+
// Demonstrate kernel detection with inconsistent residues
|
|
70
|
+
console.log('\n=== Kernel Detection ===');
|
|
71
|
+
console.log('Testing with inconsistent residue tuples:\n');
|
|
72
|
+
|
|
73
|
+
const testCases = [
|
|
74
|
+
{ residues: [0.5, 1.2, 2.8, 4.1], label: 'Consistent (low error)' },
|
|
75
|
+
{ residues: [0.99, 0.01, 2.5, 3.99], label: 'Boundary values' },
|
|
76
|
+
{ residues: [0.1, 0.2, 0.3, 0.4], label: 'Small residues' }
|
|
77
|
+
];
|
|
78
|
+
|
|
79
|
+
for (const tc of testCases) {
|
|
80
|
+
const val = crt.validate(tc.residues, 0.1);
|
|
81
|
+
console.log(` ${tc.label}:`);
|
|
82
|
+
console.log(` Residues: [${tc.residues.join(', ')}]`);
|
|
83
|
+
console.log(` L̂ = ${val.reconstructed.toFixed(2)}, ε = ${val.error.toFixed(4)}`);
|
|
84
|
+
console.log(` In kernel: ${val.inKernel}\n`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
console.log('✓ Example complete\n');
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Example 02: Birkhoff Polytope Attention
|
|
4
|
+
*
|
|
5
|
+
* Demonstrates projecting attention matrices onto the Birkhoff polytope
|
|
6
|
+
* using the Sinkhorn-Knopp algorithm.
|
|
7
|
+
*
|
|
8
|
+
* Key concepts:
|
|
9
|
+
* - Birkhoff polytope = set of doubly-stochastic matrices (row sums = col sums = 1)
|
|
10
|
+
* - Sinkhorn-Knopp: alternating row/column normalization until convergence
|
|
11
|
+
* - Physical interpretation: attention as a "transport" operator
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
'use strict';
|
|
15
|
+
|
|
16
|
+
const { BirkhoffProjector } = require('../../core/crt-homology');
|
|
17
|
+
|
|
18
|
+
console.log('=== Birkhoff Polytope Attention Example ===\n');
|
|
19
|
+
|
|
20
|
+
// Create projector with 20 Sinkhorn iterations
|
|
21
|
+
const projector = new BirkhoffProjector(20, 1e-10);
|
|
22
|
+
|
|
23
|
+
// Example 1: Project a random matrix
|
|
24
|
+
console.log('1. Random Matrix Projection:');
|
|
25
|
+
const randomMatrix = [
|
|
26
|
+
[0.8, 0.2, 0.5],
|
|
27
|
+
[0.3, 0.9, 0.1],
|
|
28
|
+
[0.4, 0.6, 0.7]
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
console.log(' Input matrix:');
|
|
32
|
+
for (const row of randomMatrix) {
|
|
33
|
+
console.log(' ', row.map(x => x.toFixed(3)).join(' '));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const projected = projector.project(randomMatrix);
|
|
37
|
+
|
|
38
|
+
console.log('\n Doubly-stochastic projection:');
|
|
39
|
+
for (const row of projected) {
|
|
40
|
+
console.log(' ', row.map(x => x.toFixed(3)).join(' '));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Verify doubly-stochastic property
|
|
44
|
+
const validation = projector.validate(projected, 0.01);
|
|
45
|
+
console.log('\n Validation:');
|
|
46
|
+
console.log(` Is doubly-stochastic: ${validation.isDoublyStochastic}`);
|
|
47
|
+
console.log(` Max row error: ${validation.maxRowError.toFixed(6)}`);
|
|
48
|
+
console.log(` Max col error: ${validation.maxColError.toFixed(6)}`);
|
|
49
|
+
|
|
50
|
+
// Example 2: Attention mechanism
|
|
51
|
+
console.log('\n2. Birkhoff Attention:');
|
|
52
|
+
|
|
53
|
+
// Query, Key, Value matrices (4 tokens, dim=3)
|
|
54
|
+
const Q = [
|
|
55
|
+
[1.0, 0.5, 0.2],
|
|
56
|
+
[0.3, 0.8, 0.4],
|
|
57
|
+
[0.6, 0.1, 0.9],
|
|
58
|
+
[0.2, 0.7, 0.3]
|
|
59
|
+
];
|
|
60
|
+
|
|
61
|
+
const K = [
|
|
62
|
+
[0.9, 0.4, 0.3],
|
|
63
|
+
[0.2, 0.7, 0.5],
|
|
64
|
+
[0.5, 0.3, 0.8],
|
|
65
|
+
[0.4, 0.6, 0.2]
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
const V = [
|
|
69
|
+
[1.0, 0.0, 0.0],
|
|
70
|
+
[0.0, 1.0, 0.0],
|
|
71
|
+
[0.0, 0.0, 1.0],
|
|
72
|
+
[0.5, 0.5, 0.0]
|
|
73
|
+
];
|
|
74
|
+
|
|
75
|
+
console.log(' Queries (Q), Keys (K), Values (V): 4 tokens × 3 dims');
|
|
76
|
+
|
|
77
|
+
const attentionOutput = projector.attention(Q, K, V);
|
|
78
|
+
|
|
79
|
+
console.log('\n Attention output:');
|
|
80
|
+
for (let i = 0; i < attentionOutput.length; i++) {
|
|
81
|
+
console.log(` Token ${i}: [${attentionOutput[i].map(x => x.toFixed(3)).join(', ')}]`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Example 3: Effect of iterations
|
|
85
|
+
console.log('\n3. Effect of Sinkhorn Iterations:');
|
|
86
|
+
|
|
87
|
+
const testMatrix = [
|
|
88
|
+
[2.0, 1.0, 0.5],
|
|
89
|
+
[0.5, 2.0, 1.0],
|
|
90
|
+
[1.0, 0.5, 2.0]
|
|
91
|
+
];
|
|
92
|
+
|
|
93
|
+
for (const iterations of [1, 5, 10, 20]) {
|
|
94
|
+
const proj = new BirkhoffProjector(iterations);
|
|
95
|
+
const result = proj.project(testMatrix);
|
|
96
|
+
const val = proj.validate(result);
|
|
97
|
+
console.log(` ${iterations.toString().padStart(2)} iters: max_error = ${val.maxRowError.toFixed(6)}`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
console.log('\n✓ Example complete\n');
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Example 03: Homology Loss for Consistency Detection
|
|
4
|
+
*
|
|
5
|
+
* Demonstrates detecting "holes" in residue space - consistency failures
|
|
6
|
+
* that persist under perturbation.
|
|
7
|
+
*
|
|
8
|
+
* Key insight: "Holes are not degrees of freedom. Holes are consistency
|
|
9
|
+
* failures that persist under perturbation."
|
|
10
|
+
*
|
|
11
|
+
* Key concepts:
|
|
12
|
+
* - Ker(ℛ) = { r | ε(r) > τ } (kernel = high reconstruction error)
|
|
13
|
+
* - Cycles in kernel represent semantic inconsistencies
|
|
14
|
+
* - Betti numbers: β₀ = components, β₁ = holes (1-cycles)
|
|
15
|
+
* - ℒ_homology = Σ_{cycles} f(cycle) penalizes inconsistency
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
'use strict';
|
|
19
|
+
|
|
20
|
+
const {
|
|
21
|
+
CRTReconstructor,
|
|
22
|
+
HomologyLoss,
|
|
23
|
+
DEFAULT_PRIMES_SMALL
|
|
24
|
+
} = require('../../core/crt-homology');
|
|
25
|
+
|
|
26
|
+
console.log('=== Homology Loss Example ===\n');
|
|
27
|
+
|
|
28
|
+
const primes = DEFAULT_PRIMES_SMALL;
|
|
29
|
+
const crt = new CRTReconstructor(primes);
|
|
30
|
+
const homology = new HomologyLoss({
|
|
31
|
+
tau: 0.1, // Kernel detection threshold
|
|
32
|
+
alpha: 1.0, // Cycle length exponent
|
|
33
|
+
beta: 1.0, // Residue weight
|
|
34
|
+
gamma: 0.5, // Residue exponent
|
|
35
|
+
lambda: 1.0 // Overall loss weight
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
console.log(`Moduli: [${primes.join(', ')}], Product P = ${crt.P}\n`);
|
|
39
|
+
|
|
40
|
+
// Example 1: Consistent residue batch (no holes)
|
|
41
|
+
console.log('1. Consistent Residue Batch:');
|
|
42
|
+
const consistentBatch = [];
|
|
43
|
+
for (let i = 0; i < 10; i++) {
|
|
44
|
+
// Generate residues that are consistent (low error)
|
|
45
|
+
const L = Math.floor(Math.random() * crt.P);
|
|
46
|
+
const residues = primes.map(p => L % p);
|
|
47
|
+
consistentBatch.push(residues);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
console.log(' Generated 10 consistent residue tuples');
|
|
51
|
+
const consistentResult = homology.compute(consistentBatch, crt);
|
|
52
|
+
console.log(` Cycles detected: ${consistentResult.cycles}`);
|
|
53
|
+
console.log(` Homology loss: ${consistentResult.loss.toFixed(6)}`);
|
|
54
|
+
console.log(` Total points in kernel: ${consistentResult.totalPoints}`);
|
|
55
|
+
|
|
56
|
+
const betti1 = homology.computeBettiNumbers(consistentBatch, crt);
|
|
57
|
+
console.log(` Betti numbers: β₀=${betti1.beta0}, β₁=${betti1.beta1}`);
|
|
58
|
+
|
|
59
|
+
// Example 2: Inconsistent residue batch (with holes)
|
|
60
|
+
console.log('\n2. Inconsistent Residue Batch:');
|
|
61
|
+
const inconsistentBatch = [];
|
|
62
|
+
for (let i = 0; i < 10; i++) {
|
|
63
|
+
// Generate residues that may be inconsistent
|
|
64
|
+
// (random values that don't correspond to valid CRT reconstruction)
|
|
65
|
+
const residues = primes.map(p => Math.random() * p);
|
|
66
|
+
inconsistentBatch.push(residues);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
console.log(' Generated 10 random (potentially inconsistent) residue tuples');
|
|
70
|
+
const inconsistentResult = homology.compute(inconsistentBatch, crt);
|
|
71
|
+
console.log(` Cycles detected: ${inconsistentResult.cycles}`);
|
|
72
|
+
console.log(` Homology loss: ${inconsistentResult.loss.toFixed(6)}`);
|
|
73
|
+
console.log(` Total points in kernel: ${inconsistentResult.totalPoints}`);
|
|
74
|
+
|
|
75
|
+
const betti2 = homology.computeBettiNumbers(inconsistentBatch, crt);
|
|
76
|
+
console.log(` Betti numbers: β₀=${betti2.beta0}, β₁=${betti2.beta1}`);
|
|
77
|
+
|
|
78
|
+
// Example 3: Mixed batch
|
|
79
|
+
console.log('\n3. Mixed Batch (alternating consistent/inconsistent):');
|
|
80
|
+
const mixedBatch = [];
|
|
81
|
+
for (let i = 0; i < 10; i++) {
|
|
82
|
+
if (i % 2 === 0) {
|
|
83
|
+
// Consistent
|
|
84
|
+
const L = Math.floor(Math.random() * crt.P);
|
|
85
|
+
mixedBatch.push(primes.map(p => L % p));
|
|
86
|
+
} else {
|
|
87
|
+
// Inconsistent
|
|
88
|
+
mixedBatch.push(primes.map(p => Math.random() * p));
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
console.log(' Generated 10 mixed residue tuples');
|
|
93
|
+
const mixedResult = homology.compute(mixedBatch, crt);
|
|
94
|
+
console.log(` Cycles detected: ${mixedResult.cycles}`);
|
|
95
|
+
console.log(` Homology loss: ${mixedResult.loss.toFixed(6)}`);
|
|
96
|
+
|
|
97
|
+
if (mixedResult.details.length > 0) {
|
|
98
|
+
console.log('\n Cycle details:');
|
|
99
|
+
for (const detail of mixedResult.details) {
|
|
100
|
+
console.log(` Length ${detail.length}: loss=${detail.loss.toFixed(4)}, ` +
|
|
101
|
+
`mean_error=${detail.meanError.toFixed(4)}`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Example 4: Persistence analysis
|
|
106
|
+
console.log('\n4. Cycle Persistence (robustness of holes):');
|
|
107
|
+
|
|
108
|
+
// Create a persistent hole (cluster of inconsistent points)
|
|
109
|
+
const persistentBatch = [];
|
|
110
|
+
for (let i = 0; i < 20; i++) {
|
|
111
|
+
if (i >= 5 && i <= 10) {
|
|
112
|
+
// Create a cluster of high-error points
|
|
113
|
+
persistentBatch.push([0.99, 0.01, 0.5, 0.5]);
|
|
114
|
+
} else {
|
|
115
|
+
const L = Math.floor(Math.random() * crt.P);
|
|
116
|
+
persistentBatch.push(primes.map(p => L % p));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const cycles = homology.detectCycles(persistentBatch, crt);
|
|
121
|
+
console.log(` Batch size: 20, Cluster at indices 5-10`);
|
|
122
|
+
console.log(` Detected ${cycles.length} cycle(s)`);
|
|
123
|
+
|
|
124
|
+
for (const cycle of cycles) {
|
|
125
|
+
const persistence = homology.cyclePersistence(cycle);
|
|
126
|
+
console.log(` Cycle of length ${cycle.length}: persistence=${persistence.toFixed(4)}`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const betti3 = homology.computeBettiNumbers(persistentBatch, crt);
|
|
130
|
+
console.log(` Final Betti numbers: β₀=${betti3.beta0}, β₁=${betti3.beta1}`);
|
|
131
|
+
|
|
132
|
+
console.log('\n✓ Example complete\n');
|