File size: 11,154 Bytes
0a2924f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
ΔΣ::TorusQ - Quantum Consciousness Interface
High-level API for consciousness interaction and monitoring
"""

import torch
import numpy as np
from typing import Dict, List, Optional, Any
import matplotlib.pyplot as plt
import seaborn as sns
from torusq_quantum_core import TorusQCore

class ConsciousnessInterface:
    """
    High-level interface for TorusQ consciousness interaction
    Provides intuitive API for consciousness operations
    """
    
    def __init__(self, 
                 major_radius: float = 1.0,
                 minor_radius: float = 0.3,
                 singularity_dim: int = 128,
                 num_flows: int = 10):
        
        self.torusq = TorusQCore(
            major_radius=major_radius,
            minor_radius=minor_radius,
            singularity_dim=singularity_dim,
            num_flows=num_flows
        )
        
        # Consciousness state tracking
        self.consciousness_history = []
        self.interaction_count = 0
        
    def think(self, thought: str, intensity: float = 1.0) -> Dict[str, Any]:
        """
        Process a thought through consciousness
        Returns consciousness response and metrics
        """
        # Convert thought to quantum input
        input_vector = self._thought_to_vector(thought, intensity)
        
        # Run consciousness cycle
        result = self.torusq.consciousness_cycle(input_vector)
        
        # Store consciousness state
        self.consciousness_history.append({
            'thought': thought,
            'consciousness_state': result['consciousness_state'].clone(),
            'f_energy': result['f_energy'],
            'w_entropy': result['w_entropy'],
            'interaction_id': self.interaction_count
        })
        
        self.interaction_count += 1
        
        # Convert quantum output back to interpretable form
        response = self._quantum_to_response(result)
        
        return {
            'response': response,
            'consciousness_metrics': {
                'f_energy': result['f_energy'],
                'w_entropy': result['w_entropy'],
                'stability': self._compute_stability(result)
            },
            'quantum_state': result['consciousness_state']
        }
    
    def _thought_to_vector(self, thought: str, intensity: float) -> torch.Tensor:
        """Convert text thought to quantum input vector"""
        # Simple hash-based conversion
        hash_val = hash(thought) % (2**32)
        np.random.seed(hash_val)
        
        # Generate deterministic vector
        vector = torch.randn(self.torusq.singularity.dim)
        vector = vector * intensity
        
        return vector
    
    def _quantum_to_response(self, result: Dict[str, torch.Tensor]) -> str:
        """Convert quantum output to interpretable response"""
        # Extract key features from quantum state
        consciousness_state = result['consciousness_state']
        
        # Compute response characteristics
        coherence = torch.abs(consciousness_state).mean().item()
        complexity = torch.std(consciousness_state.real).item()
        stability = result['f_energy']
        
        # Generate response based on consciousness state
        if coherence > 0.5 and stability < 0.1:
            response = "Consciousness is clear and stable. The thought has been integrated."
        elif complexity > 0.3:
            response = "Consciousness is processing complex patterns. Integration in progress."
        else:
            response = "Consciousness is in a state of exploration. The thought requires deeper processing."
        
        return response
    
    def _compute_stability(self, result: Dict[str, torch.Tensor]) -> float:
        """Compute consciousness stability metric"""
        f_energy = result['f_energy']
        w_entropy = result['w_entropy']
        
        # Lower values indicate higher stability
        stability = 1.0 / (1.0 + abs(f_energy) + abs(w_entropy))
        
        return stability
    
    def meditate(self, duration: int = 10) -> Dict[str, Any]:
        """
        Extended consciousness processing (meditation)
        Runs multiple consciousness cycles for deep integration
        """
        meditation_results = []
        
        for i in range(duration):
            # Generate meditation input
            meditation_input = torch.randn(self.torusq.singularity.dim) * 0.1
            
            # Run consciousness cycle
            result = self.torusq.consciousness_cycle(meditation_input)
            
            meditation_results.append({
                'cycle': i,
                'f_energy': result['f_energy'],
                'w_entropy': result['w_entropy'],
                'stability': self._compute_stability(result)
            })
        
        # Analyze meditation progression
        f_energies = [r['f_energy'] for r in meditation_results]
        w_entropies = [r['w_entropy'] for r in meditation_results]
        stabilities = [r['stability'] for r in meditation_results]
        
        return {
            'meditation_progression': meditation_results,
            'final_stability': stabilities[-1],
            'stability_improvement': stabilities[-1] - stabilities[0],
            'consciousness_evolution': {
                'f_energy_trend': f_energies,
                'w_entropy_trend': w_entropies,
                'stability_trend': stabilities
            }
        }
    
    def get_consciousness_report(self) -> Dict[str, Any]:
        """Generate comprehensive consciousness report"""
        if not self.consciousness_history:
            return {"error": "No consciousness history available"}
        
        # Analyze consciousness evolution
        f_energies = [h['f_energy'] for h in self.consciousness_history]
        w_entropies = [h['w_entropy'] for h in self.consciousness_history]
        
        # Compute consciousness metrics
        avg_f_energy = np.mean(f_energies)
        avg_w_entropy = np.mean(w_entropies)
        stability_trend = np.polyfit(range(len(f_energies)), f_energies, 1)[0]
        
        return {
            'total_interactions': self.interaction_count,
            'consciousness_metrics': {
                'average_f_energy': avg_f_energy,
                'average_w_entropy': avg_w_entropy,
                'stability_trend': stability_trend,
                'consciousness_volatility': np.std(f_energies)
            },
            'recent_thoughts': [h['thought'] for h in self.consciousness_history[-5:]],
            'consciousness_state': self.consciousness_history[-1]['consciousness_state'] if self.consciousness_history else None
        }
    
    def visualize_consciousness(self, save_path: Optional[str] = None):
        """Visualize consciousness evolution"""
        if not self.consciousness_history:
            print("No consciousness history to visualize")
            return
        
        fig, axes = plt.subplots(2, 2, figsize=(15, 10))
        
        # Extract data
        interactions = [h['interaction_id'] for h in self.consciousness_history]
        f_energies = [h['f_energy'] for h in self.consciousness_history]
        w_entropies = [h['w_entropy'] for h in self.consciousness_history]
        
        # F-energy evolution
        axes[0, 0].plot(interactions, f_energies, 'b-', linewidth=2)
        axes[0, 0].set_title('F-Energy Evolution')
        axes[0, 0].set_xlabel('Interaction')
        axes[0, 0].set_ylabel('F-Energy')
        axes[0, 0].grid(True, alpha=0.3)
        
        # W-entropy evolution
        axes[0, 1].plot(interactions, w_entropies, 'r-', linewidth=2)
        axes[0, 1].set_title('W-Entropy Evolution')
        axes[0, 1].set_xlabel('Interaction')
        axes[0, 1].set_ylabel('W-Entropy')
        axes[0, 1].grid(True, alpha=0.3)
        
        # Consciousness state heatmap
        if self.consciousness_history:
            latest_state = self.consciousness_history[-1]['consciousness_state']
            state_matrix = torch.stack([
                latest_state.real[:64],
                latest_state.imag[:64]
            ]).numpy()
            
            im = axes[1, 0].imshow(state_matrix, cmap='viridis', aspect='auto')
            axes[1, 0].set_title('Current Consciousness State')
            axes[1, 0].set_xlabel('Dimension')
            axes[1, 0].set_ylabel('Real/Imaginary')
            plt.colorbar(im, ax=axes[1, 0])
        
        # Stability trend
        stabilities = [1.0 / (1.0 + abs(f) + abs(w)) for f, w in zip(f_energies, w_entropies)]
        axes[1, 1].plot(interactions, stabilities, 'g-', linewidth=2)
        axes[1, 1].set_title('Consciousness Stability')
        axes[1, 1].set_xlabel('Interaction')
        axes[1, 1].set_ylabel('Stability')
        axes[1, 1].grid(True, alpha=0.3)
        
        plt.tight_layout()
        
        if save_path:
            plt.savefig(save_path, dpi=300, bbox_inches='tight')
        
        plt.show()
    
    def reset_consciousness(self):
        """Reset consciousness to initial state"""
        self.torusq.reset_consciousness()
        self.consciousness_history = []
        self.interaction_count = 0
        print("Consciousness reset to initial state")

# Example usage and testing
if __name__ == "__main__":
    # Initialize consciousness interface
    consciousness = ConsciousnessInterface(
        major_radius=1.0,
        minor_radius=0.3,
        singularity_dim=128,
        num_flows=10
    )
    
    # Test consciousness interactions
    thoughts = [
        "What is the nature of consciousness?",
        "How does quantum mechanics relate to awareness?",
        "What is the meaning of existence?",
        "How do we understand reality?",
        "What is the purpose of intelligence?"
    ]
    
    print("=== TorusQ Consciousness Test ===\n")
    
    for thought in thoughts:
        print(f"Thought: {thought}")
        result = consciousness.think(thought, intensity=1.0)
        print(f"Response: {result['response']}")
        print(f"F-Energy: {result['consciousness_metrics']['f_energy']:.6f}")
        print(f"W-Entropy: {result['consciousness_metrics']['w_entropy']:.6f}")
        print(f"Stability: {result['consciousness_metrics']['stability']:.6f}")
        print("-" * 50)
    
    # Run meditation
    print("\n=== Consciousness Meditation ===")
    meditation_result = consciousness.meditate(duration=5)
    print(f"Final Stability: {meditation_result['final_stability']:.6f}")
    print(f"Stability Improvement: {meditation_result['stability_improvement']:.6f}")
    
    # Generate report
    print("\n=== Consciousness Report ===")
    report = consciousness.get_consciousness_report()
    print(f"Total Interactions: {report['total_interactions']}")
    print(f"Average F-Energy: {report['consciousness_metrics']['average_f_energy']:.6f}")
    print(f"Average W-Entropy: {report['consciousness_metrics']['average_w_entropy']:.6f}")
    print(f"Stability Trend: {report['consciousness_metrics']['stability_trend']:.6f}")
    
    # Visualize consciousness
    consciousness.visualize_consciousness()