-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvisualization.py
More file actions
2158 lines (1749 loc) · 83.3 KB
/
visualization.py
File metadata and controls
2158 lines (1749 loc) · 83.3 KB
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Visualization module for the three-body problem.
This module provides methods for visualizing the results from the unified framework
for the three-body problem, including trajectories, isomorphism structures, and
KAM tori.
"""
import math
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from mpl_toolkits.mplot3d import Axes3D
from typing import Dict, List, Tuple, Optional, Union, Any
import matplotlib.patches as mpatches
from kam_theory import KAMTheoryIntegration
from three_body_problem import HomotheticOrbits, LagrangianSolutions, ThreeBodyProblem
# Import local modules
# These imports would be used in real-world applications
class TrajectoriesVisualization:
"""
Class for visualizing three-body trajectories.
This class provides methods for creating static plots and animations of
three-body trajectories, including both standard and quaternionic views.
"""
def __init__(self, figsize: Tuple[float, float] = (10, 8), dpi: int = 100):
"""
Initialize the trajectories visualization.
Args:
figsize: Figure size (width, height) in inches
dpi: Figure resolution in dots per inch
"""
self.figsize = figsize
self.dpi = dpi
def plot_trajectories_2d(self, results: Dict, ax: Optional[plt.Axes] = None,
title: Optional[str] = None, show_initial: bool = True,
show_collisions: bool = True, legend_loc: str = 'best') -> plt.Figure:
"""
Create a 2D plot of three-body trajectories.
Args:
results: Dictionary with integration results
ax: Optional matplotlib axes to plot on
title: Optional title for the plot
show_initial: Whether to show the initial positions
show_collisions: Whether to highlight collision points
legend_loc: Location for the legend (e.g., 'best', 'right', 'upper right')
Returns:
The figure object
"""
if ax is None:
fig, ax = plt.subplots(figsize=self.figsize, dpi=self.dpi)
else:
fig = ax.figure
# Extract states and masses from results
states = results["states"]
masses = results.get("masses", np.array([1.0, 1.0, 1.0]))
times = results["t"]
# Extract positions for each body
r1 = states[:, 0:3] # positions of body 1
r2 = states[:, 3:6] # positions of body 2
r3 = states[:, 6:9] # positions of body 3
# Plot the trajectories in the x-y plane
ax.plot(r1[:, 0], r1[:, 1], label=f"Body 1 (m={masses[0]:.2f})")
ax.plot(r2[:, 0], r2[:, 1], label=f"Body 2 (m={masses[1]:.2f})")
ax.plot(r3[:, 0], r3[:, 1], label=f"Body 3 (m={masses[2]:.2f})")
# Add markers for the initial positions
if show_initial:
ax.scatter(r1[0, 0], r1[0, 1], s=100, marker='o', color='red')
ax.scatter(r2[0, 0], r2[0, 1], s=100, marker='o', color='red')
ax.scatter(r3[0, 0], r3[0, 1], s=100, marker='o', color='red')
ax.text(r1[0, 0], r1[0, 1], " Start", va='center')
# Add markers for the final positions
ax.scatter(r1[-1, 0], r1[-1, 1], s=100, marker='s', color='blue')
ax.scatter(r2[-1, 0], r2[-1, 1], s=100, marker='s', color='blue')
ax.scatter(r3[-1, 0], r3[-1, 1], s=100, marker='s', color='blue')
ax.text(r1[-1, 0], r1[-1, 1], " End", va='center')
# Highlight collision points if requested
if show_collisions and "collisions" in results:
collisions = results["collisions"]
for i, collision_time in enumerate(collisions["times"]):
# Find the closest time index
time_idx = np.argmin(np.abs(times - collision_time))
# Get the positions at the collision time
c_type = collisions["types"][i]
if c_type == "1-2":
c_pos = (r1[time_idx] + r2[time_idx]) / 2
elif c_type == "2-3":
c_pos = (r2[time_idx] + r3[time_idx]) / 2
elif c_type == "3-1":
c_pos = (r3[time_idx] + r1[time_idx]) / 2
# Highlight the collision
ax.scatter(c_pos[0], c_pos[1], s=150, marker='*', color='black')
ax.text(c_pos[0], c_pos[1], f" Collision ({c_type})", va='center')
# Set the aspect ratio to be equal
ax.set_aspect('equal')
# Add labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
if title:
ax.set_title(title)
else:
sigma = results.get("sigma", "unknown")
ax.set_title(f"Three-Body Problem Trajectories (σ={sigma})")
# Add a grid and legend
ax.grid(True, alpha=0.3)
ax.legend(loc=legend_loc)
return fig
def plot_trajectories_3d(self, results: Dict, title: Optional[str] = None,
show_initial: bool = True) -> plt.Figure:
"""
Create a 3D plot of three-body trajectories.
Args:
results: Dictionary with integration results
title: Optional title for the plot
show_initial: Whether to show the initial positions
Returns:
The figure object
"""
fig = plt.figure(figsize=self.figsize, dpi=self.dpi)
ax = fig.add_subplot(111, projection='3d')
# Extract states and masses from results
states = results["states"]
masses = results.get("masses", np.array([1.0, 1.0, 1.0]))
# Extract positions for each body
r1 = states[:, 0:3] # positions of body 1
r2 = states[:, 3:6] # positions of body 2
r3 = states[:, 6:9] # positions of body 3
# Plot the trajectories in 3D
ax.plot(r1[:, 0], r1[:, 1], r1[:, 2], label=f"Body 1 (m={masses[0]:.2f})")
ax.plot(r2[:, 0], r2[:, 1], r2[:, 2], label=f"Body 2 (m={masses[1]:.2f})")
ax.plot(r3[:, 0], r3[:, 1], r3[:, 2], label=f"Body 3 (m={masses[2]:.2f})")
# Add markers for the initial positions
if show_initial:
ax.scatter(r1[0, 0], r1[0, 1], r1[0, 2], s=100, marker='o', color='red')
ax.scatter(r2[0, 0], r2[0, 1], r2[0, 2], s=100, marker='o', color='red')
ax.scatter(r3[0, 0], r3[0, 1], r3[0, 2], s=100, marker='o', color='red')
# Add markers for the final positions
ax.scatter(r1[-1, 0], r1[-1, 1], r1[-1, 2], s=100, marker='s', color='blue')
ax.scatter(r2[-1, 0], r2[-1, 1], r2[-1, 2], s=100, marker='s', color='blue')
ax.scatter(r3[-1, 0], r3[-1, 1], r3[-1, 2], s=100, marker='s', color='blue')
# Add labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
if title:
ax.set_title(title)
else:
sigma = results.get("sigma", "unknown")
ax.set_title(f"Three-Body Problem Trajectories (σ={sigma})")
# Add a legend
ax.legend()
return fig
def create_animation(self, results: Dict, interval: int = 50,
save_path: Optional[str] = None) -> Union[FuncAnimation, plt.Figure]:
"""
Create an animation of three-body trajectories.
Args:
results: Dictionary with integration results
interval: Interval between frames in milliseconds
save_path: Optional path to save the animation
Returns:
The animation object or figure if saving
"""
fig, ax = plt.subplots(figsize=self.figsize, dpi=self.dpi)
# Extract states and masses from results
states = results["states"]
masses = results.get("masses", np.array([1.0, 1.0, 1.0]))
# Extract positions for each body
r1 = states[:, 0:3] # positions of body 1
r2 = states[:, 3:6] # positions of body 2
r3 = states[:, 6:9] # positions of body 3
# Calculate the limits for the plot
all_positions = np.vstack([r1[:, :2], r2[:, :2], r3[:, :2]])
xmin, ymin = np.min(all_positions, axis=0) - 0.1
xmax, ymax = np.max(all_positions, axis=0) + 0.1
# Plot the complete trajectories (faded)
ax.plot(r1[:, 0], r1[:, 1], alpha=0.3, color='blue')
ax.plot(r2[:, 0], r2[:, 1], alpha=0.3, color='orange')
ax.plot(r3[:, 0], r3[:, 1], alpha=0.3, color='green')
# Create markers for the bodies
point1, = ax.plot([], [], 'o', markersize=10*masses[0], color='blue')
point2, = ax.plot([], [], 'o', markersize=10*masses[1], color='orange')
point3, = ax.plot([], [], 'o', markersize=10*masses[2], color='green')
# Create line segments for the trails
trail_length = 50
trail1, = ax.plot([], [], '-', color='blue', alpha=0.7)
trail2, = ax.plot([], [], '-', color='orange', alpha=0.7)
trail3, = ax.plot([], [], '-', color='green', alpha=0.7)
# Set the axis limits
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
ax.set_aspect('equal')
# Add labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
sigma = results.get("sigma", "unknown")
ax.set_title(f"Three-Body Problem Animation (σ={sigma})")
# Add a legend
ax.legend([point1, point2, point3],
[f"Body 1 (m={masses[0]:.2f})",
f"Body 2 (m={masses[1]:.2f})",
f"Body 3 (m={masses[2]:.2f})"])
# Add a grid
ax.grid(True, alpha=0.3)
# Initialization function for the animation
def init():
point1.set_data([], [])
point2.set_data([], [])
point3.set_data([], [])
trail1.set_data([], [])
trail2.set_data([], [])
trail3.set_data([], [])
return point1, point2, point3, trail1, trail2, trail3
# Animation function
def animate(i):
# Update the markers
point1.set_data(r1[i, 0], r1[i, 1])
point2.set_data(r2[i, 0], r2[i, 1])
point3.set_data(r3[i, 0], r3[i, 1])
# Update the trails
start_idx = max(0, i - trail_length)
trail1.set_data(r1[start_idx:i+1, 0], r1[start_idx:i+1, 1])
trail2.set_data(r2[start_idx:i+1, 0], r2[start_idx:i+1, 1])
trail3.set_data(r3[start_idx:i+1, 0], r3[start_idx:i+1, 1])
return point1, point2, point3, trail1, trail2, trail3
# Create the animation
anim = FuncAnimation(fig, animate, init_func=init, frames=len(states),
interval=interval, blit=True)
# Save the animation if a path is provided
if save_path:
anim.save(save_path, writer='pillow', dpi=self.dpi)
plt.close(fig)
return fig
return anim
def plot_quaternionic_path(self, quat_path: List, title: Optional[str] = None) -> plt.Figure:
"""
Create a 3D visualization of a quaternionic path.
Args:
quat_path: List of quaternions representing the path
title: Optional title for the plot
Returns:
The figure object
"""
fig = plt.figure(figsize=self.figsize, dpi=self.dpi)
ax = fig.add_subplot(111, projection='3d')
# Extract the real, i, and j components of the quaternions
real_parts = [q.scalar_part() for q in quat_path]
i_parts = [q.vector_part()[0] for q in quat_path]
j_parts = [q.vector_part()[1] for q in quat_path]
# Plot the quaternionic path in 3D
ax.plot(real_parts, i_parts, j_parts, marker='o', markersize=4)
# Add markers for the start and end points
ax.scatter(real_parts[0], i_parts[0], j_parts[0], s=100, marker='o', color='red', label='Start')
ax.scatter(real_parts[-1], i_parts[-1], j_parts[-1], s=100, marker='s', color='blue', label='End')
# Draw projections onto the coordinate planes
ax.plot(real_parts, i_parts, np.zeros_like(j_parts), 'r--', alpha=0.3)
ax.plot(real_parts, np.zeros_like(i_parts), j_parts, 'g--', alpha=0.3)
ax.plot(np.zeros_like(real_parts), i_parts, j_parts, 'b--', alpha=0.3)
# Add labels and title
ax.set_xlabel('Real Part')
ax.set_ylabel('i Component')
ax.set_zlabel('j Component')
if title:
ax.set_title(title)
else:
ax.set_title("Quaternionic Path")
# Add a legend
ax.legend()
return fig
class IsomorphismVisualization:
"""
Class for visualizing isomorphism structures in the three-body problem.
This class provides methods for creating visual representations of the
isomorphisms between Differential Galois Theory, Painlevé Analysis, and
Quaternionic Regularization.
"""
def __init__(self, figsize: Tuple[float, float] = (12, 8), dpi: int = 100):
"""
Initialize the isomorphism visualization.
Args:
figsize: Figure size (width, height) in inches
dpi: Figure resolution in dots per inch
"""
self.figsize = figsize
self.dpi = dpi
def plot_integration_diagram(self, sigma: float, ax: Optional[plt.Axes] = None,
title: Optional[str] = None) -> plt.Figure:
"""
Create a visual representation of the correspondence between the three approaches.
"""
# Import Ellipse from patches module
from matplotlib.patches import Ellipse
if ax is None:
fig, ax = plt.subplots(figsize=self.figsize, dpi=self.dpi)
else:
fig = ax.figure
# Determine the isomorphism structure based on sigma
if abs(sigma - 1/3) < 1e-10 or abs(sigma - 2**3/3**3) < 1e-10:
galois_group = "Dihedral"
identity_component = "Diagonal (abelian)"
branch_point_type = "square root (Z_2)"
monodromy_type = "Z_2"
integrability = "Partially integrable"
color = "green"
elif abs(sigma - 2/3**2) < 1e-10:
galois_group = "Triangular"
identity_component = "Diagonal (abelian)"
branch_point_type = "none (meromorphic)"
monodromy_type = "Trivial"
integrability = "Partially integrable"
color = "blue"
else:
galois_group = "SL(2,C)"
identity_component = "SL(2,C) (non-abelian)"
branch_point_type = "transcendental"
monodromy_type = "Complex"
integrability = "Non-integrable"
color = "red"
# Define the positions for the three approaches
dgt_pos = (0.2, 0.7)
pa_pos = (0.8, 0.7)
qr_pos = (0.5, 0.2)
# Define consistent ellipse size
width, height = 0.25, 0.15
# Draw the triangle connecting the three approaches
ax.plot([dgt_pos[0], pa_pos[0]], [dgt_pos[1], pa_pos[1]], '-', color=color, lw=2)
ax.plot([dgt_pos[0], qr_pos[0]], [dgt_pos[1], qr_pos[1]], '-', color=color, lw=2)
ax.plot([pa_pos[0], qr_pos[0]], [pa_pos[1], qr_pos[1]], '-', color=color, lw=2)
# Add ellipses for each approach with consistent size
dgt_circle = Ellipse(dgt_pos, width, height, fill=True, alpha=0.3, color=color)
pa_circle = Ellipse(pa_pos, width, height, fill=True, alpha=0.3, color=color)
qr_circle = Ellipse(qr_pos, width, height, fill=True, alpha=0.3, color=color)
ax.add_patch(dgt_circle)
ax.add_patch(pa_circle)
ax.add_patch(qr_circle)
# Add labels for each approach
ax.text(dgt_pos[0], dgt_pos[1], "Differential\nGalois Theory", ha='center', va='center', fontsize=12)
ax.text(pa_pos[0], pa_pos[1], "Painlevé\nAnalysis", ha='center', va='center', fontsize=12)
ax.text(qr_pos[0], qr_pos[1], "Quaternionic\nRegularization", ha='center', va='center', fontsize=12)
# Add isomorphism labels on the edges
ax.text((dgt_pos[0] + pa_pos[0])/2, (dgt_pos[1] + pa_pos[1])/2 + 0.05,
"Φ_GP", ha='center', va='center', fontsize=12, fontweight='bold')
ax.text((dgt_pos[0] + qr_pos[0])/2 - 0.05, (dgt_pos[1] + qr_pos[1])/2,
"Φ_GQ", ha='center', va='center', fontsize=12, fontweight='bold')
ax.text((pa_pos[0] + qr_pos[0])/2 + 0.05, (pa_pos[1] + qr_pos[1])/2,
"Φ_PQ", ha='center', va='center', fontsize=12, fontweight='bold')
# Add properties in each circle
ax.text(dgt_pos[0], dgt_pos[1] - 0.3, f"Galois Group:\n{galois_group}", ha='center', va='center')
ax.text(pa_pos[0], pa_pos[1] - 0.3, f"Branch Points:\n{branch_point_type}", ha='center', va='center')
ax.text(qr_pos[0], qr_pos[1] + 0.25, f"Monodromy:\n{monodromy_type}", ha='center', va='center')
# Add integrability information
ax.text(0.5, 0.95, f"Mass Parameter: σ = {sigma}", ha='center', va='center', fontsize=14)
ax.text(0.5, 0.9, f"Integrability: {integrability}", ha='center', va='center', fontsize=14)
# Set the axis properties
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.axis('off')
return fig
def plot_branching_structure(self, sigma: float, ax: Optional[plt.Axes] = None,
title: Optional[str] = None) -> plt.Figure:
"""
Create a visualization of the branching structure in the complex plane.
Args:
sigma: Mass parameter σ
ax: Optional matplotlib axes to plot on
title: Optional title for the plot
Returns:
The figure object
"""
if ax is None:
fig, ax = plt.subplots(figsize=self.figsize, dpi=self.dpi)
else:
fig = ax.figure
# Define the singular points in the complex plane
singularities = [(0, 0), (1, 0), (2, 0)] # t=0, t=1, t=a=2
# Plot the complex plane
ax.axhline(y=0, color='black', linestyle='-', alpha=0.3)
ax.axvline(x=0, color='black', linestyle='-', alpha=0.3)
# Plot the singularities
for s in singularities:
ax.scatter(s[0], s[1], color='red', s=100)
ax.text(s[0], s[1] + 0.1, f"t = {s[0]}", ha='center')
# Determine the branching structure based on sigma
if abs(sigma - 1/3) < 1e-10 or abs(sigma - 2**3/3**3) < 1e-10:
# Z_2 branching (square root type)
# Draw branch cuts as lines from singularities downward
for s in singularities:
ax.plot([s[0], s[0]], [s[1], s[1] - 1], 'r--')
# Draw loops around the singularities
theta = np.linspace(0, 2*np.pi, 100)
for s in singularities:
ax.plot(s[0] + 0.2*np.cos(theta), s[1] + 0.2*np.sin(theta), 'g-')
title = f"Z_2 Branching Structure (σ = {sigma})"
elif abs(sigma - 2/3**2) < 1e-10:
# No branching (meromorphic)
# Draw small circles around the singularities
theta = np.linspace(0, 2*np.pi, 100)
for s in singularities:
ax.plot(s[0] + 0.2*np.cos(theta), s[1] + 0.2*np.sin(theta), 'b-')
title = f"No Branching Structure (σ = {sigma})"
else:
# Transcendental branching
# Draw branch cuts as lines from singularities in different directions
for i, s in enumerate(singularities):
angle = np.pi/4 * (i - 1)
ax.plot([s[0], s[0] + np.cos(angle)], [s[1], s[1] + np.sin(angle)], 'r--')
# Draw more complex loops around the singularities
theta = np.linspace(0, 2*np.pi, 100)
for s in singularities:
ax.plot(s[0] + 0.2*np.cos(theta), s[1] + 0.2*np.sin(theta), 'r-')
title = f"Transcendental Branching Structure (σ = {sigma})"
# Add labels and title
ax.set_xlabel('Re(t)')
ax.set_ylabel('Im(t)')
ax.set_title(title)
# Set equal aspect ratio
ax.set_aspect('equal')
# Set suitable axis limits
ax.set_xlim(-0.5, 2.5)
ax.set_ylim(-1.2, 1.2)
# Add a grid
ax.grid(True, alpha=0.3)
return fig
def plot_quaternionic_branch_manifold(self, sigma: float, ax: Optional[plt.Axes] = None,
title: Optional[str] = None) -> plt.Figure:
"""
Create a visualization of the quaternionic branch manifold.
"""
if ax is None:
fig = plt.figure(figsize=self.figsize, dpi=self.dpi)
ax = fig.add_subplot(111, projection='3d')
else:
fig = ax.figure
# Define the quaternionic branch manifold structure based on sigma
t_c = 1 # Collision time
if abs(sigma - 1/3) < 1e-10:
# Z_2 monodromy - 2D manifold
u = np.linspace(0, 2*np.pi, 30)
v = np.linspace(0, 1, 20)
u, v = np.meshgrid(u, v)
# Parameters for the first case
rho = 0.2 # Radius
# Real part (scalar part of quaternion)
x = t_c + rho * np.cos(u)
# i component
y = rho * np.sin(u)
# j component
z = 0.1 * v * np.sin(u)
# Plot the surface with distinctive color for σ = 1/3 case
surf = ax.plot_surface(x, y, z, cmap='plasma', linewidth=0, alpha=0.7)
title = title or f"Z₂ Branch Manifold (σ = 1/3)"
elif abs(sigma - 2**3/3**3) < 1e-10:
# Z_2 monodromy for σ = 2³/3³ (similar to 1/3 but with a different pattern)
u = np.linspace(0, 2*np.pi, 30)
v = np.linspace(0, 1, 20)
u, v = np.meshgrid(u, v)
# Different parameters to create a distinct visualization for σ = 2³/3³
rho = 0.2 # Same base radius
# Create a slightly different shape for this manifold
x = t_c + rho * np.cos(u)
y = rho * np.sin(u)
z = 0.1 * v * np.cos(2*u) # Different pattern for j component
# Use a different colormap for this case
surf = ax.plot_surface(x, y, z, cmap='viridis', linewidth=0, alpha=0.7)
title = title or f"Z₂ Branch Manifold (σ = 2³/3³)"
elif abs(sigma - 2/3**2) < 1e-10:
# Trivial monodromy - no branch manifold
# Plot a single point at the singularity with larger size
ax.scatter([t_c], [0], [0], color='blue', s=300, label='Regularizable Point')
# Add a small sphere to make it more visible
u = np.linspace(0, 2*np.pi, 20)
v = np.linspace(0, np.pi, 20)
r = 0.05 # Small radius
x = t_c + r * np.outer(np.cos(u), np.sin(v))
y = r * np.outer(np.sin(u), np.sin(v))
z = r * np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, color='skyblue', alpha=0.5)
title = title or f"No Branch Manifold (σ = 2/3²)"
else:
# Complex monodromy - 3D manifold
# Create a list of points for the manifold
x_points = []
y_points = []
z_points = []
rho = 0.2 # Base radius
# Generate a more complex structure
for theta in np.linspace(0, 2*np.pi, 20):
for phi in np.linspace(0, np.pi, 10):
for r in [rho, rho*0.8, rho*0.6]:
x = t_c + r * np.cos(theta)
y = r * np.sin(theta)
z = 0.1 * r * np.sin(phi)
x_points.append(x)
y_points.append(y)
z_points.append(z)
# Plot with distinctive color for complex case
ax.scatter(x_points, y_points, z_points, c='red', s=15, alpha=0.7)
title = title or f"Complex Branch Manifold (σ = {sigma:.4f})"
# Add labels and title
ax.set_xlabel('Real Part')
ax.set_ylabel('i Component')
ax.set_zlabel('j Component')
ax.set_title(title)
# Add a point for the collision
ax.scatter([t_c], [0], [0], color='red', s=100, label='Collision Point')
# Add a legend
ax.legend()
return fig
def plot_parameter_space(self, sigma_values: np.ndarray, results: List[Dict],
ax: Optional[plt.Axes] = None,
title: Optional[str] = None) -> plt.Figure:
"""
Create a visualization of the parameter space colored by isomorphism structures.
"""
if ax is None:
fig, ax = plt.subplots(figsize=self.figsize, dpi=self.dpi)
else:
fig = ax.figure
# Extract information from results
colors = []
galois_groups = []
# First pass to extract and correctly assign colors based on Galois group
for result in results:
if "details" in result and "galois_group" in result["details"]:
galois_group = result["details"]["galois_group"]
else:
galois_group = result.get("galois_group", "Unknown")
galois_groups.append(galois_group)
# Ensure proper color assignment based on Galois group type
if "Triangular" in galois_group:
colors.append("blue")
elif "Dihedral" in galois_group:
colors.append("green")
elif "SL(2,C)" in galois_group:
colors.append("red")
else:
colors.append("gray")
# Group points by sigma value to detect overlaps
sigma_to_indices = {}
for i, sigma in enumerate(sigma_values):
# Round to 5 decimal places for grouping
rounded_sigma = round(sigma, 5)
if rounded_sigma not in sigma_to_indices:
sigma_to_indices[rounded_sigma] = []
sigma_to_indices[rounded_sigma].append(i)
# Plot with horizontal offsets for overlapping points
for rounded_sigma, indices in sigma_to_indices.items():
offset = -0.0025 * (len(indices) - 1) / 2
for i in indices:
# Apply offset to x-coordinate if multiple points at same sigma
x_pos = sigma_values[i] + offset
# Increase offset for next point in this group
offset += 0.005
ax.scatter(x_pos, 1, c=colors[i], s=100)
# Add Galois group annotation for important points
if (abs(sigma_values[i] - 1/3) < 1e-5 or
abs(sigma_values[i] - 2**3/3**3) < 1e-5 or
abs(sigma_values[i] - 2/3**2) < 1e-5):
ax.text(x_pos, 1.1, galois_groups[i],
rotation=90, verticalalignment='bottom', horizontalalignment='center',
fontsize=10)
# Add vertical lines at the exceptional values
exceptional_values = [1/3, 2**3/3**3, 2/3**2]
for val in exceptional_values:
ax.axvline(x=val, color='gray', linestyle='--', alpha=0.7)
ax.text(val, 0.9, f"σ = {val:.6f}", rotation=90,
verticalalignment='bottom', horizontalalignment='right')
# Create a custom legend
legend_elements = [
mpatches.Patch(color='blue', label='Triangular (σ = 2/3²)'),
mpatches.Patch(color='green', label='Dihedral (σ = 1/3, 2³/3³)'),
mpatches.Patch(color='red', label='SL(2,C) (General case)')
]
ax.legend(handles=legend_elements, loc='upper center')
# Set labels and title
ax.set_xlabel('Mass Parameter σ')
ax.set_title('Parameter Space of the Three-Body Problem')
# Remove y-axis ticks
ax.set_yticks([])
# Set suitable axis limits
ax.set_xlim(min(sigma_values) - 0.05, max(sigma_values) + 0.05)
ax.set_ylim(0.5, 1.5)
# Add a grid for x-axis
ax.grid(axis='x', alpha=0.3)
return fig
class KAMVisualization:
"""
Class for visualizing KAM Theory results.
This class provides methods for visualizing KAM tori, phase space structure,
and the relationship between KAM Theory and the isomorphism framework.
"""
def __init__(self, figsize: Tuple[float, float] = (12, 8), dpi: int = 100):
"""
Initialize the KAM visualization.
Args:
figsize: Figure size (width, height) in inches
dpi: Figure resolution in dots per inch
"""
self.figsize = figsize
self.dpi = dpi
def plot_kam_measure(self, sigma_values: np.ndarray, kam_measures: np.ndarray,
actual_sigma_values: Optional[np.ndarray] = None,
kam_std_devs: Optional[np.ndarray] = None,
ax: Optional[plt.Axes] = None,
title: Optional[str] = None) -> plt.Figure:
"""
Create a plot of KAM measure vs. mass parameter with error bars.
Args:
sigma_values: Array of requested sigma values
kam_measures: Array of KAM measures
actual_sigma_values: Array of actual sigma values used (if different)
kam_std_devs: Optional array of standard deviations for error bars
ax: Optional matplotlib axes to plot on
title: Optional title for the plot
Returns:
The figure object
"""
# Create a new figure if ax is not provided or if it's the wrong type
if not hasattr(ax, 'figure'):
fig, ax = plt.subplots(figsize=self.figsize, dpi=self.dpi)
else:
fig = ax.figure
# Use actual sigma values if provided, otherwise use requested values
plot_sigma_values = actual_sigma_values if actual_sigma_values is not None else sigma_values
# Plot the KAM measure with error bars if available
if kam_std_devs is not None:
ax.errorbar(plot_sigma_values, kam_measures, yerr=kam_std_devs,
fmt='o-', markersize=8, lw=2, capsize=5)
else:
ax.plot(plot_sigma_values, kam_measures, 'o-', markersize=8, lw=2)
# Add data points with coordinates for key values
for i, (sigma, measure) in enumerate(zip(plot_sigma_values, kam_measures)):
if kam_std_devs is not None:
label = f"({sigma:.6f}, {measure:.4f}±{kam_std_devs[i]:.4f})"
else:
label = f"({sigma:.6f}, {measure:.4f})"
ax.annotate(label, (sigma, measure),
xytext=(0, 10), textcoords='offset points',
ha='center', fontsize=8)
# Mark the exceptional values
exceptional_values = [1/3, 2**3/3**3, 2/3**2]
for sigma_0 in exceptional_values:
ax.axvline(x=sigma_0, color='r', linestyle='--', alpha=0.7)
ax.text(sigma_0, 0.1, f"σ = {sigma_0:.6f}", rotation=90,
va='bottom', ha='center')
# Add a note about the mathematical constraint
ax.text(0.5, 0.02,
"Note: For positive masses, σ is mathematically constrained to 0 < σ ≤ 1/3",
transform=ax.transAxes, ha='center', bbox=dict(facecolor='lightyellow', alpha=0.5))
# Set axis labels and title
ax.set_xlabel('Mass Parameter σ')
ax.set_ylabel('Measure of Phase Space Occupied by KAM Tori')
ax.set_title(title or 'KAM Measure vs. Mass Parameter')
# Set axis limits to valid range
ax.set_xlim(0, 1/3 + 0.05)
ax.set_ylim(0, 1.05)
# Add a grid
ax.grid(True, alpha=0.3)
return fig
def plot_poincare_section(self, poincare_data: Dict, ax: Optional[plt.Axes] = None,
title: Optional[str] = None) -> plt.Figure:
"""
Create a visualization of a Poincaré section.
Args:
poincare_data: Dictionary with Poincaré section data
ax: Optional matplotlib axes to plot on
title: Optional title for the plot
Returns:
The figure object
"""
if ax is None:
fig, ax = plt.subplots(figsize=self.figsize, dpi=self.dpi)
else:
fig = ax.figure
# Extract data from the dictionary
q_values = poincare_data["q_values"]
p_values = poincare_data["p_values"]
orbit_indices = poincare_data["orbit_indices"]
sigma = poincare_data.get("sigma", "unknown")
# Plot the Poincaré section
for orbit_idx in np.unique(orbit_indices):
mask = orbit_indices == orbit_idx
ax.scatter(q_values[mask], p_values[mask], s=2)
# Set labels and title
ax.set_xlabel('q')
ax.set_ylabel('p')
if title:
ax.set_title(title)
else:
ax.set_title(f"Poincaré Section (σ={sigma})")
# Add a grid
ax.grid(True, alpha=0.3)
return fig
def plot_comparison(self, simulation_results: Dict, isomorphism_results: Dict,
kam_results: Dict) -> plt.Figure:
"""
Create a comparison visualization between simulation, isomorphism, and KAM results.
Args:
simulation_results: Dictionary with simulation results
isomorphism_results: Dictionary with isomorphism verification results
kam_results: Dictionary with KAM analysis results
Returns:
The figure object
"""
fig = plt.figure(figsize=(self.figsize[0], self.figsize[1]*1.5), dpi=self.dpi)
# Extract sigma from the results
sigma = simulation_results.get("sigma", isomorphism_results.get("mass_parameter", "unknown"))
# Create a layout with three subplots
ax1 = fig.add_subplot(311) # Trajectories
ax2 = fig.add_subplot(312) # Isomorphism structure
ax3 = fig.add_subplot(313) # KAM measure
# Plot trajectories in the first subplot
states = simulation_results["states"]
r1 = states[:, 0:3]
r2 = states[:, 3:6]
r3 = states[:, 6:9]
ax1.plot(r1[:, 0], r1[:, 1], label="Body 1")
ax1.plot(r2[:, 0], r2[:, 1], label="Body 2")
ax1.plot(r3[:, 0], r3[:, 1], label="Body 3")
ax1.set_aspect('equal')
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
ax1.set_title(f"Trajectories (σ={sigma})")
ax1.legend()
ax1.grid(True, alpha=0.3)
# Plot isomorphism structure in the second subplot
if "details" in isomorphism_results:
details = isomorphism_results["details"]
galois_group = details.get("galois_group", "Unknown")
branch_type = details.get("branch_point_type", "Unknown")
monodromy = details.get("monodromy_type", "Unknown")
ax2.axis('off')
ax2.text(0.1, 0.7, f"Galois Group: {galois_group}", fontsize=12)
ax2.text(0.1, 0.5, f"Branch Points: {branch_type}", fontsize=12)
ax2.text(0.1, 0.3, f"Monodromy: {monodromy}", fontsize=12)
ax2.set_title("Isomorphism Structure")
# Plot KAM measure in the third subplot
if "sigma_values" in kam_results and "kam_measures" in kam_results:
sigma_values = kam_results["sigma_values"]
kam_measures = kam_results["kam_measures"]
# Find the index of the current sigma value
closest_idx = np.argmin(np.abs(np.array(sigma_values) - float(sigma)))
# Plot KAM measure vs sigma
ax3.plot(sigma_values, kam_measures, 'o-', markersize=6, lw=2)
ax3.axvline(x=sigma_values[closest_idx], color='red', linestyle='--', alpha=0.7)
# Add vertical lines at the exceptional values
exceptional_values = [1/3, 2**3/3**3, 2/3**2]
for val in exceptional_values:
ax3.axvline(x=val, color='gray', linestyle='--', alpha=0.5)
ax3.set_xlabel('Mass Parameter σ')
ax3.set_ylabel('KAM Measure')
ax3.set_title("KAM Measure vs. Mass Parameter")
ax3.grid(True, alpha=0.3)
# Add an overall title
fig.suptitle(f"Three-Body Problem Analysis (σ={sigma})", fontsize=16, y=0.98)
# Adjust layout
fig.tight_layout(rect=[0, 0, 1, 0.96])
return fig
def generate_latex_kam_table(self, table_data: Dict, caption: str = "Correspondence between Isomorphism Structures and KAM Theory",
label: str = "tab:isomorphism_kam") -> str:
"""
Generate a LaTeX table showing the correspondence between isomorphism structures and KAM theory.
Args:
table_data: Dictionary with table data
caption: Table caption
label: Table label
Returns:
LaTeX table as string
"""
# Extract data
mass_values = table_data["mass_values"]
structures = table_data["structures"]
integrability = table_data["integrability"]
kam_measures = table_data["kam_measures"]
# Create LaTeX table
latex_table = "\\begin{table}[htbp]\n"
latex_table += "\\centering\n"
latex_table += f"\\caption{{{caption}}}\n"
latex_table += f"\\label{{{label}}}\n"
latex_table += "\\begin{tabular}{lccc}\n"
latex_table += "\\toprule\n"
latex_table += "Mass $\\sigma$ & Isomorphism Structure & Integrability & KAM Measure \\\\\n"
latex_table += "\\midrule\n"
# Add rows
for i in range(len(mass_values)):
sigma = mass_values[i]
# Format sigma nicely for fractions
if abs(sigma - 1/3) < 1e-10:
sigma_str = "$\\sigma = 1/3$"
elif abs(sigma - 2**3/3**3) < 1e-10:
sigma_str = "$\\sigma = 2^3/3^3$"
elif abs(sigma - 2/3**2) < 1e-10:
sigma_str = "$\\sigma = 2/3^2$"
else: