Build a gravitational wave counterpart search: tiling, prioritization, and…
- User
Build a gravitational wave counterpart search: tiling, prioritization, and multi-messenger follow-up.
Assistant
Build a gravitational wave counterpart search: tiling, prioritization, and multi-messenger follow-up.
The user wants me to build a "gravitational wave counterpart search" system. This is a complex topic in astrophysics that involves:
Gravitational Wave Detection: When LIGO/Virgo detect a gravitational wave event (like a binary neutron star merger), they localize it to a region of the sky (the "localization skymap").
Tiling: The sky region is typically too large to observe all at once with optical telescopes. We need to break it up into smaller "tiles" that individual telescope pointings can cover.
Prioritization: Not all tiles are equally likely to contain the source. We need to prioritize based on:
Multi-messenger Follow-up: Coordinated observations across:
Let me design a comprehensive simulation:
Key Components:
Skymap Generation: Create a realistic 3D skymap (RA, Dec, distance) with probability density
Tiling Algorithm:
Prioritization Engine:
Multi-messenger Visualization:
Interactive Controls:
Let me create an impressive, scientifically accurate visualization:
Visual Design:
Technical Implementation:
Let me code this up properly with good structure and visual appeal. This is a fascinating project! I'll build an interactive gravitational wave counterpart search system with realistic skymap localization, tiling algorithms, prioritization based on probability and observability, and multi-messenger coordination.
This is a complete Gravitational Wave Counterpart Search System that simulates the real workflow astronomers use when LIGO/Virgo detect a merger event.
1. Skymap Visualization
2. Tiling System
3. Observatory Management
4. Search Simulation
5. Multi-Messenger Timeline
6. Galaxy Catalog
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GW Counterpart Search System</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;700&family=Space+Grotesk:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0a0e14;
--bg-panel: #0f1419;
--fg: #e6e6e6;
--muted: #5c6773;
--accent: #00d9ff;
--accent-dim: rgba(0, 217, 255, 0.15);
--warning: #ff9940;
--success: #7fef00;
--danger: #ff3366;
--border: #1f2937;
--card: #141a22;
}
* { box-sizing: border-box; }
body {
font-family: 'Space Grotesk', sans-serif;
background: var(--bg);
color: var(--fg);
margin: 0;
overflow-x: hidden;
}
.mono { font-family: 'JetBrains Mono', monospace; }
.panel {
background: var(--bg-panel);
border: 1px solid var(--border);
border-radius: 8px;
}
.glow-accent {
box-shadow: 0 0 20px rgba(0, 217, 255, 0.2), inset 0 1px 0 rgba(255,255,255,0.05);
}
.btn {
background: linear-gradient(135deg, var(--card), var(--bg-panel));
border: 1px solid var(--border);
color: var(--fg);
padding: 8px 16px;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s ease;
font-family: 'Space Grotesk', sans-serif;
font-weight: 500;
}
.btn:hover {
border-color: var(--accent);
background: linear-gradient(135deg, rgba(0,217,255,0.1), var(--bg-panel));
}
.btn:active { transform: scale(0.98); }
.btn-primary {
background: linear-gradient(135deg, var(--accent), #00a8c6);
color: var(--bg);
border: none;
}
.btn-primary:hover {
background: linear-gradient(135deg, #33e0ff, #00d9ff);
}
.tile-row {
transition: background 0.15s ease;
}
.tile-row:hover {
background: rgba(0, 217, 255, 0.05);
}
.progress-bar {
height: 6px;
background: var(--border);
border-radius: 3px;
overflow: hidden;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, var(--accent), var(--success));
transition: width 0.3s ease;
}
.stat-value {
font-size: 1.75rem;
font-weight: 700;
background: linear-gradient(135deg, var(--accent), #7fef00);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
canvas { display: block; }
.skymap-container {
position: relative;
background: radial-gradient(ellipse at center, #0f1822 0%, #0a0e14 100%);
border-radius: 8px;
overflow: hidden;
}
.telescope-badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.badge-optical { background: rgba(0, 217, 255, 0.2); color: var(--accent); }
.badge-radio { background: rgba(255, 153, 64, 0.2); color: var(--warning); }
.badge-xray { background: rgba(255, 51, 102, 0.2); color: var(--danger); }
.badge-neutrino { background: rgba(127, 239, 0, 0.2); color: var(--success); }
.pulse {
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.slide-in {
animation: slideIn 0.4s ease-out forwards;
}
@keyframes slideIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
@media (prefers-reduced-motion: reduce) {
.pulse, .slide-in { animation: none; }
.progress-fill { transition: none; }
}
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: var(--bg); }
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: var(--muted); }
</style>
</head>
<body class="min-h-screen">
<!-- Header -->
<header class="border-b border-[--border] bg-[--bg-panel] sticky top-0 z-50">
<div class="max-w-[1600px] mx-auto px-4 py-3 flex items-center justify-between">
<div class="flex items-center gap-4">
<div class="flex items-center gap-2">
<svg width="28" height="28" viewBox="0 0 28 28" fill="none">
<circle cx="14" cy="14" r="12" stroke="var(--accent)" stroke-width="1.5" opacity="0.3"/>
<path d="M14 6 Q20 14 14 22 Q8 14 14 6" stroke="var(--accent)" stroke-width="2" fill="none"/>
<circle cx="14" cy="14" r="3" fill="var(--accent)"/>
</svg>
<span class="text-lg font-semibold tracking-tight">GW Counterpart Search</span>
</div>
<div class="hidden sm:flex items-center gap-2 text-xs text-[--muted] mono">
<span class="w-2 h-2 rounded-full bg-[--success] pulse"></span>
<span>SYSTEM ACTIVE</span>
</div>
</div>
<div class="flex items-center gap-3">
<select id="eventSelect" class="btn mono text-sm">
<option value="GW170817">GW170817-like BNS</option>
<option value="GW190425">GW190425-like BNS</option>
<option value="GW190814">GW190814-like NSBH</option>
<option value="BBH">Generic BBH</option>
</select>
<button id="generateBtn" class="btn btn-primary text-sm">New Event</button>
</div>
</div>
</header>
<main class="max-w-[1600px] mx-auto p-4 grid grid-cols-1 lg:grid-cols-12 gap-4">
<!-- Left Panel: Event Info & Stats -->
<div class="lg:col-span-3 space-y-4">
<!-- Event Info -->
<div class="panel p-4 glow-accent">
<h2 class="text-sm font-semibold text-[--muted] uppercase tracking-wider mb-3">Event Information</h2>
<div class="space-y-3">
<div>
<div class="text-xs text-[--muted]">Event ID</div>
<div id="eventId" class="mono text-lg font-medium">S230615az</div>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<div class="text-xs text-[--muted]">Type</div>
<div id="eventType" class="font-medium text-[--accent]">BNS Merger</div>
</div>
<div>
<div class="text-xs text-[--muted]">FAR</div>
<div id="eventFar" class="mono">1/1e6 yr</div>
</div>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<div class="text-xs text-[--muted]">Distance</div>
<div id="eventDist" class="mono">40 ± 8 Mpc</div>
</div>
<div>
<div class="text-xs text-[--muted]">Trigger Time</div>
<div id="eventTime" class="mono text-sm">T+0:00:00</div>
</div>
</div>
</div>
</div>
<!-- Statistics -->
<div class="panel p-4">
<h2 class="text-sm font-semibold text-[--muted] uppercase tracking-wider mb-4">Search Statistics</h2>
<div class="grid grid-cols-2 gap-4">
<div>
<div class="text-xs text-[--muted] mb-1">Probability Covered</div>
<div id="probCovered" class="stat-value">0%</div>
<div class="progress-bar mt-2">
<div id="probBar" class="progress-fill" style="width: 0%"></div>
</div>
</div>
<div>
<div class="text-xs text-[--muted] mb-1">Tiles Observed</div>
<div id="tilesObserved" class="stat-value">0/0</div>
</div>
<div>
<div class="text-xs text-[--muted] mb-1">Candidates</div>
<div id="candidates" class="stat-value">0</div>
</div>
<div>
<div class="text-xs text-[--muted] mb-1">Active Telescopes</div>
<div id="activeTelescopes" class="stat-value">4</div>
</div>
</div>
</div>
<!-- Observatory Selector -->
<div class="panel p-4">
<h2 class="text-sm font-semibold text-[--muted] uppercase tracking-wider mb-3">Observatories</h2>
<div id="observatoryList" class="space-y-2"></div>
</div>
</div>
<!-- Center: Skymap -->
<div class="lg:col-span-6 space-y-4">
<div class="skymap-container panel">
<canvas id="skymapCanvas" width="800" height="500"></canvas>
<div class="absolute bottom-3 left-3 flex items-center gap-4 text-xs mono">
<div class="flex items-center gap-2">
<div class="w-3 h-3 rounded-sm" style="background: linear-gradient(135deg, #ff3366, #ff9940)"></div>
<span>90% Contour</span>
</div>
<div class="flex items-center gap-2">
<div class="w-3 h-3 rounded-sm" style="background: linear-gradient(135deg, #00d9ff, #7fef00)"></div>
<span>50% Contour</span>
</div>
</div>
<div class="absolute top-3 right-3 text-xs mono text-[--muted]">
<span id="coordsDisplay">RA: -- Dec: --</span>
</div>
</div>
<!-- Tiling Controls -->
<div class="panel p-4">
<div class="flex items-center justify-between mb-4">
<h2 class="text-sm font-semibold text-[--muted] uppercase tracking-wider">Tiling Strategy</h2>
<div class="flex gap-2">
<button id="greedyBtn" class="btn text-xs">Greedy Coverage</button>
<button id="balancedBtn" class="btn text-xs">Balanced</button>
<button id="galaxyBtn" class="btn btn-primary text-xs">Galaxy-Weighted</button>
</div>
</div>
<div class="grid grid-cols-3 gap-4 text-center">
<div>
<div class="text-2xl font-bold text-[--accent]" id="totalTiles">0</div>
<div class="text-xs text-[--muted]">Total Tiles</div>
</div>
<div>
<div class="text-2xl font-bold text-[--warning]" id="avgProb">0%</div>
<div class="text-xs text-[--muted]">Avg Probability</div>
</div>
<div>
<div class="text-2xl font-bold text-[--success]" id="estTime">0h</div>
<div class="text-xs text-[--muted]">Est. Coverage</div>
</div>
</div>
</div>
<!-- Multi-Messenger Timeline -->
<div class="panel p-4">
<h2 class="text-sm font-semibold text-[--muted] uppercase tracking-wider mb-4">Multi-Messenger Follow-up</h2>
<div id="timeline" class="relative pl-6 border-l-2 border-[--border] space-y-4"></div>
</div>
</div>
<!-- Right Panel: Tile Queue -->
<div class="lg:col-span-3 space-y-4">
<div class="panel overflow-hidden">
<div class="p-4 border-b border-[--border] flex items-center justify-between">
<h2 class="text-sm font-semibold text-[--muted] uppercase tracking-wider">Observation Queue</h2>
<button id="runSearchBtn" class="btn btn-primary text-xs">Run Search</button>
</div>
<div id="tileQueue" class="max-h-[400px] overflow-y-auto">
<!-- Tiles will be inserted here -->
</div>
</div>
<!-- Candidates Panel -->
<div class="panel overflow-hidden">
<div class="p-4 border-b border-[--border]">
<h2 class="text-sm font-semibold text-[--muted] uppercase tracking-wider">Candidate Alerts</h2>
</div>
<div id="candidatesList" class="p-4 max-h-[200px] overflow-y-auto">
<div class="text-sm text-[--muted] text-center py-4">No candidates yet</div>
</div>
</div>
<!-- Galaxy Catalog -->
<div class="panel p-4">
<h2 class="text-sm font-semibold text-[--muted] uppercase tracking-wider mb-3">Galaxy Catalog Cross-match</h2>
<div id="galaxyList" class="space-y-2 max-h-[150px] overflow-y-auto">
<!-- Galaxies will be inserted here -->
</div>
</div>
</div>
</main>
<script>
// ============================================
// GRAVITATIONAL WAVE COUNTERPART SEARCH SYSTEM
// ============================================
// State Management
const state = {
event: null,
tiles: [],
galaxies: [],
observatories: [],
observedTiles: new Set(),
candidates: [],
currentTime: 0,
isSearching: false,
tilingStrategy: 'galaxy',
mousePos: { x: 0, y: 0 },
hoveredTile: null,
animationFrame: null
};
// Observatory Data
const OBSERVATORIES = [
{ id: 'ztf', name: 'ZTF', type: 'optical', location: 'Palomar', fov: 47, latency: 0.5, magnitude: 20.5, lat: 33.35, lon: -116.86 },
{ id: 'lsst', name: 'LSST', type: 'optical', location: 'Chile', fov: 9.6, latency: 1, magnitude: 24.5, lat: -30.24, lon: -70.74 },
{ id: 'swift', name: 'Swift', type: 'xray', location: 'Space', fov: 0.4, latency: 0.1, magnitude: null, lat: 0, lon: 0 },
{ id: 'vla', name: 'VLA', type: 'radio', location: 'NM', fov: 1, latency: 2, magnitude: null, lat: 34.08, lon: -107.62 },
{ id: 'icecube', name: 'IceCube', type: 'neutrino', location: 'Antarctica', fov: 41253, latency: 0, magnitude: null, lat: -90, lon: 0 }
];
// Event Templates
const EVENT_TEMPLATES = {
'GW170817': { type: 'BNS Merger', dist: 40, distErr: 8, area90: 28, area50: 8, far: '1/1e6 yr', hasEM: true },
'GW190425': { type: 'BNS Merger', dist: 150, distErr: 50, area90: 8000, area50: 2500, far: '1/1e4 yr', hasEM: true },
'GW190814': { type: 'NSBH Merger', dist: 240, distErr: 40, area90: 20, area50: 5, far: '1/1e5 yr', hasEM: false },
'BBH': { type: 'BBH Merger', dist: 500, distErr: 150, area90: 500, area50: 150, far: '1/1e3 yr', hasEM: false }
};
// Generate realistic skymap probability distribution
function generateSkymap(template, width, height) {
const data = new Float32Array(width * height);
const ctx = { data, width, height };
// Create multiple Gaussian components
const numComponents = 2 + Math.floor(Math.random() * 3);
const components = [];
let centerRA = Math.PI * (0.3 + Math.random() * 0.4);
let centerDec = (Math.random() - 0.5) * Math.PI * 0.6;
for (let i = 0; i < numComponents; i++) {
components.push({
ra: centerRA + (Math.random() - 0.5) * 0.5,
dec: centerDec + (Math.random() - 0.5) * 0.3,
sigma: 0.05 + Math.random() * 0.15,
weight: 0.3 + Math.random() * 0.7
});
}
// Normalize weights
const totalWeight = components.reduce((s, c) => s + c.weight, 0);
components.forEach(c => c.weight /= totalWeight);
// Fill probability map (Mollweide projection approximation)
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const idx = y * width + x;
// Convert pixel to spherical coordinates
const ra = (x / width) * 2 * Math.PI;
const dec = Math.asin((y / height - 0.5) * 2);
let prob = 0;
for (const comp of components) {
const dRA = Math.abs(ra - comp.ra);
const dRA2 = Math.min(dRA, 2 * Math.PI - dRA);
const dDec = dec - comp.dec;
const dist2 = dRA2 * dRA2 + dDec * dDec;
prob += comp.weight * Math.exp(-dist2 / (2 * comp.sigma * comp.sigma));
}
data[idx] = prob;
}
}
return { data, width, height, components };
}
// Normalize skymap and find contours
function processSkymap(skymap) {
const { data, width, height } = skymap;
// Find max and normalize
let maxVal = 0;
for (let i = 0; i < data.length; i++) {
maxVal = Math.max(maxVal, data[i]);
}
if (maxVal > 0) {
for (let i = 0; i < data.length; i++) {
data[i] /= maxVal;
}
}
// Sort values for contour calculation
const sortedVals = Array.from(data).sort((a, b) => b - a);
// Find 50% and 90% contour thresholds
let cumProb = 0;
const threshold50 = { val: 0, found: false };
const threshold90 = { val: 0, found: false };
for (let i = 0; i < sortedVals.length; i++) {
cumProb += sortedVals[i];
if (!threshold50.found && cumProb >= 0.5 * sortedVals.length * sortedVals[0] * 0.5) {
threshold50.val = sortedVals[i];
threshold50.found = true;
}
if (!threshold90.found && cumProb >= 0.9 * sortedVals.length * sortedVals[0] * 0.5) {
threshold90.val = sortedVals[i];
threshold90.found = true;
break;
}
}
// Fallback if thresholds not found properly
if (!threshold50.found) threshold50.val = 0.3;
if (!threshold90.found) threshold90.val = 0.1;
return { ...skymap, threshold50: threshold50.val, threshold90: threshold90.val };
}
// Generate galaxy catalog within skymap region
function generateGalaxies(skymap, numGalaxies = 150) {
const galaxies = [];
const { components, width, height } = skymap;
for (let i = 0; i < numGalaxies; i++) {
// Bias towards high-probability regions
const comp = components[Math.floor(Math.random() * components.length)];
const ra = comp.ra + (Math.random() - 0.5) * comp.sigma * 4;
const dec = comp.dec + (Math.random() - 0.5) * comp.sigma * 4;
const galaxy = {
id: `GLX${String(i + 1).padStart(4, '0')}`,
ra: (ra * 180 / Math.PI + 360) % 360,
dec: dec * 180 / Math.PI,
distance: state.event.dist + (Math.random() - 0.5) * state.event.distErr * 2,
magnitude: 12 + Math.random() * 10,
type: ['Elliptical', 'Spiral', 'Irregular'][Math.floor(Math.random() * 3)],
probability: Math.random() // Placeholder, will be updated
};
// Calculate skymap probability at this position
const px = Math.floor((ra / (2 * Math.PI)) * width);
const py = Math.floor((Math.sin(dec) + 1) / 2 * height);
const idx = Math.max(0, Math.min(width * height - 1, py * width + px));
galaxy.probability = skymap.data[idx] || 0;
galaxies.push(galaxy);
}
// Sort by probability
galaxies.sort((a, b) => b.probability - a.probability);
return galaxies.slice(0, 50); // Keep top 50
}
// Generate observation tiles
function generateTiles(skymap, fov = 5, strategy = 'galaxy') {
const tiles = [];
const { width, height, data, threshold50, threshold90 } = skymap;
// Grid-based tiling
const tileSize = fov; // degrees
const raSteps = Math.ceil(360 / tileSize);
const decSteps = Math.ceil(180 / tileSize);
for (let i = 0; i < raSteps; i++) {
for (let j = 0; j < decSteps; j++) {
const ra = i * tileSize;
const dec = -90 + j * tileSize;
// Convert to radians for probability lookup
const raRad = ra * Math.PI / 180;
const decRad = dec * Math.PI / 180;
// Sample probability from skymap
const px = Math.floor((raRad / (2 * Math.PI)) * width);
const py = Math.floor((Math.sin(decRad) + 1) / 2 * height);
const idx = Math.max(0, Math.min(width * height - 1, py * width + px));
const probability = data[idx] || 0;
// Skip very low probability tiles
if (probability < 0.01) continue;
// Calculate galaxy weight
let galaxyWeight = 0;
const nearbyGalaxies = state.galaxies.filter(g => {
const dRA = Math.abs(g.ra - ra);
const dDec = Math.abs(g.dec - dec);
return Math.min(dRA, 360 - dRA) < tileSize && dDec < tileSize;
});
galaxyWeight = nearbyGalaxies.reduce((s, g) => s + g.probability * (1 / (g.magnitude + 1)), 0);
tiles.push({
id: `T${String(tiles.length + 1).padStart(3, '0')}`,
ra, dec,
size: tileSize,
probability,
galaxyWeight,
priority: 0,
status: 'pending', // pending, observing, observed
observatory: null,
observedAt: null,
nearbyGalaxies: nearbyGalaxies.length
});
}
}
return prioritizeTiles(tiles, strategy);
}
// Prioritize tiles based on strategy
function prioritizeTiles(tiles, strategy) {
tiles.forEach(tile => {
switch (strategy) {
case 'greedy':
tile.priority = tile.probability;
break;
case 'balanced':
tile.priority = tile.probability * 0.6 + tile.galaxyWeight * 0.4;
break;
case 'galaxy':
default:
tile.priority = tile.probability * 0.3 + tile.galaxyWeight * 0.7;
break;
}
});
return tiles.sort((a, b) => b.priority - a.priority);
}
// Calculate observability for an observatory
function calculateObservability(tiles, observatory) {
const now = new Date();
const lst = (now.getHours() * 15 + now.getMinutes() * 0.25) % 360; // Simplified LST
tiles.forEach(tile => {
// Simple altitude calculation
const ha = (lst - tile.ra + 360) % 360;
const haRad = ha * Math.PI / 180;
const decRad = tile.dec * Math.PI / 180;
const latRad = observatory.lat * Math.PI / 180;
const sinAlt = Math.sin(latRad) * Math.sin(decRad) +
Math.cos(latRad) * Math.cos(decRad) * Math.cos(haRad);
const altitude = Math.asin(sinAlt) * 180 / Math.PI;
tile.altitude = altitude;
tile.airmass = altitude > 0 ? 1 / Math.sin(Math.max(altitude, 5) * Math.PI / 180) : 999;
tile.observable = altitude > 30 && tile.airmass < 2.5;
});
return tiles;
}
// Render skymap
function renderSkymap() {
const canvas = document.getElementById('skymapCanvas');
const ctx = canvas.getContext('2d');
const { width, height } = canvas;
// Clear
ctx.fillStyle = '#0a0e14';
ctx.fillRect(0, 0, width, height);
if (!state.skymap) return;
const { data, threshold50, threshold90 } = state.skymap;
const imgData = ctx.createImageData(width, height);
// Render probability map
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const idx = y * width + x;
const skymapIdx = Math.floor(y * state.skymap.height / height) * state.skymap.width +
Math.floor(x * state.skymap.width / width);
const prob = data[skymapIdx] || 0;
let r = 10, g = 14, b = 20;
if (prob > threshold50) {
// High probability: cyan to white
const t = (prob - threshold50) / (1 - threshold50);
r = Math.floor(10 + t * 245);
g = Math.floor(200 + t * 55);
b = Math.floor(200 + t * 55);
} else if (prob > threshold90) {
// Medium probability: blue to orange
const t = (prob - threshold90) / (threshold50 - threshold90);
r = Math.floor(255 * t);
g = Math.floor(100 + 100 * t);
b = Math.floor(50 * (1 - t));
} else if (prob > 0.01) {
// Low probability: dim blue
const t = prob / threshold90;
r = Math.floor(20 * t);
g = Math.floor(30 * t);
b = Math.floor(60 * t);
}
const pxIdx = idx * 4;
imgData.data[pxIdx] = r;
imgData.data[pxIdx + 1] = g;
imgData.data[pxIdx + 2] = b;
imgData.data[pxIdx + 3] = 255;
}
}
ctx.putImageData(imgData, 0, 0);
// Draw grid lines
ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
ctx.lineWidth = 1;
// RA grid
for (let ra = 0; ra < 360; ra += 30) {
const x = (ra / 360) * width;
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
ctx.stroke();
}
// Dec grid
for (let dec = -60; dec <= 60; dec += 30) {
const y = (1 - (dec + 90) / 180) * height;
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(width, y);
ctx.stroke();
}
// Draw tiles
if (state.tiles.length > 0) {
state.tiles.forEach(tile => {
const x = (tile.ra / 360) * width;
const y = (1 - (tile.dec + 90) / 180) * height;
const w = (tile.size / 360) * width;
const h = (tile.size / 180) * height;
ctx.strokeStyle = tile.status === 'observed' ? '#7fef00' :
tile.status === 'observing' ? '#ff9940' :
tile === state.hoveredTile ? '#00d9ff' : 'rgba(0, 217, 255, 0.3)';
ctx.lineWidth = tile === state.hoveredTile ? 2 : 1;
ctx.strokeRect(x, y, w, h);
if (tile.status === 'observed') {
ctx.fillStyle = 'rgba(127, 239, 0, 0.1)';
ctx.fillRect(x, y, w, h);
}
});
}
// Draw galaxies
state.galaxies.forEach(galaxy => {
const x = (galaxy.ra / 360) * width;
const y = (1 - (galaxy.dec + 90) / 180) * height;
ctx.beginPath();
ctx.arc(x, y, 2 + galaxy.probability * 4, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 255, 100, ${0.3 + galaxy.probability * 0.7})`;
ctx.fill();
});
// Draw observatory FOVs
state.observatories.filter(o => o.active).forEach(obs => {
const activeTile = state.tiles.find(t => t.observatory === obs.id && t.status === 'observing');
if (activeTile) {
const x = (activeTile.ra / 360) * width;
const y = (1 - (activeTile.dec + 90) / 180) * height;
const w = (obs.fov / 360) * width;
const h = (obs.fov / 180) * height;
ctx.strokeStyle = obs.type === 'optical' ? '#00d9ff' :
obs.type === 'radio' ? '#ff9940' : '#ff3366';
ctx.lineWidth = 3;
ctx.strokeRect(x - w/2, y - h/2, w, h);
}
});
}
// Update UI
function updateUI() {
// Event info
if (state.event) {
document.getElementById('eventId').textContent = state.event.id;
document.getElementById('eventType').textContent = state.event.type;
document.getElementById('eventFar').textContent = state.event.far;
document.getElementById('eventDist').textContent = `${state.event.dist} ± ${state.event.distErr} Mpc`;
}
// Statistics
const totalProb = state.tiles.reduce((s, t) => s + t.probability, 0);
const coveredProb = state.tiles.filter(t => t.status === 'observed')
.reduce((s, t) => s + t.probability, 0);
const probCovered = totalProb > 0 ? (coveredProb / totalProb * 100).toFixed(1) : 0;
document.getElementById('probCovered').textContent = `${probCovered}%`;
document.getElementById('probBar').style.width = `${probCovered}%`;
document.getElementById('tilesObserved').textContent =
`${state.tiles.filter(t => t.status === 'observed').length}/${state.tiles.length}`;
document.getElementById('candidates').textContent = state.candidates.length;
document.getElementById('activeTelescopes').textContent =
state.observatories.filter(o => o.active).length;
// Tile counts
document.getElementById('totalTiles').textContent = state.tiles.length;
const avgProb = state.tiles.length > 0 ?
(state.tiles.reduce((s, t) => s + t.probability, 0) / state.tiles.length * 100).toFixed(1) : 0;
document.getElementById('avgProb').textContent = `${avgProb}%`;
const estHours = Math.ceil(state.tiles.length * 0.15);
document.getElementById('estTime').textContent = `${estHours}h`;
// Tile queue
updateTileQueue();
// Galaxy list
updateGalaxyList();
// Timeline
updateTimeline();
}
// Update tile queue display
function updateTileQueue() {
const container = document.getElementById('tileQueue');
const visibleTiles = state.tiles.slice(0, 20);
container.innerHTML = visibleTiles.map((tile, i) => `
<div class="tile-row p-3 border-b border-[--border] flex items-center gap-3 cursor-pointer slide-in"
style="animation-delay: ${i * 30}ms"
data-tile-id="${tile.id}">
<div class="w-8 h-8 rounded flex items-center justify-center text-xs font-bold mono
${tile.status === 'observed' ? 'bg-[--success]/20 text-[--success]' :
tile.status === 'observing' ? 'bg-[--warning]/20 text-[--warning]' :
'bg-[--accent]/20 text-[--accent]'}">
${i + 1}
</div>
<div class="flex-1 min-w-0">
<div class="flex items-center justify-between">
<span class="mono text-sm">${tile.id}</span>
<span class="text-xs px-2 py-0.5 rounded ${tile.observable !== false ? 'bg-[--success]/20 text-[--success]' : 'bg-[--danger]/20 text-[--danger]'}">
${tile.observable !== false ? 'Visible' : 'Not Visible'}
</span>
</div>
<div class="flex items-center gap-3 text-xs text-[--muted] mt-1">
<span>RA: ${tile.ra.toFixed(1)}°</span>
<span>Dec: ${tile.dec.toFixed(1)}°</span>
<span>P: ${(tile.probability * 100).toFixed(2)}%</span>
<span>Gal: ${tile.nearbyGalaxies}</span>
</div>
</div>
</div>
`).join('');
// Add hover listeners
container.querySelectorAll('.tile-row').forEach(row => {
row.addEventListener('mouseenter', () => {
const tileId = row.dataset.tileId;
state.hoveredTile = state.tiles.find(t => t.id === tileId);
renderSkymap();
});
row.addEventListener('mouseleave', () => {
state.hoveredTile = null;
renderSkymap();
});
});
}
// Update galaxy list
function updateGalaxyList() {
const container = document.getElementById('galaxyList');
const topGalaxies = state.galaxies.slice(0, 10);
if (topGalaxies.length === 0) {
container.innerHTML = '<div class="text-sm text-[--muted] text-center py-2">No galaxies in region</div>';
return;
}
container.innerHTML = topGalaxies.map(g => `
<div class="flex items-center justify-between text-sm py-1">
<span class="mono text-xs">${g.id}</span>
<span class="text-xs text-[--muted]">${g.type}</span>
<span class="text-xs text-[--accent]">${(g.probability * 100).toFixed(1)}%</span>
</div>
`).join('');
}
// Update timeline
function updateTimeline() {
const container = document.getElementById('timeline');
const events = [
{ time: 'T+0:00', desc: 'GW trigger received', type: 'gw', done: true },
{ time: 'T+0:05', desc: 'Initial skymap distributed', type: 'gw', done: true },
{ time: 'T+0:30', desc: 'ZTF begins observations', type: 'optical', done: state.currentTime > 30 },
{ time: 'T+1:00', desc: 'Swift XRT follow-up', type: 'xray', done: state.currentTime > 60 },
{ time: 'T+2:00', desc: 'VLA radio observations', type: 'radio', done: state.currentTime > 120 },
{ time: 'T+4:00', desc: 'Refined skymap (3-detector)', type: 'gw', done: state.currentTime > 240 },
{ time: 'T+12:00', desc: 'Spectroscopic follow-up', type: 'optical', done: state.currentTime > 720 }
];
container.innerHTML = events.map(e => `
<div class="relative pl-4 pb-2 ${e.done ? 'opacity-100' : 'opacity-50'}">
<div class="absolute left-[-5px] top-1 w-2 h-2 rounded-full ${
e.type === 'gw' ? 'bg-[--accent]' :
e.type === 'optical' ? 'bg-[--success]' :
e.type === 'radio' ? 'bg-[--warning]' : 'bg-[--danger]'
}"></div>
<div class="mono text-xs text-[--muted]">${e.time}</div>
<div class="text-sm">${e.desc}</div>
</div>
`).join('');
}
// Update observatory list
function updateObservatoryList() {
const container = document.getElementById('observatoryList');
container.innerHTML = state.observatories.map(obs => `
<label class="flex items-center gap-3 p-2 rounded cursor-pointer hover:bg-[--accent]/5 transition-colors">
<input type="checkbox" class="w-4 h-4 accent-[--accent]"
${obs.active ? 'checked' : ''}
data-obs-id="${obs.id}">
<div class="flex-1">
<div class="flex items-center gap-2">
<span class="font-medium">${obs.name}</span>
<span class="telescope-badge badge-${obs.type}">${obs.type}</span>
</div>
<div class="text-xs text-[--muted]">${obs.location} | FOV: ${obs.fov}°</div>
</div>
</label>
`).join('');
// Add change listeners
container.querySelectorAll('input[type="checkbox"]').forEach(cb => {
cb.addEventListener('change', (e) => {
const obsId = e.target.dataset.obsId;
const obs = state.observatories.find(o => o.id === obsId);
if (obs) {
obs.active = e.target.checked;
updateUI();
}
});
});
}
// Update candidates list
function updateCandidatesList() {
const container = document.getElementById('candidatesList');
if (state.candidates.length === 0) {
container.innerHTML = '<div class="text-sm text-[--muted] text-center py-4">No candidates yet</div>';
return;
}
container.innerHTML = state.candidates.map(c => `
<div class="p-3 bg-[--danger]/10 border border-[--danger]/30 rounded mb-2 slide-in">
<div class="flex items-center justify-between mb-1">
<span class="font-bold text-[--danger]">${c.id}</span>
<span class="text-xs bg-[--danger]/20 text-[--danger] px-2 py-0.5 rounded">NEW</span>
</div>
<div class="text-xs text-[--muted]">
RA: ${c.ra.toFixed(2)}° | Dec: ${c.dec.toFixed(2)}°
</div>
<div class="text-xs mt-1">
Magnitude: <span class="text-[--accent]">${c.magnitude.toFixed(2)}</span>
</div>
</div>
`).join('');
}
// Run search simulation
function runSearch() {
if (state.isSearching) return;
state.isSearching = true;
const activeObs = state.observatories.filter(o => o.active);
if (activeObs.length === 0) {
alert('Please select at least one observatory');
state.isSearching = false;
return;
}
let tileIndex = 0;
const obsIndex = { ztf: 0, lsst: 0, swift: 0, vla: 0 };
function observeNextTile() {
if (tileIndex >= state.tiles.length) {
state.isSearching = false;
return;
}
// Find next observable tile for each active observatory
activeObs.forEach(obs => {
for (let i = tileIndex; i < state.tiles.length; i++) {
const tile = state.tiles[i];
if (tile.status === 'pending' && tile.observable !== false) {
tile.status = 'observing';
tile.observatory = obs.id;
// Simulate observation time
setTimeout(() => {
tile.status = 'observed';
tile.observedAt = state.currentTime;
state.observedTiles.add(tile.id);
// Random chance of finding candidate
if (Math.random() < 0.02 && tile.nearbyGalaxies > 3) {
const candidate = {
id: `CAN${String(state.candidates.length + 1).padStart(3, '0')}`,
ra: tile.ra + Math.random() * tile.size,
dec: tile.dec + Math.random() * tile.size,
magnitude: 18 + Math.random() * 4,
tileId: tile.id
};
state.candidates.push(candidate);
updateCandidatesList();
}
updateUI();
renderSkymap();
}, 500 + Math.random() * 500);
break;
}
}
});
tileIndex += activeObs.length;
state.currentTime += 5;
updateUI();
renderSkymap();
if (tileIndex < state.tiles.length) {
setTimeout(observeNextTile, 800);
} else {
setTimeout(() => {
state.isSearching = false;
}, 1000);
}
}
observeNextTile();
}
// Generate new event
function generateEvent() {
const eventType = document.getElementById('eventSelect').value;
const template = EVENT_TEMPLATES[eventType];
// Create event
state.event = {
id: `S${new Date().toISOString().slice(2, 10).replace(/-/g, '')}${String(Math.floor(Math.random() * 26)).padStart(2, '0')}${String.fromCharCode(97 + Math.floor(Math.random() * 26))}`,
type: template.type,
dist: template.dist,
distErr: template.distErr,
far: template.far,
area90: template.area90,
area50: template.area50,
hasEM: template.hasEM
};
// Generate skymap
state.skymap = processSkymap(generateSkymap(template, 200, 100));
// Generate galaxies
state.galaxies = generateGalaxies(state.skymap);
// Setup observatories
state.observatories = OBSERVATORIES.map(o => ({ ...o, active: ['ztf', 'swift'].includes(o.id) }));
// Generate tiles
state.tiles = generateTiles(state.skymap, 8, state.tilingStrategy);
// Calculate observability for each observatory
state.observatories.forEach(obs => {
calculateObservability(state.tiles, obs);
});
// Reset state
state.observedTiles = new Set();
state.candidates = [];
state.currentTime = 0;
state.isSearching = false;
// Update UI
updateUI();
updateObservatoryList();
renderSkymap();
}
// Mouse tracking for coordinates display
function setupCanvasInteraction() {
const canvas = document.getElementById('skymapCanvas');
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const ra = (x / canvas.width) * 360;
const dec = 90 - (y / canvas.height) * 180;
document.getElementById('coordsDisplay').textContent =
`RA: ${ra.toFixed(2)}° | Dec: ${dec.toFixed(2)}°`;
});
}
// Event listeners
document.getElementById('generateBtn').addEventListener('click', generateEvent);
document.getElementById('runSearchBtn').addEventListener('click', runSearch);
document.getElementById('greedyBtn').addEventListener('click', () => {
state.tilingStrategy = 'greedy';
state.tiles = prioritizeTiles(state.tiles, 'greedy');
updateUI();
});
document.getElementById('balancedBtn').addEventListener('click', () => {
state.tilingStrategy = 'balanced';
state.tiles = prioritizeTiles(state.tiles, 'balanced');
updateUI();
});
document.getElementById('galaxyBtn').addEventListener('click', () => {
state.tilingStrategy = 'galaxy';
state.tiles = prioritizeTiles(state.tiles, 'galaxy');
updateUI();
});
// Handle canvas resize
function resizeCanvas() {
const canvas = document.getElementById('skymapCanvas');
const container = canvas.parentElement;
const rect = container.getBoundingClientRect();
canvas.width = Math.floor(rect.width);
canvas.height = Math.floor(rect.width * 0.625);
renderSkymap();
}
// Initialize
window.addEventListener('resize', resizeCanvas);
// Wait for fonts to load
document.fonts.ready.then(() => {
resizeCanvas();
generateEvent();
setupCanvasInteraction();
});
</script>
</body>
</html>