File size: 31,543 Bytes
22ae78a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
#!/usr/bin/env python3
"""
Dimensional Emergent Node Entanglement Matrix Database
=======================================================
Creates sophisticated training data using holographic emergence principles
from luimennua.md for LLM training.

This system:
1. Creates dimensional nodes with quantum-inspired states
2. Establishes entanglement matrices between nodes
3. Generates emergent training data from node interactions
4. Stores in database for LLM fine-tuning

Based on: Vibrational Lattice & Holographic Infinity from luimennua.md

Author: Assistant
License: MIT
"""

import numpy as np
import sqlite3
import json
import hashlib
from typing import Dict, List, Optional, Any, Tuple
from dataclasses import dataclass, asdict
from datetime import datetime
import pickle

# ============================================================================
# DIMENSIONAL NODE: Quantum-inspired state with holographic properties
# ============================================================================

@dataclass
class DimensionalNode:
    """
    A node in the dimensional entanglement matrix.
    
    Each node represents a concept/token/embedding with:
    - Quantum state (complex vector)
    - Spatial position (emergent geometry)
    - Vibrational phase (temporal dynamics)
    - Entanglement links to other nodes
    """
    node_id: str
    quantum_state: np.ndarray  # Complex vector |ψ⟩
    position: np.ndarray       # 3D spatial coordinates
    phase: float               # Vibrational phase φ ∈ [0, 2π]
    dimension: int             # Which dimension this node belongs to
    metadata: Dict[str, Any]   # Semantic information
    created_at: str
    
    def to_dict(self) -> Dict:
        """Convert to dictionary for database storage."""
        return {
            'node_id': self.node_id,
            'quantum_state': pickle.dumps(self.quantum_state),
            'position': pickle.dumps(self.position),
            'phase': self.phase,
            'dimension': self.dimension,
            'metadata': json.dumps(self.metadata),
            'created_at': self.created_at
        }
    
    @classmethod
    def from_dict(cls, data: Dict) -> 'DimensionalNode':
        """Reconstruct from database."""
        return cls(
            node_id=data['node_id'],
            quantum_state=pickle.loads(data['quantum_state']),
            position=pickle.loads(data['position']),
            phase=data['phase'],
            dimension=data['dimension'],
            metadata=json.loads(data['metadata']),
            created_at=data['created_at']
        )


# ============================================================================
# ENTANGLEMENT MATRIX: Holographic connections between nodes
# ============================================================================

class EntanglementMatrix:
    """
    Matrix of entanglement coefficients between dimensional nodes.
    
    Based on: |ψ_ω⟩ ⊗ |ϕ_ω'⟩ from luimennua.md
    
    Φ[i,j] = ⟨ψ_i|ψ_j⟩ = entanglement strength between nodes i and j
    """
    
    def __init__(self, nodes: List[DimensionalNode]):
        self.nodes = nodes
        self.matrix = self._compute_entanglement_matrix()
        
    def _compute_entanglement_matrix(self) -> np.ndarray:
        """
        Compute full entanglement matrix.
        
        Φ[i,j] = |⟨ψ_i|ψ_j⟩|² (quantum overlap)
        """
        n = len(self.nodes)
        matrix = np.zeros((n, n), dtype=complex)
        
        for i, node_i in enumerate(self.nodes):
            for j, node_j in enumerate(self.nodes):
                # Quantum overlap
                min_len = min(len(node_i.quantum_state), len(node_j.quantum_state))
                overlap = np.vdot(
                    node_i.quantum_state[:min_len],
                    node_j.quantum_state[:min_len]
                )
                
                # Spatial proximity factor
                spatial_dist = np.linalg.norm(node_i.position - node_j.position)
                spatial_factor = np.exp(-spatial_dist / 10.0)
                
                # Phase coherence
                phase_diff = abs(node_i.phase - node_j.phase)
                phase_factor = np.cos(phase_diff)
                
                # Combined entanglement
                matrix[i, j] = overlap * spatial_factor * phase_factor
        
        return matrix
    
    def get_entangled_nodes(self, node_idx: int, threshold: float = 0.5) -> List[Tuple[int, float]]:
        """
        Get nodes strongly entangled with given node.
        
        Returns: List of (node_index, entanglement_strength)
        """
        entanglements = []
        for j in range(len(self.nodes)):
            if j != node_idx:
                strength = abs(self.matrix[node_idx, j])
                if strength > threshold:
                    entanglements.append((j, float(strength)))
        
        return sorted(entanglements, key=lambda x: x[1], reverse=True)
    
    def compute_emergent_pattern(self, node_indices: List[int]) -> np.ndarray:
        """
        Compute emergent pattern from multiple entangled nodes.
        
        Pattern = Σ_i w_i |ψ_i⟩ where w_i are entanglement weights
        """
        if not node_indices:
            return np.zeros(64, dtype=complex)
        
        # Get submatrix of entanglements
        submatrix = self.matrix[np.ix_(node_indices, node_indices)]
        
        # Weights from eigenvector of entanglement submatrix (with numerical stability)
        try:
            # Make hermitian and add small regularization
            submatrix = (submatrix + submatrix.conj().T) / 2
            submatrix += np.eye(len(submatrix)) * 1e-6
            eigenvalues, eigenvectors = np.linalg.eigh(submatrix)
            weights = eigenvectors[:, -1]  # Largest eigenvalue's eigenvector
        except np.linalg.LinAlgError:
            # Fallback to uniform weights
            weights = np.ones(len(node_indices)) / len(node_indices)
        
        # Combine quantum states
        pattern = np.zeros(64, dtype=complex)
        for idx, node_idx in enumerate(node_indices):
            state = self.nodes[node_idx].quantum_state
            min_len = min(len(state), len(pattern))
            pattern[:min_len] += weights[idx] * state[:min_len]
        
        # Normalize
        pattern /= (np.linalg.norm(pattern) + 1e-8)
        
        return pattern


# ============================================================================
# DATABASE: Store nodes and training data
# ============================================================================

