File size: 10,217 Bytes
7ccd32c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import torch
from singularity_core import SingularityCore
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.patches as patches

class SingularityVisualizer:
    """Визуализация сингулярного ядра в стиле React-компонента."""
    
    def __init__(self, singularity_radius=0.01, wormhole_depth=2.1, rotation_speed=0.0):
        self.singularity = SingularityCore(
            singularity_radius=singularity_radius,
            wormhole_depth=wormhole_depth,
            rotation_speed=rotation_speed,
            embedding_dim=256
        )
        
        # Параметры визуализации
        self.fig = None
        self.ax = None
        self.animation = None
        
    def create_torus_mesh(self, theta_res=64, phi_res=128):
        """Создание тороидальной сетки с wormhole эффектом."""
        theta = np.linspace(0, 2*np.pi, theta_res)
        phi = np.linspace(0, 2*np.pi, phi_res)
        
        theta_grid, phi_grid = np.meshgrid(theta, phi)
        
        # Тороидальные координаты
        R = 1.0  # Major radius
        r = self.singularity.singularity_radius  # Minor radius
        
        x = (R + r * np.cos(phi_grid)) * np.cos(theta_grid)
        y = (R + r * np.cos(phi_grid)) * np.sin(theta_grid)
        z = r * np.sin(phi_grid)
        
        # Wormhole effect: z = sin(3θ) × depth
        wormhole_effect = np.sin(3 * theta_grid) * self.singularity.wormhole_depth
        z += wormhole_effect
        
        return x, y, z
    
    def visualize_singularity(self, show_trajectories=True, show_singularity=True):
        """Основная визуализация сингулярности."""
        self.fig = plt.figure(figsize=(12, 8))
        self.ax = self.fig.add_subplot(111, projection='3d')
        
        # Создание тороидальной сетки
        x, y, z = self.create_torus_mesh()
        
        # Отрисовка тороидальной поверхности
        self.ax.plot_wireframe(x, y, z, color='#00ffff', alpha=0.8, linewidth=0.5)
        
        # Траектории частиц
        if show_trajectories:
            self._add_trajectories()
        
        # Сингулярность в центре
        if show_singularity:
            self.ax.scatter([0], [0], [0], color='red', s=100, alpha=0.8, label='Singularity')
        
        # Настройка осей
        self.ax.set_xlabel('X')
        self.ax.set_ylabel('Y')
        self.ax.set_zlabel('Z')
        self.ax.set_title(f'Singularity Core\nRadius: {self.singularity.singularity_radius:.3f}, '
                         f'Depth: {self.singularity.wormhole_depth:.3f}')
        
        # Установка равных масштабов
        max_range = np.array([x.max()-x.min(), y.max()-y.min(), z.max()-z.min()]).max() / 2.0
        mid_x = (x.max()+x.min()) * 0.5
        mid_y = (y.max()+y.min()) * 0.5
        mid_z = (z.max()+z.min()) * 0.5
        self.ax.set_xlim(mid_x - max_range, mid_x + max_range)
        self.ax.set_ylim(mid_y - max_range, mid_y + max_range)
        self.ax.set_zlim(mid_z - max_range, mid_z + max_range)
        
        plt.tight_layout()
        return self.fig
    
    def _add_trajectories(self):
        """Добавление траекторий частиц."""
        # Создаем несколько траекторий
        num_trajectories = 5
        for i in range(num_trajectories):
            # Случайная траектория вокруг тора
            t = np.linspace(0, 4*np.pi, 100)
            theta = t + i * 2*np.pi/num_trajectories
            phi = 0.5 * np.sin(2*t) + i * np.pi/num_trajectories
            
            R = 1.0
            r = self.singularity.singularity_radius
            
            x_traj = (R + r * np.cos(phi)) * np.cos(theta)
            y_traj = (R + r * np.cos(phi)) * np.sin(theta)
            z_traj = r * np.sin(phi) + np.sin(3 * theta) * self.singularity.wormhole_depth
            
            self.ax.plot(x_traj, y_traj, z_traj, 'o-', markersize=2, alpha=0.7, color='white')
    
    def animate_singularity(self, frames=100):
        """Анимация сингулярности."""
        self.fig = plt.figure(figsize=(12, 8))
        self.ax = self.fig.add_subplot(111, projection='3d')
        
        def animate(frame):
            self.ax.clear()
            
            # Обновляем параметры для анимации
            rotation_angle = frame * 2 * np.pi / frames * self.singularity.rotation_speed
            
            # Создаем тороидальную сетку с поворотом
            theta = np.linspace(0, 2*np.pi, 64)
            phi = np.linspace(0, 2*np.pi, 128)
            theta_grid, phi_grid = np.meshgrid(theta + rotation_angle, phi)
            
            R = 1.0
            r = self.singularity.singularity_radius
            
            x = (R + r * np.cos(phi_grid)) * np.cos(theta_grid)
            y = (R + r * np.cos(phi_grid)) * np.sin(theta_grid)
            z = r * np.sin(phi_grid) + np.sin(3 * theta_grid) * self.singularity.wormhole_depth
            
            self.ax.plot_wireframe(x, y, z, color='#00ffff', alpha=0.8, linewidth=0.5)
            
            # Сингулярность
            self.ax.scatter([0], [0], [0], color='red', s=100, alpha=0.8)
            
            # Настройка осей
            self.ax.set_xlabel('X')
            self.ax.set_ylabel('Y')
            self.ax.set_zlabel('Z')
            self.ax.set_title(f'Singularity Animation\nFrame: {frame}/{frames}')
            
            # Установка равных масштабов
            max_range = 2.0
            self.ax.set_xlim(-max_range, max_range)
            self.ax.set_ylim(-max_range, max_range)
            self.ax.set_zlim(-max_range, max_range)
        
        self.animation = animation.FuncAnimation(
            self.fig, animate, frames=frames, interval=50, blit=False
        )
        
        return self.animation
    
    def show_transformation_metrics(self):
        """Показать метрики трансформации."""
        # Создаем тестовое состояние
        test_state = torch.randn(1, 10, 256)
        
        # Применяем трансформацию
        result = self.singularity.self_wrapping_cycle(test_state, "Визуализация")
        
        if result["success"]:
            metrics = result["metrics"]
            
            # Создаем график метрик
            fig, axes = plt.subplots(2, 2, figsize=(12, 8))
            fig.suptitle('Singularity Transformation Metrics', fontsize=16)
            
            # Метрики
            metric_names = ['State Transformation', 'Curvature', 'Entropy', 'Coherence']
            metric_values = [
                metrics['state_transformation'],
                metrics['curvature'],
                metrics['entropy'] if not np.isnan(metrics['entropy']) else 0,
                metrics['coherence']
            ]
            
            colors = ['#00ffff', '#ff00ff', '#ffff00', '#00ff00']
            
            for i, (name, value, color) in enumerate(zip(metric_names, metric_values, colors)):
                ax = axes[i//2, i%2]
                ax.bar([name], [value], color=color, alpha=0.7)
                ax.set_title(name)
                ax.set_ylabel('Value')
                ax.text(0, value, f'{value:.3f}', ha='center', va='bottom')
            
            plt.tight_layout()
            return fig
        
        return None
    
    def update_parameters(self, singularity_radius=None, wormhole_depth=None, rotation_speed=None):
        """Обновление параметров сингулярности."""
        self.singularity.update_parameters(
            singularity_radius=singularity_radius,
            wormhole_depth=wormhole_depth,
            rotation_speed=rotation_speed
        )
        print(f"✅ Параметры обновлены: r={self.singularity.singularity_radius:.3f}, "
              f"depth={self.singularity.wormhole_depth:.3f}, speed={self.singularity.rotation_speed:.3f}")

def demo_singularity_visualization():
    """Демонстрация визуализации сингулярности."""
    print("🌀 Демонстрация сингулярной визуализации...")
    
    # Создаем визуализатор
    visualizer = SingularityVisualizer(
        singularity_radius=0.01,
        wormhole_depth=2.1,
        rotation_speed=0.5
    )
    
    # Статическая визуализация
    print("📊 Создание статической визуализации...")
    fig1 = visualizer.visualize_singularity(show_trajectories=True, show_singularity=True)
    plt.savefig('singularity_static.png', dpi=300, bbox_inches='tight')
    print("✅ Статическая визуализация сохранена как 'singularity_static.png'")
    
    # Метрики трансформации
    print("📈 Создание графика метрик...")
    fig2 = visualizer.show_transformation_metrics()
    if fig2:
        plt.savefig('singularity_metrics.png', dpi=300, bbox_inches='tight')
        print("✅ График метрик сохранен как 'singularity_metrics.png'")
    
    # Анимация
    print("🎬 Создание анимации...")
    anim = visualizer.animate_singularity(frames=50)
    anim.save('singularity_animation.gif', writer='pillow', fps=10)
    print("✅ Анимация сохранена как 'singularity_animation.gif'")
    
    # Интерактивная демонстрация
    print("🖱️ Запуск интерактивной демонстрации...")
    plt.show()
    
    print("🎉 Демонстрация завершена!")

if __name__ == "__main__":
    demo_singularity_visualization()