Created
May 23, 2025 21:54
-
-
Save attentionmech/97632427b503ab014535b529d130f833 to your computer and use it in GitHub Desktop.
matplotlib 4d pca demo code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import matplotlib.pyplot as plt | |
from sklearn.decomposition import PCA | |
from itertools import product | |
def generate_4d_honeycomb(grid_size=4, spacing=2.0): | |
"""Generate a 4D hexagonal-like lattice (offset in x/y, uniform in z/w).""" | |
points = [] | |
edges = [] | |
point_index = {} | |
idx = 0 | |
for ix, iy, iz, iw in product(range(grid_size), repeat=4): | |
# Hexagonal offset in 2D plane (x/y) | |
x = ix * spacing * 0.866 # cos(30°) | |
y = iy * spacing + (ix % 2) * (spacing / 2) | |
z = iz * spacing | |
w = iw * spacing | |
pt = (x, y, z, w) | |
point_index[(ix, iy, iz, iw)] = idx | |
points.append(pt) | |
idx += 1 | |
# 4D neighborhood (adjacent cells in 4D grid) | |
offsets = [ | |
(1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1), | |
(-1, 0, 0, 0), (0, -1, 0, 0), (0, 0, -1, 0), (0, 0, 0, -1), | |
] | |
for key, idx1 in point_index.items(): | |
for dx, dy, dz, dw in offsets: | |
neighbor = (key[0] + dx, key[1] + dy, key[2] + dz, key[3] + dw) | |
if neighbor in point_index: | |
idx2 = point_index[neighbor] | |
if idx1 < idx2: | |
edges.append((idx1, idx2)) | |
return np.array(points), edges | |
# Generate 4D honeycomb structure | |
points_4d, edges = generate_4d_honeycomb(grid_size=4) | |
# Project to 3D using PCA | |
pca = PCA(n_components=3) | |
points_3d = pca.fit_transform(points_4d) | |
# Plotting | |
fig = plt.figure(figsize=(10, 8), facecolor='black') | |
ax = fig.add_subplot(111, projection='3d', facecolor='black') | |
# Draw edges with white lines | |
for start_idx, end_idx in edges: | |
start, end = points_3d[start_idx], points_3d[end_idx] | |
ax.plot(*zip(start, end), color='white', linewidth=0.5) | |
# Equal aspect ratio | |
max_range = (points_3d.max(axis=0) - points_3d.min(axis=0)).max() / 2 | |
mid_coords = (points_3d.max(axis=0) + points_3d.min(axis=0)) / 2 | |
ax.set_xlim(mid_coords[0] - max_range, mid_coords[0] + max_range) | |
ax.set_ylim(mid_coords[1] - max_range, mid_coords[1] + max_range) | |
ax.set_zlim(mid_coords[2] - max_range, mid_coords[2] + max_range) | |
ax.axis('off') | |
ax.set_title("4D Honeycomb Projected to 3D", color='white') | |
plt.tight_layout() | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment