""" t-SNE Explorer - Streamlit Application with MCP Server A transparent t-SNE implementation with synthetic data generation and file upload support This version provides: 1. Streamlit UI for web browser access 2. MCP server endpoints for android.py to connect remotely Android clients can connect to this Hugging Face deployment as their MCP computation server. """ import os import sys import json import warnings import numpy as np import pandas as pd import streamlit as st import plotly.graph_objects as go from io import BytesIO from PIL import Image from pathlib import Path # Suppress warnings warnings.filterwarnings('ignore') os.environ['PYTHONWARNINGS'] = 'ignore' try: from sklearn.manifold import TSNE as SklearnTSNE from sklearn.datasets import fetch_openml except Exception: SklearnTSNE = None fetch_openml = None # ==================== Styling ==================== def inject_custom_css(): """Inject custom CSS from web/style.css to match the original design""" st.markdown(""" """, unsafe_allow_html=True) # ==================== TSNEExplorer Backend Class (MCP-Ready) ==================== class TSNEExplorer: """ Backend API for t-SNE computations. This class is MCP-ready - all methods return JSON-serializable data and can be called directly (Streamlit) or via API endpoints (future Android app). """ def __init__(self): pass # ==================== Synthetic Data Generation ==================== def generate_simplex_points(self, n, d, k, seed=42): """Generate n points in d dimensions with k distinct distance types""" np.random.seed(seed) # Validate inputs max_distances = (n * (n - 1)) // 2 if k > max_distances: return { 'success': False, 'error': f'Cannot create {k} distinct distances with only {n} points. ' f'Maximum possible is {max_distances} distinct distances.' } if k < 1: return { 'success': False, 'error': f'k must be at least 1 (you specified k={k}).' } # Special case: k=1 if k == 1: if n > d + 1: return { 'success': False, 'error': f'For k=1 (equidistant points), maximum n is {d+1} in {d}D.' } X = self._generate_regular_simplex(n, d) else: X = self._generate_k_distance_set(n, d, k, seed) # Compute pairwise distances distances = self._compute_pairwise_distances(X) unique_distances = np.unique(np.round(distances[distances > 0], decimals=6)) return { 'success': True, 'points': X.tolist(), 'n': n, 'd': d, 'k': k, 'actual_k': len(unique_distances), 'unique_distances': unique_distances.tolist(), 'distances_min': float(np.min(distances[distances > 0])) if n > 1 else 0, 'distances_mean': float(np.mean(distances[distances > 0])) if n > 1 else 0, 'distances_max': float(np.max(distances)), } def _generate_regular_simplex(self, n, d): """Generate regular n-simplex with equal pairwise distances""" if n == 1: return np.zeros((1, d)) if n == 2: X = np.zeros((2, d)) X[0, 0] = -0.5 X[1, 0] = 0.5 return X vertices = np.eye(n) vertices = vertices - np.mean(vertices, axis=0) vertices = vertices / np.sqrt(2) if d >= n - 1: X = vertices[:, :min(d, n)] if d > n: X = np.pad(X, ((0, 0), (0, d - n)), 'constant') else: X = vertices[:, :d] return X def _generate_k_distance_set(self, n, d, k, seed): """Generate points aiming for k distinct pairwise distances""" np.random.seed(seed) if n <= 0 or d <= 0: return np.zeros((0, max(d, 0))) if n == 1: return np.zeros((1, d)) # Exact k=2 constructions if k == 2: if d >= 2 and n == 5: return self._regular_ngon(n=5, d=d) if n <= 2 * d: return self._cross_polytope(n=n, d=d) return self._optimize_k_distance_set(n=n, d=d, k=k, seed=seed) # Exact k>=3 constructions if k >= 3 and d >= k and k <= 12 and n <= (2 ** k): return self._k_cube_k_distance_set(n=n, d=d, k=k) if k == 3 and d >= 2 and n in (6, 7): return self._regular_ngon(n=n, d=d) return self._optimize_k_distance_set(n=n, d=d, k=k, seed=seed) def _regular_ngon(self, n, d): """Regular n-gon in 2D""" X = np.zeros((n, d)) if d < 2: return X angles = np.linspace(0, 2 * np.pi, n + 1)[:-1] X[:, 0] = np.cos(angles) X[:, 1] = np.sin(angles) return X def _cross_polytope(self, n, d): """Cross polytope vertices""" X = np.zeros((n, d)) if n == 1: return X point_idx = 0 for i in range(d): if point_idx >= n: break X[point_idx, i] = 1.0 point_idx += 1 if point_idx >= n: break X[point_idx, i] = -1.0 point_idx += 1 return X def _k_cube_k_distance_set(self, n, d, k): """k-dimensional hypercube vertices""" vertices = [] seen = set() origin = tuple([0] * k) vertices.append(origin) seen.add(origin) for weight in range(1, k + 1): if len(vertices) >= n: break v = tuple([1] * weight + [0] * (k - weight)) if v not in seen: vertices.append(v) seen.add(v) for mask in range(1, 2 ** k): if len(vertices) >= n: break v = tuple((mask >> bit) & 1 for bit in range(k)) if v in seen: continue vertices.append(v) seen.add(v) Xk = np.array(vertices[:n], dtype=float) X = np.zeros((n, d), dtype=float) X[:, :k] = Xk X = X - X.mean(axis=0, keepdims=True) return X def _optimize_k_distance_set(self, n, d, k, seed, n_iter=2000, lr=0.02): """Heuristic optimization for k distances""" rng = np.random.default_rng(seed) X = rng.standard_normal((n, d)) * 0.1 if n < 2: return X D0 = self._compute_pairwise_distances(X) upper = D0[np.triu_indices(n, k=1)] if upper.size == 0: return X r_min = float(np.percentile(upper, 10)) r_max = float(np.percentile(upper, 90)) if r_max <= 1e-8: r_max = 1.0 radii = np.linspace(max(r_min, 1e-3), max(r_max, 1e-3), k) use_minibatch = n > 150 batch_size = min(5000, (n * (n - 1)) // 2) if use_minibatch else 0 ema = 0.15 for _ in range(n_iter): if use_minibatch: ii = rng.integers(0, n, size=batch_size) jj = rng.integers(0, n, size=batch_size) mask = ii != jj if not np.any(mask): continue ii = ii[mask] jj = jj[mask] diff = X[ii] - X[jj] dist = np.sqrt(np.sum(diff * diff, axis=1)) dist_safe = np.maximum(dist, 1e-12) assign = np.argmin(np.abs(dist[:, np.newaxis] - radii[np.newaxis, :]), axis=1) target = radii[assign] for m in range(k): m_mask = assign == m if np.any(m_mask): radii[m] = (1 - ema) * radii[m] + ema * float(np.mean(dist[m_mask])) err = dist_safe - target coef = (2.0 * err / dist_safe)[:, np.newaxis] grad_pairs = coef * diff grad = np.zeros_like(X) np.add.at(grad, ii, grad_pairs) np.add.at(grad, jj, -grad_pairs) else: D = self._compute_pairwise_distances(X) iu, ju = np.triu_indices(n, k=1) dist = D[iu, ju] dist_safe = np.maximum(dist, 1e-12) assign = np.argmin(np.abs(dist[:, np.newaxis] - radii[np.newaxis, :]), axis=1) target = radii[assign] for m in range(k): m_mask = assign == m if np.any(m_mask): radii[m] = float(np.mean(dist[m_mask])) err = dist_safe - target coef = (2.0 * err / dist_safe)[:, np.newaxis] diff = X[iu] - X[ju] grad_pairs = coef * diff grad = np.zeros_like(X) np.add.at(grad, iu, grad_pairs) np.add.at(grad, ju, -grad_pairs) grad += 1e-3 * X X = X - lr * grad X = X - X.mean(axis=0, keepdims=True) return X def _compute_pairwise_distances(self, X): """Compute pairwise Euclidean distances""" n = X.shape[0] distances = np.zeros((n, n)) for i in range(n): for j in range(i+1, n): dist = np.linalg.norm(X[i] - X[j]) distances[i, j] = dist distances[j, i] = dist return distances # ==================== MNIST Dataset ==================== def load_mnist(self, max_samples=1000, subset='train'): """Load MNIST dataset""" try: if fetch_openml is None: return {'success': False, 'error': 'scikit-learn not available'} mnist = fetch_openml('mnist_784', version=1, as_frame=False, parser='auto') all_images = np.array(mnist.data, dtype=np.float32) if isinstance(mnist.target[0], str): all_labels = np.array([int(label) for label in mnist.target], dtype=np.int32) else: all_labels = np.array(mnist.target, dtype=np.int32) if subset == 'train': images_flat = all_images[:60000] labels = all_labels[:60000] else: images_flat = all_images[60000:] labels = all_labels[60000:] if max_samples > 0 and max_samples < len(images_flat): images_flat = images_flat[:max_samples] labels = labels[:max_samples] X = images_flat / 255.0 return { 'success': True, 'X': X, 'labels': labels, 'count': len(images_flat), 'shape': X.shape, 'message': f'Loaded {len(images_flat)} MNIST {subset} samples' } except Exception as e: return {'success': False, 'error': str(e)} # ==================== t-SNE Implementation ==================== def run_tsne(self, X, perplexity=30, learning_rate=200, n_iter=1000, early_exaggeration=12, momentum=0.8, seed=42, progress_callback=None): """Run t-SNE with transparent internals""" try: n, d = X.shape if n > 1000: return {'success': False, 'error': f'Dataset too large ({n} points). Please use n <= 1000.'} # Initialize Y np.random.seed(seed) Y = np.random.randn(n, 2) * 0.0001 # Compute P if progress_callback: progress_callback(0, 'Computing P matrix...') P = self._compute_P(X, perplexity) # Optimize if progress_callback: progress_callback(0, 'Starting t-SNE optimization...') Y, Q, C_history = self._optimize_tsne( P, Y, learning_rate, n_iter, early_exaggeration, momentum, progress_callback ) return { 'success': True, 'Y': Y, 'P': P, 'Q': Q, 'C_history': C_history, 'n': n } except Exception as e: return {'success': False, 'error': str(e)} def _compute_P(self, X, perplexity): """Compute pairwise affinities P_ij""" n = X.shape[0] sum_X = np.sum(X**2, axis=1) D = sum_X[:, np.newaxis] + sum_X[np.newaxis, :] - 2 * X @ X.T D = np.maximum(D, 0) P = np.zeros((n, n)) target_entropy = np.log2(perplexity) for i in range(n): beta_min = -np.inf beta_max = np.inf beta = 1.0 for _ in range(50): Di = D[i].copy() Di[i] = 0 P_i = np.exp(-Di * beta) P_i[i] = 0 sum_P_i = np.sum(P_i) if sum_P_i == 0: P_i = np.ones(n) / n sum_P_i = 1.0 P_i = P_i / sum_P_i P_i_nonzero = P_i[P_i > 1e-12] H = -np.sum(P_i_nonzero * np.log2(P_i_nonzero)) H_diff = H - target_entropy if np.abs(H_diff) < 1e-5: break if H_diff > 0: beta_min = beta if beta_max == np.inf: beta = beta * 2 else: beta = (beta + beta_max) / 2 else: beta_max = beta if beta_min == -np.inf: beta = beta / 2 else: beta = (beta + beta_min) / 2 P[i] = P_i P = (P + P.T) / (2 * n) P = np.maximum(P, 1e-12) return P def _optimize_tsne(self, P, Y, learning_rate, n_iter, early_exaggeration, momentum, progress_callback=None): """Optimize t-SNE using gradient descent""" n = Y.shape[0] Y_velocity = np.zeros_like(Y) C_history = [] P_exag = P * early_exaggeration for iteration in range(n_iter): P_current = P_exag if iteration < 250 else P sum_Y = np.sum(Y**2, axis=1) D_low = sum_Y[:, np.newaxis] + sum_Y[np.newaxis, :] - 2 * Y @ Y.T D_low = np.maximum(D_low, 0) Q = (1 + D_low) ** (-1) np.fill_diagonal(Q, 0) sum_Q = np.sum(Q) if sum_Q < 1e-12: sum_Q = 1e-12 Q = Q / sum_Q Q = np.maximum(Q, 1e-12) C = np.sum(P_current * np.log((P_current + 1e-12) / (Q + 1e-12))) C_history.append(float(C)) PQ_diff = P_current - Q repulsion = (1 + D_low) ** (-1) attraction_repulsion = (PQ_diff * repulsion)[:, :, np.newaxis] Y_diff = Y[:, np.newaxis, :] - Y[np.newaxis, :, :] gradient = 4 * (attraction_repulsion * Y_diff).sum(axis=1) Y_velocity = momentum * Y_velocity - learning_rate * gradient Y = Y + Y_velocity Y = Y - Y.mean(axis=0) if progress_callback and iteration % 10 == 0: progress_callback(iteration / n_iter, f'Iteration {iteration}/{n_iter}, Cost: {C:.4f}') # Final Q computation sum_Y = np.sum(Y**2, axis=1) D_low = sum_Y[:, np.newaxis] + sum_Y[np.newaxis, :] - 2 * Y @ Y.T D_low = np.maximum(D_low, 0) Q = (1 + D_low) ** (-1) np.fill_diagonal(Q, 0) sum_Q = np.sum(Q) if sum_Q < 1e-12: sum_Q = 1e-12 Q = Q / sum_Q Q = np.maximum(Q, 1e-12) if progress_callback: progress_callback(1.0, 'Complete!') return Y, Q, C_history # ==================== Clustering ==================== def run_clustering(self, Y, method='kmeans', k=3, eps=0.5, min_samples=5): """Run clustering on t-SNE results""" try: if method == 'kmeans': labels = self._kmeans(Y, k) elif method == 'dbscan': labels = self._dbscan(Y, eps, min_samples) else: return {'success': False, 'error': 'Unknown clustering method'} unique_labels = np.unique(labels) summary = [] for label in unique_labels: count = np.sum(labels == label) summary.append({ 'label': int(label), 'count': int(count) }) return { 'success': True, 'labels': labels.tolist(), 'summary': summary } except Exception as e: return {'success': False, 'error': str(e)} def _kmeans(self, X, k, max_iter=100): """K-means clustering""" n = X.shape[0] indices = np.random.choice(n, k, replace=False) centroids = X[indices].copy() labels = np.zeros(n, dtype=int) for _ in range(max_iter): distances = np.zeros((n, k)) for i in range(k): distances[:, i] = np.sum((X - centroids[i])**2, axis=1) new_labels = np.argmin(distances, axis=1) if np.all(labels == new_labels): break labels = new_labels for i in range(k): cluster_points = X[labels == i] if len(cluster_points) > 0: centroids[i] = cluster_points.mean(axis=0) return labels def _dbscan(self, X, eps, min_samples): """DBSCAN clustering""" n = X.shape[0] labels = -np.ones(n, dtype=int) cluster_id = 0 for i in range(n): if labels[i] != -1: continue neighbors = self._find_neighbors(X, i, eps) if len(neighbors) < min_samples: labels[i] = -1 else: self._expand_cluster(X, labels, i, neighbors, cluster_id, eps, min_samples) cluster_id += 1 return labels def _find_neighbors(self, X, point_idx, eps): """Find neighbors within eps distance""" distances = np.sum((X - X[point_idx])**2, axis=1) return np.where(distances <= eps**2)[0] def _expand_cluster(self, X, labels, point_idx, neighbors, cluster_id, eps, min_samples): """Expand cluster from seed point""" labels[point_idx] = cluster_id i = 0 while i < len(neighbors): neighbor_idx = neighbors[i] if labels[neighbor_idx] == -1: labels[neighbor_idx] = cluster_id if labels[neighbor_idx] != -1: i += 1 continue labels[neighbor_idx] = cluster_id new_neighbors = self._find_neighbors(X, neighbor_idx, eps) if len(new_neighbors) >= min_samples: neighbors = np.concatenate([neighbors, new_neighbors]) i += 1 # ==================== Streamlit UI ==================== def main(): # Page config st.set_page_config( page_title="t-SNE Explorer", page_icon="๐", layout="wide", initial_sidebar_state="expanded" ) # Inject custom CSS inject_custom_css() # Header with MCP indicator st.markdown("""
Transparent t-SNE with synthetic data generation and file uploads
๐ง MCP Server Active - Android clients can connect!