import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import RangeSlider
 
# Generate sample 4-dimensional data
np.random.seed(0)
n = 100
x = np.random.rand(n) * 2 - 1
y = np.random.rand(n) * 2 - 1
z = np.random.rand(n) * 2 - 1
t = np.random.rand(n) * 2 - 1
 
# Sort the data based on the values of t
sort_indices = np.argsort(t)
x = x[sort_indices]
y = y[sort_indices]
z = z[sort_indices]
t = t[sort_indices]
 
# Set the initial range of t
t_min, t_max = -0.5, 0.5
 
# Function to filter data points within the range of a 4-dimensional hypersphere and calculate transparency
def filter_points(t_min, t_max):
    distances = np.sqrt(x**2 + y**2 + z**2 + t**2)
    mask = (distances <= 1) & (t >= t_min) & (t <= t_max)
    alpha = 1 - np.abs(t[mask] - (t_min + t_max) / 2) / (t_max - t_min)
    return x[mask], y[mask], z[mask], t[mask], alpha
 
# Function to update the transparency of data points within the range of t
def update_points(val):
    t_min, t_max = val
    filtered_x, filtered_y, filtered_z, filtered_t, alpha = filter_points(t_min, t_max)
    ax.clear()
    ax.scatter(filtered_x, filtered_y, filtered_z, c=filtered_t, cmap='viridis', alpha=alpha)
    ax.plot(filtered_x, filtered_y, filtered_z, 'gray', alpha=0.3)
    ax.set_xlim(-1, 1)
    ax.set_ylim(-1, 1)
    ax.set_zlim(-1, 1)
    fig.canvas.draw_idle()
 
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
filtered_x, filtered_y, filtered_z, filtered_t, alpha = filter_points(t_min, t_max)
ax.scatter(filtered_x, filtered_y, filtered_z, c=filtered_t, cmap='viridis', alpha=alpha)
ax.plot(filtered_x, filtered_y, filtered_z, 'gray', alpha=0.3)
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_zlim(-1, 1)
 
# Add a RangeSlider to adjust the range of t
slider_ax = plt.axes([0.2, 0.02, 0.6, 0.03])
slider = RangeSlider(slider_ax, 't', -1, 1, valinit=(t_min, t_max))
slider.on_changed(update_points)
 
plt.show()