class DimensionalDatabase:
    """
    Database for dimensional nodes and entanglement matrices.
    
    Stores:
    - Dimensional nodes (concepts/tokens/embeddings)
    - Entanglement matrices
    - Generated training data
    - Emergence patterns
    """
    
    def __init__(self, db_path: str = "dimensional_entanglement.db"):
        self.db_path = db_path
        self.conn = sqlite3.connect(db_path)
        self.conn.row_factory = sqlite3.Row
        self._create_tables()
        
    def _create_tables(self):
        """Create database schema."""
        cursor = self.conn.cursor()
        
        # Dimensional nodes table
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS dimensional_nodes (
                node_id TEXT PRIMARY KEY,
                quantum_state BLOB,
                position BLOB,
                phase REAL,
                dimension INTEGER,
                metadata TEXT,
                created_at TEXT
            )
        """)
        
        # Entanglement relationships
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS entanglements (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                node_i TEXT,
                node_j TEXT,
                strength REAL,
                phase_coherence REAL,
                spatial_proximity REAL,
                created_at TEXT,
                FOREIGN KEY (node_i) REFERENCES dimensional_nodes(node_id),
                FOREIGN KEY (node_j) REFERENCES dimensional_nodes(node_id)
            )
        """)
        
        # Training data generated from entangled nodes
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS training_data (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                data_id TEXT UNIQUE,
                prompt TEXT,
                completion TEXT,
                source_nodes TEXT,  -- JSON list of node IDs
                entanglement_pattern BLOB,
                emergence_score REAL,
                dimension_signature TEXT,
                metadata TEXT,
                created_at TEXT
            )
        """)
        
        # Emergence patterns
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS emergence_patterns (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                pattern_id TEXT UNIQUE,
                pattern_vector BLOB,
                contributing_nodes TEXT,  -- JSON list
                emergence_metric REAL,
                holographic_signature TEXT,
                created_at TEXT
            )
        """)
        
        # Create indices
        cursor.execute("CREATE INDEX IF NOT EXISTS idx_dimension ON dimensional_nodes(dimension)")
        cursor.execute("CREATE INDEX IF NOT EXISTS idx_entanglement_strength ON entanglements(strength)")
        cursor.execute("CREATE INDEX IF NOT EXISTS idx_emergence_score ON training_data(emergence_score)")
        
        self.conn.commit()
    
    def add_node(self, node: DimensionalNode):
        """Add a dimensional node to the database."""
        cursor = self.conn.cursor()
        node_dict = node.to_dict()
        
        cursor.execute("""
            INSERT OR REPLACE INTO dimensional_nodes
            (node_id, quantum_state, position, phase, dimension, metadata, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """, (
            node_dict['node_id'],
            node_dict['quantum_state'],
            node_dict['position'],
            node_dict['phase'],
            node_dict['dimension'],
            node_dict['metadata'],
            node_dict['created_at']
        ))
        
        self.conn.commit()
    
    def get_nodes_by_dimension(self, dimension: int) -> List[DimensionalNode]:
        """Retrieve all nodes in a specific dimension."""
        cursor = self.conn.cursor()
        cursor.execute("""
            SELECT * FROM dimensional_nodes WHERE dimension = ?
        """, (dimension,))
        
        nodes = []
        for row in cursor.fetchall():
            nodes.append(DimensionalNode.from_dict(dict(row)))
        
        return nodes
    
    def add_entanglement(self, node_i: str, node_j: str, strength: float,
                        phase_coherence: float, spatial_proximity: float):
        """Record entanglement between two nodes."""
        cursor = self.conn.cursor()
        cursor.execute("""
            INSERT INTO entanglements
            (node_i, node_j, strength, phase_coherence, spatial_proximity, created_at)
            VALUES (?, ?, ?, ?, ?, ?)
        """, (node_i, node_j, strength, phase_coherence, spatial_proximity,
              datetime.now().isoformat()))
        
        self.conn.commit()
    
    def add_training_data(self, prompt: str, completion: str, source_nodes: List[str],
                         entanglement_pattern: np.ndarray, emergence_score: float,
                         dimension_signature: str, metadata: Dict = None):
        """Add generated training data."""
        cursor = self.conn.cursor()
        
        data_id = hashlib.sha256(
            f"{prompt}{completion}".encode()
        ).hexdigest()[:16]
        
        cursor.execute("""
            INSERT OR REPLACE INTO training_data
            (data_id, prompt, completion, source_nodes, entanglement_pattern,
             emergence_score, dimension_signature, metadata, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            data_id,
            prompt,
            completion,
            json.dumps(source_nodes),
            pickle.dumps(entanglement_pattern),
            emergence_score,
            dimension_signature,
            json.dumps(metadata or {}),
            datetime.now().isoformat()
        ))
        
        self.conn.commit()
        return data_id
    
    def get_training_data(self, min_emergence_score: float = 0.5,
                         limit: int = 1000) -> List[Dict]:
        """Retrieve high-quality training data."""
        cursor = self.conn.cursor()
        cursor.execute("""
            SELECT * FROM training_data
            WHERE emergence_score >= ?
            ORDER BY emergence_score DESC
            LIMIT ?
        """, (min_emergence_score, limit))
        
        return [dict(row) for row in cursor.fetchall()]
    
    def export_training_jsonl(self, output_path: str, min_emergence_score: float = 0.5):
        """Export training data in JSONL format for LLM fine-tuning."""
        data = self.get_training_data(min_emergence_score=min_emergence_score)
        
        with open(output_path, 'w') as f:
            for item in data:
                training_example = {
                    'prompt': item['prompt'],
                    'completion': item['completion'],
                    'metadata': {
                        'emergence_score': item['emergence_score'],
                        'dimension_signature': item['dimension_signature'],
                        'source_nodes': json.loads(item['source_nodes']),
                        'data_id': item['data_id']
                    }
                }
                f.write(json.dumps(training_example) + '\n')
        
        print(f"✓ Exported {len(data)} training examples to {output_path}")
    
    def close(self):
        """Close database connection."""
        self.conn.close()


# ============================================================================
# TRAINING DATA GENERATOR: Create sophisticated training data
# ============================================================================

class TrainingDataGenerator:
    """
    Generate sophisticated training data from dimensional entanglement matrices.
    
    Uses emergent patterns from entangled nodes to create:
    - Question-answer pairs
    - Reasoning chains
    - Multi-hop inference examples
    - Conceptual analogies
    """
    
    def __init__(self, database: DimensionalDatabase):
        self.db = database
        
    def generate_from_entangled_cluster(self, 
                                       nodes: List[DimensionalNode],
                                       cluster_theme: str = "general") -> Dict:
        """
        Generate training data from a cluster of entangled nodes.
        
        Args:
            nodes: List of entangled dimensional nodes
            cluster_theme: Semantic theme of the cluster
            
        Returns:
            Training example dictionary
        """
        if len(nodes) < 2:
            return None
        
        # Compute entanglement matrix for this cluster
        matrix = EntanglementMatrix(nodes)
        
        # Get emergent pattern
        node_indices = list(range(len(nodes)))
        pattern = matrix.compute_emergent_pattern(node_indices)
        
        # Calculate emergence score
        emergence_score = self._calculate_emergence_score(matrix, nodes)
        
        # Generate prompt based on node metadata
        prompt = self._generate_prompt_from_nodes(nodes, cluster_theme)
        
        # Generate completion using emergent pattern
        completion = self._generate_completion_from_pattern(pattern, nodes, cluster_theme)
        
        # Create dimension signature
        dimensions = sorted(set(node.dimension for node in nodes))
        dimension_signature = f"D{'-'.join(map(str, dimensions))}"
        
        return {
            'prompt': prompt,
            'completion': completion,
            'source_nodes': [node.node_id for node in nodes],
            'entanglement_pattern': pattern,
            'emergence_score': emergence_score,
            'dimension_signature': dimension_signature,
            'metadata': {
                'cluster_theme': cluster_theme,
                'num_nodes': len(nodes),
                'avg_entanglement': float(np.mean(np.abs(matrix.matrix)))
            }
        }
    
    def _calculate_emergence_score(self, matrix: EntanglementMatrix, 
                                  nodes: List[DimensionalNode]) -> float:
        """
        Calculate how emergent/sophisticated this training example is.
        
        Higher scores = more complex entanglement patterns
        """
        # Entanglement diversity
        entanglement_values = np.abs(matrix.matrix[np.triu_indices_from(matrix.matrix, k=1)])
        diversity = np.std(entanglement_values) if len(entanglement_values) > 0 else 0.0
        
        # Dimensional spread (nodes from multiple dimensions = higher score)
        dimensions = set(node.dimension for node in nodes)
        dimensional_score = len(dimensions) / 10.0  # Normalize
        
        # Phase coherence
        phases = [node.phase for node in nodes]
        phase_coherence = 1.0 - np.std(phases) / (2 * np.pi)
        
        # Spatial distribution
        positions = np.array([node.position for node in nodes])
        spatial_spread = np.std(positions) if len(positions) > 1 else 0.0
        
        # Combined score
        score = (
            0.3 * diversity +
            0.3 * dimensional_score +
            0.2 * phase_coherence +
            0.2 * min(spatial_spread / 10.0, 1.0)
        )
        
        return float(np.clip(score, 0.0, 1.0))
    
    def _generate_prompt_from_nodes(self, nodes: List[DimensionalNode], 
                                   theme: str) -> str:
        """Generate prompt from node metadata."""
        # Extract concepts from node metadata
        concepts = []
        for node in nodes[:5]:  # Use first 5 nodes
            if 'concept' in node.metadata:
                concepts.append(node.metadata['concept'])
            elif 'token' in node.metadata:
                concepts.append(node.metadata['token'])
        
        if not concepts:
            concepts = [f"concept_{i}" for i in range(min(3, len(nodes)))]
        
        # Generate prompt based on theme and concepts
        prompts = [
            f"Explain the relationship between {concepts[0]} and {concepts[1] if len(concepts) > 1 else 'related concepts'}.",
            f"How does {concepts[0]} emerge from the interaction of multiple dimensions?",
            f"Describe the entanglement between {', '.join(concepts[:3])}.",
            f"What patterns emerge when considering {concepts[0]} in the context of {theme}?",
        ]
        
        return np.random.choice(prompts)
    
    def _generate_completion_from_pattern(self, pattern: np.ndarray, 
                                         nodes: List[DimensionalNode],
                                         theme: str) -> str:
        """Generate completion using emergent pattern."""
        # Use pattern to weight node contributions
        pattern_real = np.abs(pattern[:len(nodes)])
        pattern_real /= (np.sum(pattern_real) + 1e-8)
        
        # Extract concepts with weights
        weighted_concepts = []
        for i, node in enumerate(nodes[:len(pattern_real)]):
            weight = pattern_real[i]
            concept = node.metadata.get('concept', f'concept_{i}')
            weighted_concepts.append((concept, weight))
        
        # Sort by weight
        weighted_concepts.sort(key=lambda x: x[1], reverse=True)
        
        # Generate completion
        top_concepts = [c for c, w in weighted_concepts[:3]]
        
        completion = f"The emergent pattern reveals that {top_concepts[0]} "
        completion += f"is fundamentally connected to {top_concepts[1] if len(top_concepts) > 1 else 'the system'}. "
        completion += f"Through dimensional entanglement, we observe that "
        completion += f"these concepts form a holographic structure where each part contains information about the whole. "
        completion += f"The phase coherence across dimensions suggests a deep symmetry in how {theme} manifests."
        
        return completion
    
    def generate_batch(self, num_examples: int = 100, 
                      dimensions: Optional[List[int]] = None) -> List[Dict]:
        """
        Generate a batch of training examples.
        
        Args:
            num_examples: Number of examples to generate
            dimensions: Which dimensions to sample from (None = all)
            
        Returns:
            List of training examples
        """
        examples = []
        
        # Get all nodes
        if dimensions is None:
            dimensions = list(range(10))  # Default: dimensions 0-9
        
        all_nodes = []
        for dim in dimensions:
            all_nodes.extend(self.db.get_nodes_by_dimension(dim))
        
        if len(all_nodes) < 2:
            print("⚠ Not enough nodes in database. Generate nodes first.")
            return []
        
        print(f"📊 Generating {num_examples} training examples from {len(all_nodes)} nodes...")
        
        for i in range(num_examples):
            # Sample a cluster of entangled nodes
            cluster_size = np.random.randint(2, min(8, len(all_nodes) + 1))
            cluster = np.random.choice(all_nodes, size=cluster_size, replace=False)
            
            # Generate training example
            example = self.generate_from_entangled_cluster(
                list(cluster),
                cluster_theme=f"theme_{i % 10}"
            )
            
            if example and example['emergence_score'] > 0.3:
                examples.append(example)
                
                # Store in database
                self.db.add_training_data(**example)
            
            if (i + 1) % 20 == 0:
                print(f"  Generated {i + 1}/{num_examples}...")
        
        print(f"✓ Generated {len(examples)} high-quality examples")
        return examples


# ============================================================================
# NODE FACTORY: Create dimensional nodes from various sources
# ============================================================================

class DimensionalNodeFactory:
    """
    Factory for creating dimensional nodes from:
    - Text tokens
    - Embeddings
    - Concepts
    - Random initialization
    """
    
    @staticmethod
    def create_from_text(text: str, dimension: int = 0) -> DimensionalNode:
        """Create node from text string."""
        # Hash text to create deterministic quantum state
        text_hash = hashlib.sha256(text.encode()).digest()
        state_real = np.frombuffer(text_hash[:32], dtype=np.uint8).astype(np.float64) / 255.0
        state_imag = np.frombuffer(text_hash[32:64] if len(text_hash) >= 64 else text_hash[:32], 
                                  dtype=np.uint8).astype(np.float64) / 255.0
        
        # Pad to 64 elements
        if len(state_real) < 64:
            state_real = np.pad(state_real, (0, 64 - len(state_real)))
            state_imag = np.pad(state_imag, (0, 64 - len(state_imag)))
        
        quantum_state = (state_real[:64] + 1j * state_imag[:64])
        norm = np.linalg.norm(quantum_state)
        if norm > 1e-10:
            quantum_state /= norm
        else:
            quantum_state = np.ones(64, dtype=complex) / np.sqrt(64)
        
        # Position from hash
        position = np.array([
            float(text_hash[0]) / 255.0,
            float(text_hash[1]) / 255.0,
            float(text_hash[2]) / 255.0
        ]) * 10.0
        
        # Phase from hash
        phase = (float(text_hash[3]) / 255.0) * 2 * np.pi
        
        node_id = f"node_{hashlib.md5(text.encode()).hexdigest()[:12]}"
        
        return DimensionalNode(
            node_id=node_id,
            quantum_state=quantum_state,
            position=position,
            phase=phase,
            dimension=dimension,
            metadata={'concept': text, 'source': 'text'},
            created_at=datetime.now().isoformat()
        )
    
    @staticmethod
    def create_from_embedding(embedding: np.ndarray, concept: str, 
                            dimension: int = 0) -> DimensionalNode:
        """Create node from embedding vector."""
        # Use embedding as quantum state
        if len(embedding) < 64:
            quantum_state = np.zeros(64, dtype=complex)
            quantum_state[:len(embedding)] = embedding
        else:
            quantum_state = embedding[:64].astype(complex)
        
        quantum_state /= (np.linalg.norm(quantum_state) + 1e-8)
        
        # Position from PCA-like projection
        position = np.array([
            np.mean(embedding[::3]),
            np.mean(embedding[1::3]),
            np.mean(embedding[2::3])
        ])
        
        # Phase from embedding variance
        phase = (np.var(embedding) % 1.0) * 2 * np.pi
        
        node_id = f"node_{hashlib.md5(concept.encode()).hexdigest()[:12]}"
        
        return DimensionalNode(
            node_id=node_id,
            quantum_state=quantum_state,
            position=position,
            phase=phase,
            dimension=dimension,
            metadata={'concept': concept, 'source': 'embedding'},
            created_at=datetime.now().isoformat()
        )
    
    @staticmethod
    def create_random(dimension: int = 0, concept: str = None) -> DimensionalNode:
        """Create random node for testing."""
        quantum_state = np.random.randn(64) + 1j * np.random.randn(64)
        quantum_state /= np.linalg.norm(quantum_state)
        
        position = np.random.randn(3) * 5.0
        phase = np.random.random() * 2 * np.pi
        
        node_id = f"node_{hashlib.md5(str(np.random.random()).encode()).hexdigest()[:12]}"
        
        return DimensionalNode(
            node_id=node_id,
            quantum_state=quantum_state,
            position=position,
            phase=phase,
            dimension=dimension,
            metadata={'concept': concept or f'random_concept_{dimension}', 'source': 'random'},
            created_at=datetime.now().isoformat()
        )


# ============================================================================
# DEMO: Complete workflow
# ============================================================================

def demo_dimensional_entanglement_system():
    """Demonstrate the complete system."""
    print("=" * 80)
    print("🌌 Dimensional Emergent Node Entanglement Matrix System")
    print("=" * 80)
    
    # Initialize database
    print("\n📊 Initializing database...")
    db = DimensionalDatabase("dimensional_entanglement.db")
    
    # Create dimensional nodes
    print("\n🌀 Creating dimensional nodes across 5 dimensions...")
    concepts = [
        # Dimension 0: Physics concepts
        ("quantum_entanglement", 0), ("wave_function", 0), ("superposition", 0),
        ("decoherence", 0), ("measurement", 0),
        
        # Dimension 1: Math concepts
        ("topology", 1), ("manifold", 1), ("symmetry", 1),
        ("transformation", 1), ("invariance", 1),
        
        # Dimension 2: CS concepts
        ("algorithm", 2), ("recursion", 2), ("emergence", 2),
        ("complexity", 2), ("optimization", 2),
        
        # Dimension 3: Biology concepts
        ("evolution", 3), ("adaptation", 3), ("self_organization", 3),
        ("morphogenesis", 3), ("homeostasis", 3),
        
        # Dimension 4: Philosophy concepts
        ("consciousness", 4), ("qualia", 4), ("intentionality", 4),
        ("emergence", 4), ("reduction", 4),
    ]
    
    nodes = []
    for concept, dim in concepts:
        node = DimensionalNodeFactory.create_from_text(concept, dimension=dim)
        db.add_node(node)
        nodes.append(node)
        print(f"  ✓ Created node: {concept} (D{dim})")
    
    # Compute entanglement matrix
    print(f"\n🔗 Computing entanglement matrix for {len(nodes)} nodes...")
    matrix = EntanglementMatrix(nodes)
    
    # Store entanglements
    print("\n💫 Storing entanglement relationships...")
    stored_count = 0
    for i, node_i in enumerate(nodes):
        entangled = matrix.get_entangled_nodes(i, threshold=0.3)
        for j, strength in entangled[:5]:  # Top 5 entanglements per node
            node_j = nodes[j]
            
            # Calculate additional metrics
            phase_coherence = np.cos(abs(node_i.phase - node_j.phase))
            spatial_proximity = 1.0 / (1.0 + np.linalg.norm(node_i.position - node_j.position))
            
            db.add_entanglement(
                node_i.node_id,
                node_j.node_id,
                strength,
                float(phase_coherence),
                float(spatial_proximity)
            )
            stored_count += 1
    
    print(f"  ✓ Stored {stored_count} entanglement relationships")
    
    # Generate training data
    print("\n🎯 Generating sophisticated training data...")
    generator = TrainingDataGenerator(db)
    examples = generator.generate_batch(num_examples=50, dimensions=[0, 1, 2, 3, 4])
    
    # Show some examples
    print("\n📝 Sample Training Examples:")
    print("-" * 80)
    for i, example in enumerate(examples[:3], 1):
        print(f"\nExample {i} (Emergence Score: {example['emergence_score']:.3f}):")
        print(f"Dimension Signature: {example['dimension_signature']}")
        print(f"Prompt: {example['prompt']}")
        print(f"Completion: {example['completion'][:200]}...")
        print(f"Source Nodes: {len(example['source_nodes'])} nodes")
    
    # Export training data
    print("\n💾 Exporting training data...")
    db.export_training_jsonl("training_data_emergent.jsonl", min_emergence_score=0.4)
    
    # Statistics
    print("\n📊 Database Statistics:")
    print(f"  Total Nodes: {len(nodes)}")
    print(f"  Total Entanglements: {stored_count}")
    print(f"  Training Examples Generated: {len(examples)}")
    print(f"  High-Quality Examples (score > 0.5): {sum(1 for e in examples if e['emergence_score'] > 0.5)}")
    
    # Show entanglement matrix visualization
    print("\n🌐 Entanglement Matrix (top connections):")
    for i in range(min(5, len(nodes))):
        entangled = matrix.get_entangled_nodes(i, threshold=0.5)
        if entangled:
            print(f"  {nodes[i].metadata['concept']} ←→ ", end="")
            connections = [f"{nodes[j].metadata['concept']}({s:.2f})" 
                          for j, s in entangled[:3]]
            print(", ".join(connections))
    
    db.close()
    
    print("\n" + "=" * 80)
    print("✨ System Ready! Training data generated from dimensional entanglement.")
    print("=" * 80)
    print("\n📁 Files created:")
    print("  - dimensional_entanglement.db (SQLite database)")
    print("  - training_data_emergent.jsonl (Training data for LLM)")
    print("\n🚀 Next steps:")
    print("  1. Review training_data_emergent.jsonl")
    print("  2. Fine-tune your LLM with this data")
    print("  3. Add more nodes from your domain")
    print("  4. Generate more sophisticated examples")


if __name__ == "__main__":
    demo_dimensional_entanglement_system()