Here's a thinking process that leads to the suggested HTML page:
-
Understand the User's Request:
- Topic: "Architect a vector compression lab exploring PQ, scalar quantization, and recall impacts."
- Role: Top-tier creative front-end engineer and UI/UX designer (Awwwards/CSS Design Awards level).
- Principles: Typography hierarchy, negative space, 60-30-10 color rule, Swiss/minimalist style with avant-garde digital interaction, narrative scroll.
- Triggers: Micro-interactions (magnetic buttons), non-linear layout, scroll-dependent storytelling (Lenis/Parallax), Bento Grids.
- Tech Stack: Tailwind CSS, GSAP/Framer Motion, advanced shaders/WebGL if needed (Three.js optional for texture/depth), SVG filters, Glassmorphism, Mesh Gradients.
- Constraint: Single self-contained HTML file, no external dependencies that break (must use CDNs), high visual impact, not a "template."
- Special Note: The "System" prompt warns against simplifications due to complexity, emphasizing high completion and visual impact. It also hints against "template" looks.
-
Conceptualization & Narrative (The "Lab" Metaphor):
- This is a technical deep dive into Vector Quantization (PQ - Product Quantization) and Scalar Quantization.
- Visual Metaphor: Compression as "Grinding/Cutting" raw vectors into smaller pieces. "Recall" as reconstruction accuracy.
- Theme: Dark mode (space/lab feel). Neon accents (Cyber Blue/Sunset Glow). Mesh gradients representing data flow.
- Structure:
- Hero: "The Vector Compression Lab". Interactive 3D noise/particles representing high-dimensional data. Title with large typography.
- Intro: What is compression? Theoretical intro.
- The Lab (Interactive Demo): The core experience. A visualization where users can adjust quantization bits (scalar) or codebook size (PQ) and see the effect on the vector (a shape/point cloud) and a "Recall Score" metric. This needs to be built with Canvas or SVG for performance.
- Comparison (Bento Grid): Cards explaining the trade-offs (Space vs. Time vs. Accuracy).
- Deep Dive (Parallax): Technical details scroll-triggered.
- Footer: Minimalist.
-
Technical Implementation Strategy:
- Styling: Tailwind CSS (via CDN). Custom config for colors (Dark background #050505, Accents: #00f0ff (Cyan), #ff0055 (Magenta).).
- Fonts: Google Fonts: 'Inter' (body), 'Space Grotesk' or 'Syncopate' (headings for that sci-fi/engineered feel).
- Animation: GSAP (via CDN) + ScrollTrigger. This is crucial for smooth narrative scroll.
- 3D/WebGL: Three.js (via CDN) for the Hero background. A swirling field of particles representing vectors. The user can move the mouse to rotate/perturb the field. This adds the "high-endedness" requested.
- Interaction (The Lab):
- Use HTML Canvas for a 2D visualization (simpler to integrate into DOM events than Three.js for precise UI controls, but still high performance).
- Visualize a 2D dataset (sine wave + noise).
- "Original" vs "Compressed" overlays.
- Sliders:
bits (1-8) and codebook_size (k).
- Real-time calculation of reconstruction error and "Recall" (approximation of recall = % of points within threshold of original).
- Visual Polish:
- Glassmorphism panels with backdrop-blur.
- Custom cursor? Maybe a subtle circle.
- Magnetic buttons in the UI.
- Mesh gradients using CSS
radial-gradient with animation.
-
Drafting the Code (Iterative Process):
- Setup: HTML5 boilerplate, Tailwind CDN, GSAP CDNs, Three.js CDN.
- Global Styles: Dark theme, custom font import,
::-webkit-scrollbar styling.
- Hero Section:
- Overlay Canvas
#webgl-bg.
- Content: Big Title "VECTOR COMPRESSION LAB".
- Subtitle: "Exploring the trade-offs of Product Quantization & Scalar Quantization".
- Scroll indicator (arrow).
- Three.js Background: Create a particle system (PointsMaterial). Add subtle rotation. Add mouse interaction (raycasting or simple mouse pos mapping). Use a "Tech Blue" color.
- Section 1: The Concept:
- Text block. "In high-dimensional spaces, storing raw vectors is expensive. We compress."
- Swirl/SVG graphics on the side.
- Section 2: The Interactive Lab (The Core):
- Layout: Split screen. Left: Controls (Sliders). Right: Visualization (Canvas).
- JS Logic:
- Generate random points in a spiral/gaussian pattern.
- Implement Scalar Quantization logic: Round values to nearest level depending on bits.
- Implement PQ logic (simulate): Split vector into sub-vectors, assign nearest centroid. To visualize, we'll simulate the "blocky" approximation.
- Render original points (dimmed). Render compressed points (bright).
- Update stats: "Avg Distance: X.XX", "Recall @ R=0.1: XX%".
- UI: Tailwind sliders (
range). Add event listeners.
- Section 3: Metrics (Bento Grid):
- Grid (Grid Col 2 or 3).
- Cards: "Space Efficiency", "Query Latency", "Approximation Quality".
- Icons (SVG).
- Hover effects: slight lift, glow.
- Section 4: Deep Dive:
- Parallax text. As you scroll, text layers move at different speeds.
- Code snippets inside glass bubbles (Monaco font look).
- Footer: Simple.
- Refinement & Polish:
- Lenis Scroll: Install Lenis (smooth scroll) to add that "weight" to the page.
- Typography: Massive scale.
text-6xl, leading-tight.
- Gradients: Add a fixed gradient orb in the background that blends using
mix-blend-mode.
- Animate elements on entry (fade up, blur out).
-
Refining the Code (Self-Correction during drafting):
- Critique: Is the Three.js background too heavy? Keep the particle count reasonable (2000-3000).
- Critique: The Lab demo needs to be understandable. Let's stick to 2D for the points to make the "quantization" effect visually obvious to a layperson (blockiness).
- Quantization implementation details:
- Scalar:
Math.floor(value * (2^bits - 1)) / (2^bits - 1).
- PQ: We'll fake it for visualization by reducing precision vertically vs horizontally or using a grid approach. Actually, to show PQ effectively in 2D, we can partition the space into clusters. PQ = train codebooks + encode. For the demo, just clustering the points into
k groups (k-means) and representing each point by the centroid color. This visually looks like color-based compression. That's easier to grasp than XOR residuals.
- Let's offer a toggle: "Scalar" (bit depth) vs "PQ" (codebook size). Actually, simpler: Two sliders. "Scalar Bit Depth" and "PQ Cluster Count". The visual updates show the "compression error" as an offset vector (lines connecting original to compressed) or color shift. Decision: Visualize original as white ghost points. Compressed as colored points. The offset distance determines color/intensity. This creates a beautiful effect.
- Recalls Calculate:
- Define a radius threshold (e.g., 0.05). Count points where distance(original, compressed) < threshold. That's "Recall".
-
Writing the actual code (Mental Check of the output):
- HTML Structure: Header, Sections, Scripts.
- Tailwind classes:
bg-[#050505], text-white, mix-blend-difference, backdrop-blur-md.
- Scripts: Need to load modules correctly.
- Three.js: Use
THREE.BufferGeometry, PointsMaterial, AdditiveBlending for glow.
-
Final Polish (The "Wow" Factor):
- Add a custom cursor that blends with the background (
mix-blend-mode: exclusion).
- Add a noise grain overlay (CSS
url('data:image/svg...') ) to reduce banding and add texture.
- Ensure the "Lab" UI looks like a sci-fi HUD (thin borders, monospace numbers).
- Verify GSAP animations are trigger-based not just time-based.
-
Output Generation: Assemble the code into the final single HTML file. (The resulting code will be long, but highly structured).
(Self-Correction during coding): I initially thought about k-means, but k-means is heavy to run in JS every frame for ~2000 points. I'll pre-calculate centroids for different k values or use a simpler grid for PQ visualization (simulating coarse codebooks). Actually, let's keep it simple but effective: The point color indicates compression quality. Blue = high quality, Red = low quality. Scalar quantization increases "banding" visually - the points snap to grid lines. PQ will cluster points into specific color zones. This is intuitive.
Let's refine the "Recall" calculation: It's a dynamic number that updates as sliders move.
Key visual elements to ensure:
- Hero: Three.js vortex.
- Typography: Huge, 'Syncopate' or 'Space Grotesk'.
- Color: Dark, Cyan/Magenta accents.
- Lab: Glassmorphism panel, canvas showing points, sliders with custom tracks.
-
Final Code Structure:
<!DOCTYPE html>
<head>: Styles, CDNs (Tailwind, GSAP, Three.js, Lenis, Google Fonts).
<body>:
cursor-custom
noise-overlay
canvas#webgl-bg
main container:
hero
intro
lab-container
bento-grid
parallax-section
footer
script tag with all logic.
-
Execute Code Generation. (Proceeds to generate the actual response).
(Final check of constraints): Single file? Yes. No JS file links? Yes. Tailwind? Yes. High visual impact? Yes. Topic matches? Yes.
Let's write.
Here is the complete, single-file HTML solution for the Vector Compression Lab.
This page integrates Three.js for the immersive background, GSAP for scroll storytelling, Tailwind CSS for styling, and a custom interactive Canvas-based lab to demonstrate the physics of vector quantization.
It features a "Swiss design" layout with aggressive typography, noise texture overlay, glassmorphism, and a reactive particle field.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vector Compression Lab</title>
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&family=Space+Grotesk:wght@300;500;700&display=swap" rel="stylesheet">
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
void: '#050505',
cyber: '#00f0ff',
neon: '#ff0055',
glass: 'rgba(255, 255, 255, 0.05)',
glassBorder: 'rgba(255, 255, 255, 0.1)'
},
fontFamily: {
sans: ['Inter', 'sans-serif'],
display: ['Space Grotesk', 'sans-serif'],
mono: ['Courier New', 'monospace']
},
backgroundImage: {
'gradient-radial': 'radial-gradient(var(--tw-gradient-stops))',
}
}
}
}
</script>
<!-- GSAP -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
<!-- Lenis Smooth Scroll -->
<script src="https://cdn.jsdelivr.net/gh/studio-freight/lenis@1.0.29/bundled/lenis.min.js"></script>
<!-- Three.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<!-- Noise Texture Overlay -->
<style>
/* Base Styles */
body {
background-color: #050505;
color: #ffffff;
overflow-x: hidden;
cursor: none; /* Custom cursor */
}
.font-display { font-family: 'Space Grotesk', sans-serif; }
/* Noise Grain */
.noise-overlay {
position: fixed;
top: 0; left: 0; width: 100%; height: 100%;
pointer-events: none;
z-index: 9998;
opacity: 0.05;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)' opacity='1'/%3E%3C/svg%3E");
}
/* Custom Cursor */
.cursor-dot,
.cursor-outline {
position: fixed;
top: 0; left: 0;
transform: translate(-50%, -50%);
border-radius: 50%;
z-index: 9999;
pointer-events: none;
}
.cursor-dot {
width: 8px; height: 8px;
background-color: #00f0ff;
}
.cursor-outline {
width: 40px; height: 40px;
border: 1px solid rgba(255, 255, 255, 0.5);
transition: width 0.2s, height 0.2s, background-color 0.2s;
}
body:hover .cursor-outline.hovered {
width: 60px;
height: 60px;
background-color: rgba(0, 240, 255, 0.1);
border-color: #00f0ff;
mix-blend-mode: exclusion;
}
/* Glassmorphism Panel */
.glass-panel {
background: rgba(20, 20, 20, 0.4);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255, 255, 255, 0.08);
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
}
/* Range Slider Styling */
input[type=range] {
-webkit-appearance: none;
width: 100%;
background: transparent;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
height: 20px;
width: 20px;
border-radius: 50%;
background: #00f0ff;
cursor: pointer;
margin-top: -8px;
box-shadow: 0 0 10px #00f0ff;
}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 4px;
cursor: pointer;
background: rgba(255,255,255,0.2);
border-radius: 2px;
}
/* Text Utilities */
.text-gradient {
background: linear-gradient(to right, #00f0ff, #ff0055);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
/* Parallax */
.parallax-wrap {
overflow: hidden;
}
.parallax-element {
will-change: transform;
}
</style>
</head>
<body>
<!-- Noise Overlay -->
<div class="noise-overlay"></div>
<!-- Custom Cursor -->
<div class="cursor-dot"></div>
<div class="cursor-outline"></div>
<!-- WebGL Background -->
<canvas id="webgl-bg" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1;"></canvas>
<!-- Content -->
<main class="relative z-10">
<!-- Hero Section -->
<section class="h-screen flex flex-col justify-center items-center text-center px-4 relative">
<div class="max-w-5xl mx-auto">
<p class="text-cyber tracking-[0.2em] text-sm md:text-base mb-6 uppercase animate-fade-in font-mono">A Research Initiative</p>
<h1 class="text-5xl md:text-8xl font-display font-bold leading-tight mb-8 mix-blend-difference">
VECTOR<br><span class="text-gradient">COMPRESSION</span><br>LAB
</h1>
<p class="text-gray-400 text-lg md:text-2xl max-w-2xl mx-auto font-light leading-relaxed">
Exploring the delicate balance between <span class="text-white font-semibold">memory footprint</span> and <span class="text-white font-semibold">approximation quality</span>. Dive into the mechanics of Scalar Quantization and Product Quantization.
</p>
</div>
<!-- Scroll Indicator -->
<div class="absolute bottom-10 left-1/2 transform -translate-x-1/2 flex flex-col items-center gap-2 opacity-70">
<span class="text-xs uppercase tracking-widest">Scroll</span>
<div class="w-[1px] h-12 bg-gradient-to-b from-cyber to-transparent"></div>
</div>
</section>
<!-- Intro Section -->
<section class="min-h-[80vh] py-24 px-4 md:px-20 flex flex-col md:flex-row items-center gap-16 relative">
<div class="w-full md:w-1/2">
<h2 class="text-4xl md:text-6xl font-display font-bold mb-8 parallax-element" data-speed="0.8">
The Art of<br>Dimensionality<br>Reduction
</h2>
<div class="space-y-6 text-gray-300 text-lg leading-relaxed font-light">
<p class="parallax-element" data-speed="1.0">
In a world of billion-vector datasets, raw storage is a luxury we cannot afford. High-dimensional embeddings, while powerful, consume vast amounts of memory and slow down nearest-neighbor searches.
</p>
<p class="parallax-element" data-speed="1.2">
<strong class="text-white">Scalar Quantization</strong> uniformly enforces levels on each dimension. Simple, but fast.
<br><strong class="text-white">Product Quantization (PQ)</strong> partitions the space and learns codebooks, grouping dimensions to capture correlation. Complex, but intricate.
</p>
</div>
</div>
<div class="w-full md:w-1/2 relative h-[400px] flex items-center justify-center">
<!-- Abstract Visual Decor -->
<div class="absolute w-64 h-64 bg-cyber/20 blur-[80px] rounded-full animate-pulse"></div>
<div class="absolute w-48 h-48 bg-neon/20 blur-[60px] rounded-full animate-pulse delay-1000"></div>
<div class="glass-panel p-8 rounded-3xl relative z-10 text-center max-w-sm">
<div class="text-5xl font-display font-bold text-white mb-2">256</div>
<div class="text-sm text-gray-400 uppercase tracking-widest">Original Dimensions</div>
<div class="my-4 flex items-center justify-center text-cyber text-2xl">→</div>
<div class="text-5xl font-display font-bold text-gradient mb-2">8 bits</div>
<div class="text-sm text-gray-400 uppercase tracking-widest">Final Footprint</div>
</div>
</div>
</section>
<!-- The Interactive Lab -->
<section id="lab" class="min-h-screen py-24 px-4 md:px-12 relative bg-[#080808] overflow-hidden">
<div class="max-w-7xl mx-auto">
<div class="flex flex-col md:flex-row justify-between items-end mb-12 border-b border-white/10 pb-6">
<div>
<h2 class="text-3xl md:text-5xl font-display font-bold">The Quantization Lab</h2>
<p class="mt-2 text-gray-500 text-sm">Interactive simulation of reconstruction error.</p>
</div>
<div class="glass-panel px-6 py-3 rounded-full mt-4 md:mt-0 font-mono text-cyber text-sm border border-cyber/30">
RECALL METRIC: <span id="recall-value">0.00%</span>
</div>
</div>
<!-- Lab UI Layout -->
<div class="grid grid-cols-1 lg:grid-cols-12 gap-8 h-[600px]">
<!-- Controls Column (Left) -->
<div class="lg:col-span-3 flex flex-col gap-8">
<!-- Scalar Control -->
<div class="glass-panel p-6 rounded-2xl">
<div class="flex justify-between items-center mb-4">
<label class="text-sm font-bold uppercase tracking-wider text-gray-300">Scalar Bits</label>
<span id="bits-display" class="font-mono text-cyber">8</span>
</div>
<input type="range" id="scalar-slider" min="1" max="8" step="1" value="8" class="w-full">
<p class="text-xs text-gray-500 mt-2">Uniform truncation of floating point precision.</p>
</div>
<!-- PQ Control -->
<div class="glass-panel p-6 rounded-2xl">
<div class="flex justify-between items-center mb-4">
<label class="text-sm font-bold uppercase tracking-wider text-gray-300">PQ Codebook Size</label>
<span id="k-display" class="font-mono text-neon">256</span>
</div>
<input type="range" id="pq-slider" min="2" max="256" step="1" value="256" class="w-full">
<p class="text-xs text-gray-500 mt-2">Number of cluster centroids per subspace.</p>
</div>
<!-- Stats Display -->
<div class="glass-panel p-6 rounded-2xl flex-1 flex flex-col justify-center">
<div class="space-y-4 font-mono text-sm">
<div class="flex justify-between border-b border-white/10 pb-2">
<span class="text-gray-400">Avg. Distortion</span>
<span id="distortion-val" class="text-white">0.00</span>
</div>
<div class="flex justify-between border-b border-white/10 pb-2">
<span class="text-gray-400">Dim Count</span>
<span class="text-white">2</span>
</div>
<div class="flex justify-between">
<span class="text-gray-400">Context</span>
<span class="text-cyber">Interactive</span>
</div>
</div>
</div>
</div>
<!-- Visualization Column (Right) -->
<div class="lg:col-span-9 relative bg-black/40 rounded-3xl border border-white/5 overflow-hidden shadow-2xl">
<canvas id="lab-canvas" class="absolute inset-0 w-full h-full"></canvas>
<!-- Legend -->
<div class="absolute bottom-6 right-6 flex gap-6 text-xs font-mono text-gray-400 pointer-events-none">
<div class="flex items-center gap-2">
<span class="w-3 h-3 bg-white rounded-full opacity-30 blur-[1px]"></span> Original
</div>
<div class="flex items-center gap-2">
<span class="w-3 h-3 bg-neon rounded-full shadow-[0_0_8px_rgba(255,0,85,0.8)]"></span> Compressed
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Bento Grid: The Trade-offs -->
<section class="py-24 px-4 md:px-12 bg-[#050505]">
<div class="max-w-7xl mx-auto">
<h2 class="text-3xl md:text-5xl font-display font-bold mb-16 text-center">
The <span class="text-neon">Trade-offs</span>
</h2>
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
<!-- Card 1 -->
<div class="glass-panel p-8 rounded-3xl hover:-translate-y-2 transition-transform duration-500 group">
<div class="w-14 h-14 rounded-full bg-white/5 flex items-center justify-center mb-6 group-hover:bg-cyber/20 transition-colors">
<svg class="w-8 h-8 text-cyber" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 4m-7-4l7 4"></path></svg>
</div>
<h3 class="text-xl font-bold mb-4">Compression Ratio</h3>
<p class="text-gray-400 font-light leading-relaxed">
The reduction in bit-width directly impacts storage costs. PQ offers near 10x-20x reduction through structured codebooks.
</p>
</div>
<!-- Card 2 -->
<div class="glass-panel p-8 rounded-3xl hover:-translate-y-2 transition-transform duration-500 group">
<div class="w-14 h-14 rounded-full bg-white/5 flex items-center justify-center mb-6 group-hover:bg-neon/20 transition-colors">
<svg class="w-8 h-8 text-neon" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
</div>
<h3 class="text-xl font-bold mb-4">Query Latency</h3>
<p class="text-gray-400 font-light leading-relaxed">
Lower precision means SIMD operations run faster. PQ requires table lookups but avoids expensive distance calculations on raw floats.
</p>
</div>
<!-- Card 3 -->
<div class="glass-panel p-8 rounded-3xl hover:-translate-y-2 transition-transform duration-500 group">
<div class="w-14 h-14 rounded-full bg-white/5 flex items-center justify-center mb-6 group-hover:bg-white transition-colors">
<svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
</div>
<h3 class="text-xl font-bold mb-4">Approximation Error</h3>
<p class="text-gray-400 font-light leading-relaxed">
Quality is non-linear. Scalar quantization degrades uniformly; PQ degrades gracefully as codebook size shrinks due to adaptive clustering.
</p>
</div>
</div>
</div>
</section>
<!-- Parallax Deep Dive -->
<section class="parallax-wrap py-32 relative" id="deep-dive">
<!-- Background Text -->
<div class="absolute inset-0 flex items-center justify-center pointer-events-none z-0">
<h1 class="text-[20vw] font-display font-bold text-white/5 uppercase whitespace-nowrap select-none">
Mathematics
</h1>
</div>
<div class="max-w-4xl mx-auto px-6 relative z-10">
<div class="glass-panel p-10 md:p-16 rounded-3xl border border-white/10 bg-gradient-to-br from-black/60 to-black/40">
<h2 class="text-3xl font-display font-bold text-cyber mb-8">The Equations</h2>
<div class="space-y-12 font-mono text-sm md:text-base">
<!-- Scalar -->
<div>
<p class="text-gray-400 mb-2">Scalar Quantization (SQ)</p>
<div class="bg-black/50 p-4 rounded-lg border border-white/5 font-mono">
q(x) = round( x / Δ ) * Δ <br>
<span class="text-gray-500 text-xs">where Δ = (max - min) / (2^b - 1)</span>
</div>
</div>
<!-- PQ Substitute Explanation -->
<div>
<p class="text-gray-400 mb-2">Product Quantization (PQ)</p>
<div class="bg-black/50 p-4 rounded-lg border border-white/5 font-mono">
x = [x<sub>1</sub>, ..., x<sub>m</sub>]<br>
c* = argmin<sub>c∈C<sub>i</sub></sub> || x<sub>i</sub> - c ||<br>
<span class="text-gray-500 text-xs">Split vector into m sub-vectors, assign to nearest centroid in codebook C<sub>i</sub>.</span>
</div>
</div>
<!-- Recall -->
<div>
<p class="text-gray-400 mb-2">Recall (Ground Truth Neighbor)</p>
<div class="bg-black/50 p-4 rounded-lg border border-white/5 font-mono">
Recall@k = |{q ∈ Top-K(result)}| / k<br>
<span class="text-gray-500 text-xs">Percentage of true nearest neighbors retrieved within the k candidates.</span>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Footer -->
<footer class="py-12 border-t border-white/10 bg-black">
<div class="max-w-7xl mx-auto px-6 flex flex-col md:flex-row justify-between items-center text-sm text-gray-500 font-mono">
<div class="mb-4 md:mb-0">
© 2023 <span class="text-white">Vector Lab</span>. All rights reserved.
</div>
<div class="flex gap-8">
<a href="#" class="hover:text-cyber transition-colors">Research</a>
<a href="#" class="hover:text-cyber transition-colors">GitHub</a>
<a href="#" class="hover:text-neon transition-colors">Contact</a>
</div>
</div>
</footer>
</main>
<!-- JavaScript Implementation -->
<script>
/**
* 1. CURSOR & UI MICROINTERACTIONS
*/
const cursorDot = document.querySelector('.cursor-dot');
const cursorOutline = document.querySelector('.cursor-outline');
window.addEventListener('mousemove', (e) => {
const posX = e.clientX;
const posY = e.clientY;
// Dot moves instantly
cursorDot.style.left = `${posX}px`;
cursorDot.style.top = `${posY}px`;
// Outline trails slightly (will update in animation loop or transition)
cursorOutline.animate({
left: `${posX}px`,
top: `${posY}px`
}, { duration: 500, fill: "forwards" });
});
// Hover states for interactive elements
const hoverables = document.querySelectorAll('a, button, input[type=range]');
hoverables.forEach(el => {
el.addEventListener('mouseenter', () => cursorOutline.classList.add('hovered'));
el.addEventListener('mouseleave', () => cursorOutline.classList.remove('hovered'));
});
/**
* 2. LENIS SMOOTH SCROLL
*/
const lenis = new Lenis({
duration: 1.2,
easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
smooth: true
});
function raf(time) {
lenis.raf(time);
requestAnimationFrame(raf);
}
requestAnimationFrame(raf);
/**
* 3. THREE.JS BACKGROUND (QUANTUM FLOW)
*/
const initThree = () => {
const canvas = document.getElementById('webgl-bg');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
const scene = new THREE.Scene();
// Fog for depth
scene.fog = new THREE.FogExp2(0x050505, 0.002);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 30;
// Particles
const particlesGeometry = new THREE.BufferGeometry();
const count = 3000;
const positions = new Float32Array(count * 3);
const colors = new Float32Array(count * 3);
const sizes = new Float32Array(count);
for(let i = 0; i < count; i++) {
// Spiral distribution
const i3 = i * 3;
const radius = Math.random() * 50;
const spin = radius * 2;
const theta = Math.random() * Math.PI * 2 + spin;
positions[i3] = Math.cos(theta) * radius;
positions[i3+1] = Math.sin(theta) * radius;
positions[i3+2] = (Math.random() - 0.5) * 50;
// Color gradient between Cyan and Neon
const mixRatio = Math.random();
colors[i3] = 0 * (1-mixRatio) + 1 * mixRatio; // R
colors[i3+1] = 0.94 * (1-mixRatio) + 0 * mixRatio; // G
colors[i3+2] = 1 * (1-mixRatio) + 0.33 * mixRatio; // B
sizes[i] = Math.random() * 2;
}
particlesGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
particlesGeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
particlesGeometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));
// Custom material to make soft dots
const material = new THREE.PointsMaterial({
size: 0.2,
transparent: true,
opacity: 0.8,
vertexColors: true,
blending: THREE.AdditiveBlending,
sizeAttenuation: true
});
const particleSystem = new THREE.Points(particlesGeometry, material);
scene.add(particleSystem);
// Mouse interaction variables
let mouseX = 0;
let mouseY = 0;
let targetRotationX = 0;
let targetRotationY = 0;
document.addEventListener('mousemove', (e) => {
mouseX = (e.clientX / window.innerWidth) - 0.5;
mouseY = (e.clientY / window.innerHeight) - 0.5;
});
// Animation Loop
const clock = new THREE.Clock();
const animate = () => {
const elapsedTime = clock.getElapsedTime();
// Gentle auto rotation
particleSystem.rotation.y = elapsedTime * 0.05;
particleSystem.rotation.x = mouseY * 0.5;
particleSystem.rotation.z += 0.001;
// Mouse parallax influence
targetRotationX = mouseX * 0.5;
targetRotationY = -mouseY * 0.5;
// Move camera slightly
camera.position.x += (mouseX * 5 - camera.position.x) * 0.05;
camera.position.y += (mouseY * 5 - camera.position.y) * 0.05;
camera.lookAt(scene.position);
renderer.render(scene, camera);
requestAnimationFrame(animate);
};
animate();
// Resize handler
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
};
/**
* 4. THE INTERACTIVE LAB (CANVAS)
*/
const initLab = () => {
const canvas = document.getElementById('lab-canvas');
const ctx = canvas.getContext('2d', { alpha: false });
let width, height;
const state = {
bits: 8,
kSize: 256,
pointsOriginal: [],
pointsCompressed: [],
dimensions: 2
};
// Generate synthetic data: a noisy spiral
function generateData(count = 2000) {
const points = [];
for (let i = 0; i < count; i++) {
const angle = 0.3 * i;
const radius = 5 + (i % 50) * 0.1;
const x = radius * Math.cos(angle);
const y = radius * Math.sin(angle);
// Add some noise
points.push({
x: x + (Math.random() - 0.5) * 1.5,
y: y + (Math.random() - 0.5) * 1.5,
val: (Math.sin(i * 0.05) + 1) / 2 // Extra value for scalar quantization demo
});
}
return points;
}
// Initialize
function resize() {
const rect = canvas.parentElement.getBoundingClientRect();
width = rect.width;
height = rect.height;
canvas.width = width;
canvas.height = height;
}
function computeScalarQuantization(points, bits) {
const levels = Math.pow(2, bits) - 1;
// Normalize coordinates roughly to 0-1 for quantization logic then rescale
// Assuming data spread around ~30x30, we map to range 0..1 based on min/max approx
const range = 30;
return points.map(p => {
const qx = Math.round(((p.x + range/2) / range) * levels) / levels * range - range/2;
const qy = Math.round(((p.y + range/2) / range) * levels) / levels * range - range/2;
return { x: qx, y: qy };
});
}
// Clustering for PQ (Simplified K-Means simulation)
function computePQ(points, k) {
if (k >= points.length) return points; // No compression
// Pre-calculate centroids using a simple grid method for visual approximation
// Real PQ would involve subspace splitting, but here we just cluster points
// to show the "blocky" effect and recall degradation.
// To keep it fast, we won't run full Lloyd's algorithm every frame for 2000 points.
// We will use a deterministic grid hash based on position.
// This simulates the "nearest codebook" effect visually.
const gridSize = Math.sqrt(k * 5); // approximate grid size
const cellW = 30 / gridSize;
const cellH = 30 / gridSize;
const offset = 15;
return points.map(p => {
// Find which grid cell this falls into (simulating nearest centroid)
const gx = Math.floor((p.x + offset) / cellW);
const gy = Math.floor((p.y + offset) / cellH);
// Centroid is cell center
const cx = gx * cellW + cellW/2 - offset;
const cy = gy * cellH + cellH/2 - offset;
return { x: cx, y: cy };
});
}
function computeRecall(original, compressed, threshold = 1.0) {
let matches = 0;
for(let i=0; i<original.length; i++) {
const dx = original[i].x - compressed[i].x;
const dy = original[i].y - compressed[i].y;
if(dx*dx + dy*dy <= threshold*threshold) matches++;
}
return (matches / original.length) * 100;
}
function render() {
// Clear background
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, width, height);
// Coordinate mapper: Map world -15..15 to canvas coords
const map = (val, dim) => {
const scale = dim === 'x' ? width / 3 : height / 3;
const offset = dim === 'x' ? width / 2 : height / 2;
return val * scale + offset;
};
// Draw compressed points (Foreground)
ctx.fillStyle = '#ff0055'; // Neon
state.pointsCompressed.forEach(p => {
ctx.fillRect(map(p.x, 'x') - 1.5, map(p.y, 'y') - 1.5, 3, 3);
});
// Draw original points (Ghost background)
ctx.fillStyle = 'rgba(255,255,255,0.15)';
state.pointsOriginal.forEach(p => {
ctx.beginPath();
ctx.arc(map(p.x, 'x'), map(p.y, 'y'), 1.2, 0, Math.PI * 2);
ctx.fill();
});
// Draw connecting lines for distortion (if not too many points)
// Optional: Draw outliers
}
// Update Logic
function update() {
const bits = state.bits;
const k = state.kSize;
// 1. Get Compressed
let compressed;
if (bits < 8) {
compressed = computeScalarQuantization(state.pointsOriginal, bits);
} else {
// Max bits -> effectively no scalar compression, show PQ effect
// We simulate PQ by using the K slider value essentially
compressed = computePQ(state.pointsOriginal, k);
}
state.pointsCompressed = compressed;
// 2. Compute Metrics
const distortion = compressed.reduce((sum, p, i) => {
const op = state.pointsOriginal[i];
return sum + Math.sqrt(Math.pow(op.x - p.x, 2) + Math.pow(op.y - p.y, 2));
}, 0) / compressed.length;
const recall = computeRecall(state.pointsOriginal, compressed, 1.5);
// 3. Update DOM
document.getElementById('distortion-val').textContent = distortion.toFixed(3);
document.getElementById('recall-value').textContent = recall.toFixed(2) + '%';
// 4. Render
render();
}
// Event Listeners
const scalarSlider = document.getElementById('scalar-slider');
const bitsDisplay = document.getElementById('bits-display');
scalarSlider.addEventListener('input', (e) => {
state.bits = parseInt(e.target.value);
bitsDisplay.textContent = state.bits;
// Reduce k to avoid visual conflict? Or separate modes?
// We'll keep them both active: scalar applies to val, PQ applies to k.
// Visual hybrid: if bits<8, we show scalar quantization; else we show PQ.
update();
});
const pqSlider = document.getElementById('pq-slider');
const kDisplay = document.getElementById('k-display');
pqSlider.addEventListener('input', (e) => {
state.kSize = parseInt(e.target.value);
kDisplay.textContent = state.kSize;
update();
});
// Init
state.pointsOriginal = generateData();
resize();
update(); // First render
window.addEventListener('resize', () => {
resize();
render();
});
// Animation Loop for smooth visuals if needed, but static redraw on event is fine for this
};
/**
* 5. GSAP SCROLL ANIMATIONS & PARALLAX
*/
const initAnimations = () => {
gsap.registerPlugin(ScrollTrigger);
// Fade in Hero
gsap.from("section:first-child h1", {
duration: 1.5,
y: 100,
opacity: 0,
ease: "power4.out",
delay: 0.2
});
gsap.from("section:first-child p", {
duration: 1.5,
y: 50,
opacity: 0,
ease: "power4.out",
delay: 0.5
});
// Parallax Elements in Intro
document.querySelectorAll('.parallax-element').forEach(el => {
const speed = parseFloat(el.getAttribute('data-speed') || 1);
gsap.to(el, {
scrollTrigger: {
trigger: el,
start: "top bottom",
end: "bottom top",
scrub: true
},
yPercent: -20 * speed,
ease: "none"
});
});
// Reveal Sections
gsap.utils.toArray("section").forEach(section => {
if(section.id !== 'hero' && section.id !== 'deep-dive') {
gsap.from(section, {
scrollTrigger: {
trigger: section,
start: "top 80%",
},
y: 50,
opacity: 0,
duration: 1,
ease: "power3.out"
});
}
});
// Deep Dive Parallax Background Text
gsap.to("#deep-dive .absolute h1", {
scrollTrigger: {
trigger: "#deep-dive",
start: "top bottom",
end: "bottom top",
scrub: 1
},
y: -150,
ease: "none"
});
// Lab specific entrance
gsap.from(".glass-panel", {
scrollTrigger: {
trigger: "#lab",
start: "top 70%",
},
y: 30,
opacity: 0,
duration: 0.8,
stagger: 0.1,
ease: "power2.out"
});
};
/**
* BOOTSTRAP
*/
window.onload = () => {
initThree();
initLab();
initAnimations();
};
</script>
</body>
</html>