-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
496 lines (421 loc) · 16.1 KB
/
script.js
File metadata and controls
496 lines (421 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// Global variables
let leaderboardData = [];
let currentDomain = 'overall'; // will be mapped to 'Overall' when displaying
let isOracleMode = false; // toggle to switch between benchmark_results.csv and benchmark_oracle.csv
let pipelineDesignData = [];
let pipelineImplementationData = [];
// Load and display leaderboard data
async function loadLeaderboard() {
try {
// Select the appropriate CSV file based on the oracle mode toggle
const csvFile = isOracleMode ? "data/benchmark_oracle.csv" : "data/benchmark_results.csv";
console.log(`Loading data from: ${csvFile} (Oracle mode: ${isOracleMode})`);
const response = await fetch(csvFile);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const csvText = await response.text();
const parsed = Papa.parse(csvText, { header: true });
if (parsed.errors && parsed.errors.length > 0) {
console.warn('CSV parsing errors:', parsed.errors);
}
// Filter out empty rows, require System and Models fields
console.log('Parsed CSV data:', parsed.data);
leaderboardData = parsed.data.filter(d => d.System && d.System.trim() !== '' && d.Models && d.Models.trim() !== '');
console.log('Filtered leaderboard data:', leaderboardData);
displayLeaderboard(currentDomain);
} catch (error) {
console.error('Error loading leaderboard:', error);
const tbody = document.querySelector("#leaderboard-table tbody");
if (tbody) {
tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #dc3545;">Error loading leaderboard data: ' + error.message + '</td></tr>';
}
}
}
// Global variable for search term
let currentSearchTerm = '';
// Display leaderboard for selected domain
function displayLeaderboard(domain, searchTerm = currentSearchTerm) {
if (!leaderboardData.length) {
const tbody = document.querySelector("#leaderboard-table tbody");
tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #dc3545;">No data available</td></tr>';
return;
}
// Store the current search term for reusing when domain changes
currentSearchTerm = searchTerm;
// Adjust domain name casing (benchmark_results.csv uses capitalized domain names)
const adjustedDomain = domain.charAt(0).toUpperCase() + domain.slice(1);
// Filter out entries that don't have a score for this domain
let validData = leaderboardData.filter(entry => {
const score = parseFloat(entry[adjustedDomain]);
return !isNaN(score) && score >= 0;
});
// Apply search filter if provided
if (searchTerm && searchTerm.trim() !== '') {
const normalizedSearchTerm = searchTerm.trim().toLowerCase();
validData = validData.filter(entry => {
const system = (entry.System || '').toLowerCase();
const model = (entry.Models || '').toLowerCase();
return system.includes(normalizedSearchTerm) || model.includes(normalizedSearchTerm);
});
// Add a status message about filtered results
const filterStatus = document.querySelector('#filter-status');
if (filterStatus) {
filterStatus.textContent = `Showing ${validData.length} filtered results with original rankings`;
filterStatus.style.display = 'block';
}
} else {
// Clear the filter status message when no search
const filterStatus = document.querySelector('#filter-status');
if (filterStatus) {
filterStatus.style.display = 'none';
}
}
if (!validData.length) {
const tbody = document.querySelector("#leaderboard-table tbody");
tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #dc3545;">No matching results found</td></tr>';
return;
}
// First, sort ALL valid data by domain score to determine original rankings
const allValidData = leaderboardData.filter(entry => {
const score = parseFloat(entry[adjustedDomain]);
return !isNaN(score) && score >= 0;
}).sort((a, b) => {
const scoreA = parseFloat(a[adjustedDomain]) || 0;
const scoreB = parseFloat(b[adjustedDomain]) || 0;
return scoreB - scoreA;
});
// Create a map of entries to their original rankings
const originalRankMap = new Map();
allValidData.forEach((entry, index) => {
// Use a unique identifier combining system, model and score to ensure proper mapping
// This handles cases where systems/models might have identical names
const score = parseFloat(entry[adjustedDomain]) || 0;
const uniqueId = `${entry.System}-${entry.Models}-${score.toFixed(3)}`;
originalRankMap.set(uniqueId, index + 1);
});
// Now sort the filtered valid data by original rank (to preserve order)
const sortedData = [...validData].sort((a, b) => {
const scoreA = parseFloat(a[adjustedDomain]) || 0;
const scoreB = parseFloat(b[adjustedDomain]) || 0;
// If we're searching, sort by original rank to maintain the global ranking order
if (searchTerm && searchTerm.trim() !== '') {
const idA = `${a.System}-${a.Models}-${scoreA.toFixed(3)}`;
const idB = `${b.System}-${b.Models}-${scoreB.toFixed(3)}`;
const rankA = originalRankMap.get(idA) || 999;
const rankB = originalRankMap.get(idB) || 999;
return rankA - rankB;
}
// Otherwise, sort by score
return scoreB - scoreA;
});
const tbody = document.querySelector("#leaderboard-table tbody");
tbody.innerHTML = ''; // Clear existing content
sortedData.forEach((entry) => {
const row = document.createElement("tr");
// Get score once and use it for both ranking and display
const score = parseFloat(entry[adjustedDomain]) || 0;
const scoreDisplay = escapeHtml((entry[adjustedDomain] || `${score.toFixed(1)}%`).trim());
const overallBenchmarkTime = escapeHtml((entry['Overall Benchmark Time'] || '-').trim());
// Get the original rank using the same unique identifier format
const uniqueId = `${entry.System}-${entry.Models}-${score.toFixed(3)}`;
const originalRank = originalRankMap.get(uniqueId);
// Add special styling for top 3 based on original rank
if (originalRank <= 3) {
row.classList.add(`rank-${originalRank}`);
}
// Highlight search terms if present
let systemText = escapeHtml(entry.System);
let modelText = escapeHtml(entry.Models);
if (searchTerm && searchTerm.trim() !== '') {
const regex = new RegExp(`(${escapeHtml(searchTerm.trim())})`, 'gi');
systemText = systemText.replace(regex, '<mark>$1</mark>');
modelText = modelText.replace(regex, '<mark>$1</mark>');
}
row.innerHTML = `
<td>${originalRank}</td>
<td>${systemText}</td>
<td>${modelText}</td>
<td>${scoreDisplay}</td>
<td>${overallBenchmarkTime}</td>
`;
tbody.appendChild(row);
});
// Add top performers styling
addTopPerformersStyling();
}
function parseScoreValue(rawScore) {
const scoreText = typeof rawScore === 'string' ? rawScore : '';
const match = scoreText.match(/-?\d+(?:\.\d+)?/);
if (!match) {
return NaN;
}
return parseFloat(match[0]);
}
function renderPipelineTable(tableSelector, entries) {
const tableBody = document.querySelector(`${tableSelector} tbody`);
if (!tableBody) {
return;
}
if (!entries.length) {
tableBody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: #dc3545;">No data available</td></tr>';
return;
}
const sortedEntries = [...entries].sort((a, b) => {
const scoreA = parseScoreValue(a.Overall);
const scoreB = parseScoreValue(b.Overall);
const safeScoreA = Number.isNaN(scoreA) ? -Infinity : scoreA;
const safeScoreB = Number.isNaN(scoreB) ? -Infinity : scoreB;
return safeScoreB - safeScoreA;
});
tableBody.innerHTML = '';
sortedEntries.forEach((entry, index) => {
const rank = index + 1;
const row = document.createElement('tr');
if (rank <= 3) {
row.classList.add(`rank-${rank}`);
}
row.innerHTML = `
<td>${rank}</td>
<td>${escapeHtml((entry.System || '-').trim())}</td>
<td>${escapeHtml((entry.Models || '-').trim())}</td>
<td>${escapeHtml((entry.Overall || '-').trim())}</td>
`;
tableBody.appendChild(row);
});
}
async function loadPipelineScores() {
const sources = [
{
url: 'data/pipeline_design_scores.csv',
assignData: data => {
pipelineDesignData = data;
}
},
{
url: 'data/pipeline_implementation_scores.csv',
assignData: data => {
pipelineImplementationData = data;
}
}
];
await Promise.all(sources.map(async source => {
const response = await fetch(source.url);
if (!response.ok) {
throw new Error(`HTTP error (${source.url}): ${response.status}`);
}
const csvText = await response.text();
const parsed = Papa.parse(csvText, { header: true });
if (parsed.errors && parsed.errors.length > 0) {
console.warn(`CSV parsing errors for ${source.url}:`, parsed.errors);
}
const cleanRows = parsed.data.filter(row => {
const hasBasicFields = row.System && row.System.trim() !== '' && row.Models && row.Models.trim() !== '';
const hasValidScore = !Number.isNaN(parseScoreValue(row.Overall));
return hasBasicFields && hasValidScore;
});
source.assignData(cleanRows);
}));
renderPipelineTable('#pipeline-design-table', pipelineDesignData);
renderPipelineTable('#pipeline-implementation-table', pipelineImplementationData);
}
// Handle domain selection change
function handleDomainChange() {
const domainSelector = document.querySelector('#domain-selector');
if (domainSelector) {
// Update domain selector options to match capitalized domains in benchmark_results.csv
const domains = ['Overall', 'Archaeology', 'Astronomy', 'Biomedical', 'Environment', 'Legal', 'Wildfire'];
// Clear existing options
domainSelector.innerHTML = '';
// Add new options
domains.forEach(domain => {
const option = document.createElement('option');
option.value = domain.toLowerCase();
option.textContent = domain;
domainSelector.appendChild(option);
});
domainSelector.addEventListener('change', function(e) {
currentDomain = e.target.value;
displayLeaderboard(currentDomain);
});
}
}
// Handle oracle toggle change
function handleOracleToggle() {
const oracleToggle = document.querySelector('#oracle-toggle');
const toggleContainer = document.querySelector('.toggle-container');
if (oracleToggle) {
// Initialize with correct state
isOracleMode = oracleToggle.checked;
// Add click handler to both the toggle and its container for better UX
function toggleHandler() {
// Toggle the checkbox state
oracleToggle.checked = !oracleToggle.checked;
isOracleMode = oracleToggle.checked;
// Update the title to indicate which dataset is being shown
const title = document.querySelector('.leaderboard-section h2');
if (title) {
title.textContent = isOracleMode ? "Current Rankings (Oracle Inputs)" : "Current Rankings";
}
console.log(`Oracle mode toggled: ${isOracleMode}`);
// Reload the leaderboard data with the new source
loadLeaderboard();
// Visual feedback - add a pulse animation
toggleContainer.classList.add('pulse');
setTimeout(() => {
toggleContainer.classList.remove('pulse');
}, 500);
}
// For label/container clicking
toggleContainer.addEventListener('click', function(e) {
// Prevent triggering twice if clicking directly on the checkbox
if (e.target !== oracleToggle) {
e.preventDefault();
toggleHandler();
}
});
// Add keyboard support (for accessibility)
toggleContainer.addEventListener('keydown', function(e) {
// Toggle on Enter or Space key
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleHandler();
}
});
// For direct checkbox changes
oracleToggle.addEventListener('change', function() {
isOracleMode = this.checked;
// Update the title to indicate which dataset is being shown
const title = document.querySelector('.leaderboard-section h2');
if (title) {
title.textContent = isOracleMode ? "Current Rankings (Oracle Inputs)" : "Current Rankings";
}
console.log(`Oracle mode changed: ${isOracleMode}`);
// Reload the leaderboard data with the new source
loadLeaderboard();
});
}
}
// Utility function to escape HTML
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Format date for display
function formatDate(dateString) {
try {
const date = new Date(dateString);
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
} catch (error) {
return dateString; // Return original if parsing fails
}
}
// Add special styling for top performers
function addTopPerformersStyling() {
const styles = `
<style>
.rank-1 td:first-child::before { content: "🥇 "; }
.rank-2 td:first-child::before { content: "🥈 "; }
.rank-3 td:first-child::before { content: "🥉 "; }
.rank-1:hover, .rank-2:hover, .rank-3:hover {
transform: scale(1.01);
transition: transform 0.2s ease;
}
</style>
`;
if (!document.querySelector('#top-performers-styles')) {
const styleElement = document.createElement('div');
styleElement.id = 'top-performers-styles';
styleElement.innerHTML = styles;
document.head.appendChild(styleElement);
}
}
// Smooth scrolling for navigation links
function initSmoothScrolling() {
document.querySelectorAll('.sidebar a[href^="#"]').forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault();
const targetId = this.getAttribute('href');
const targetElement = document.querySelector(targetId);
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
});
});
}
// Handle search functionality
function handleSearch() {
const searchInput = document.querySelector('#search-input');
const clearSearchBtn = document.querySelector('#clear-search');
if (searchInput && clearSearchBtn) {
// Search as you type (with debounce)
let debounceTimeout;
searchInput.addEventListener('input', function() {
clearTimeout(debounceTimeout);
// Show/hide clear button
if (this.value) {
clearSearchBtn.style.display = 'block';
} else {
clearSearchBtn.style.display = 'none';
}
// Debounce the search
debounceTimeout = setTimeout(() => {
displayLeaderboard(currentDomain, this.value);
}, 300);
});
// Clear search when button is clicked
clearSearchBtn.addEventListener('click', function() {
searchInput.value = '';
clearSearchBtn.style.display = 'none';
displayLeaderboard(currentDomain, '');
// Add focus back to input
searchInput.focus();
});
// Handle enter key press
searchInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter') {
e.preventDefault();
displayLeaderboard(currentDomain, this.value);
} else if (e.key === 'Escape') {
// Clear on escape
this.value = '';
clearSearchBtn.style.display = 'none';
displayLeaderboard(currentDomain, '');
}
});
}
}
// Initialize the page
document.addEventListener('DOMContentLoaded', function() {
loadLeaderboard();
loadPipelineScores().catch(error => {
console.error('Error loading pipeline scores:', error);
renderPipelineTable('#pipeline-design-table', []);
renderPipelineTable('#pipeline-implementation-table', []);
});
handleDomainChange();
handleOracleToggle();
handleSearch();
initSmoothScrolling();
// Auto-refresh leaderboard every 5 minutes
setInterval(loadLeaderboard, 5 * 60 * 1000);
});
// Export functions for potential external use
window.KramaBench = {
loadLeaderboard,
loadPipelineScores,
displayLeaderboard,
formatDate,
escapeHtml,
handleDomainChange,
handleOracleToggle,
handleSearch
};