Spaces:
Running
Running
File size: 18,040 Bytes
e4f1db2 7bbab39 e4f1db2 7bbab39 e4f1db2 7bbab39 e4f1db2 7bbab39 e4f1db2 7bbab39 e4f1db2 7bbab39 e4f1db2 7bbab39 e4f1db2 7bbab39 e4f1db2 7bbab39 e4f1db2 7bbab39 e4f1db2 7bbab39 e4f1db2 |
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 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 |
const express = require('express');
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const NodeCache = require('node-cache');
const router = express.Router();
const cache = new NodeCache({ stdTTL: 3600 });
const ALGORITHMS_PATH = path.join(__dirname, '../../data/algorithms.json');
const TIMELINE_CACHE_PATH = path.join(__dirname, '../../data/timeline-cache.json');
const PUBMED_BASE_URL = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils';
function loadAlgorithms() {
const data = fs.readFileSync(ALGORITHMS_PATH, 'utf8');
return JSON.parse(data);
}
function loadTimelineCache() {
try {
if (fs.existsSync(TIMELINE_CACHE_PATH)) {
const data = fs.readFileSync(TIMELINE_CACHE_PATH, 'utf8');
return JSON.parse(data);
}
} catch (error) {
console.warn('Error loading timeline cache:', error.message);
}
return {};
}
function saveTimelineCache(cache) {
try {
fs.writeFileSync(TIMELINE_CACHE_PATH, JSON.stringify(cache, null, 2));
} catch (error) {
console.error('Error saving timeline cache:', error.message);
}
}
function getCacheKey(algorithmKey, year) {
return `${algorithmKey}-${year}`;
}
function isCurrentYear(year) {
return year === new Date().getFullYear();
}
async function searchAlgorithmUsage(problem, algorithmKey, algorithmData) {
try {
const synonymQueries = algorithmData.synonyms.map(synonym =>
`("${problem}" AND "${synonym}")`
).join(' OR ');
// Build blacklist exclusions if they exist
let blacklistExclusions = '';
if (algorithmData.blacklist && algorithmData.blacklist.length > 0) {
const blacklistTerms = algorithmData.blacklist.map(term => `NOT "${term}"`).join(' ');
blacklistExclusions = ` ${blacklistTerms}`;
}
// Add filters to exclude review papers, meta-analyses, and systematic reviews
const filteredQuery = `(${synonymQueries})${blacklistExclusions} NOT Review[Publication Type] NOT Meta-Analysis[Publication Type] NOT Systematic Review[Publication Type]`;
const searchUrl = `${PUBMED_BASE_URL}/esearch.fcgi?db=pubmed&term=${encodeURIComponent(filteredQuery)}&retmode=json`;
// Debug logging for CNN and GAN specifically
if (algorithmKey === 'cnn') {
console.log(`CNN Search for "${problem}":`);
console.log(`Query: ${filteredQuery}`);
console.log(`URL: ${searchUrl}`);
}
if (algorithmKey === 'gan') {
console.log(`GAN Search for "${problem}":`);
console.log(`Synonym queries: ${synonymQueries}`);
console.log(`Blacklist exclusions: ${blacklistExclusions}`);
console.log(`Final query: ${filteredQuery}`);
console.log(`URL: ${searchUrl}`);
}
const response = await axios.get(searchUrl);
const count = parseInt(response.data.esearchresult.count) || 0;
// Debug logging for CNN and GAN results
if (algorithmKey === 'cnn') {
console.log(`CNN Results: ${count} papers found`);
console.log(`Sample IDs:`, response.data.esearchresult.idlist?.slice(0, 3));
}
if (algorithmKey === 'gan') {
console.log(`GAN Results: ${count} papers found`);
console.log(`Sample IDs:`, response.data.esearchresult.idlist?.slice(0, 3));
}
return {
algorithm: algorithmKey,
name: algorithmData.name,
category: algorithmData.category,
description: algorithmData.description,
count: count,
sampleIds: response.data.esearchresult.idlist?.slice(0, 3) || []
};
} catch (error) {
if (algorithmKey === 'cnn') {
console.error(`CNN Search Error:`, error.message);
}
return {
algorithm: algorithmKey,
name: algorithmData.name,
category: algorithmData.category,
description: algorithmData.description,
count: 0,
sampleIds: []
};
}
}
router.post('/problem', async (req, res) => {
try {
const { problem } = req.body;
if (!problem) {
return res.status(400).json({ error: 'Problem parameter is required' });
}
const algorithms = loadAlgorithms();
const results = [];
for (const [key, algo] of Object.entries(algorithms.algorithms)) {
const result = await searchAlgorithmUsage(problem, key, algo);
results.push(result);
}
results.sort((a, b) => b.count - a.count);
res.json({
problem,
totalAlgorithms: results.length,
results: results.filter(r => r.count > 0),
allResults: results
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
async function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fetchAlgorithmCount(key, algo) {
const cacheKey = `dashboard-${key}`;
const cached = cache.get(cacheKey);
if (cached !== undefined) {
console.log(`${algo.name}: ${cached} results (cached)`);
return cached;
}
const generalQuery = algo.synonyms.map(s => `"${s}"`).join(' OR ');
// Build blacklist exclusions if they exist
let blacklistExclusions = '';
if (algo.blacklist && algo.blacklist.length > 0) {
const blacklistTerms = algo.blacklist.map(term => `NOT "${term}"`).join(' ');
blacklistExclusions = ` ${blacklistTerms}`;
}
// Add filters to exclude review papers, meta-analyses, and systematic reviews
const filteredQuery = `(${generalQuery})${blacklistExclusions} NOT Review[Publication Type] NOT Meta-Analysis[Publication Type] NOT Systematic Review[Publication Type]`;
try {
const searchUrl = `${PUBMED_BASE_URL}/esearch.fcgi?db=pubmed&term=${encodeURIComponent(filteredQuery)}&retmode=json`;
const response = await axios.get(searchUrl, { timeout: 15000 });
const count = parseInt(response.data.esearchresult.count) || 0;
console.log(`${algo.name}: ${count} results for query: ${filteredQuery}`);
cache.set(cacheKey, count);
return count;
} catch (error) {
console.error(`Error fetching data for ${algo.name}:`, error.message);
return 0;
}
}
router.get('/dashboard-stats', async (req, res) => {
try {
const algorithms = loadAlgorithms();
const stats = {
classical_ml: [],
deep_learning: [],
llms: []
};
// Process algorithms sequentially to avoid rate limiting
for (const [key, algo] of Object.entries(algorithms.algorithms)) {
const count = await fetchAlgorithmCount(key, algo);
stats[algo.category].push({
algorithm: key,
name: algo.name,
count: count
});
// Add delay between requests to respect rate limits
await delay(200);
}
stats.classical_ml.sort((a, b) => b.count - a.count);
stats.deep_learning.sort((a, b) => b.count - a.count);
stats.llms.sort((a, b) => b.count - a.count);
res.json(stats);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
router.get('/pubmed-link', (req, res) => {
const { problem, algorithm } = req.query;
if (!problem || !algorithm) {
return res.status(400).json({ error: 'Both problem and algorithm parameters are required' });
}
const algorithms = loadAlgorithms();
const algoData = algorithms.algorithms[algorithm];
if (!algoData) {
return res.status(404).json({ error: 'Algorithm not found' });
}
const synonymQueries = algoData.synonyms.map(synonym =>
`("${problem}" AND "${synonym}")`
).join(' OR ');
// Build blacklist exclusions if they exist
let blacklistExclusions = '';
if (algoData.blacklist && algoData.blacklist.length > 0) {
const blacklistTerms = algoData.blacklist.map(term => `NOT "${term}"`).join(' ');
blacklistExclusions = ` ${blacklistTerms}`;
}
// Add filters to exclude review papers for PubMed links too
const filteredQuery = `(${synonymQueries})${blacklistExclusions} NOT Review[Publication Type] NOT Meta-Analysis[Publication Type] NOT Systematic Review[Publication Type]`;
const pubmedUrl = `https://pubmed.ncbi.nlm.nih.gov/?term=${encodeURIComponent(filteredQuery)}`;
res.json({ url: pubmedUrl });
});
async function fetchAlgorithmCountByYear(key, algo, year, diskCache, retryCount = 0) {
const diskCacheKey = getCacheKey(key, year);
// Check disk cache first for past years (which never change)
if (!isCurrentYear(year) && diskCache[diskCacheKey] !== undefined) {
console.log(`Using disk cache for ${algo.name} (${year}): ${diskCache[diskCacheKey]}`);
return diskCache[diskCacheKey];
}
// Check memory cache for current year
const memoryCacheKey = `timeline-${key}-${year}`;
const memCached = cache.get(memoryCacheKey);
if (isCurrentYear(year) && memCached !== undefined) {
return memCached;
}
const generalQuery = algo.synonyms.map(s => `"${s}"`).join(' OR ');
const yearFilter = `"${year}"[Date - Publication]`;
// Build blacklist exclusions if they exist
let blacklistExclusions = '';
if (algo.blacklist && algo.blacklist.length > 0) {
const blacklistTerms = algo.blacklist.map(term => `NOT "${term}"`).join(' ');
blacklistExclusions = ` ${blacklistTerms}`;
}
const filteredQuery = `(${generalQuery}) AND ${yearFilter}${blacklistExclusions} NOT Review[Publication Type] NOT Meta-Analysis[Publication Type] NOT Systematic Review[Publication Type]`;
try {
const searchUrl = `${PUBMED_BASE_URL}/esearch.fcgi?db=pubmed&term=${encodeURIComponent(filteredQuery)}&retmode=json`;
const response = await axios.get(searchUrl, { timeout: 15000 });
const count = parseInt(response.data.esearchresult.count) || 0;
// Save to appropriate cache
if (isCurrentYear(year)) {
// Current year: save to memory cache (expires)
cache.set(memoryCacheKey, count);
} else {
// Past years: save to disk cache (permanent)
diskCache[diskCacheKey] = count;
}
console.log(`Fetched ${algo.name} (${year}): ${count} papers`);
return count;
} catch (error) {
if (error.response?.status === 429 && retryCount < 3) {
const backoffTime = Math.pow(2, retryCount) * 1000; // 1s, 2s, 4s
console.log(`Rate limited for ${algo.name} (${year}), retrying in ${backoffTime}ms (attempt ${retryCount + 1})`);
await delay(backoffTime);
return fetchAlgorithmCountByYear(key, algo, year, diskCache, retryCount + 1);
}
console.error(`Error fetching timeline data for ${algo.name} (${year}):`, error.message);
return 0;
}
}
router.get('/timeline-stream', async (req, res) => {
const { startYear = 2015, endYear = 2024 } = req.query;
const start = parseInt(startYear);
const end = parseInt(endYear);
if (start > end || start < 2010 || end > 2024) {
return res.status(400).json({ error: 'Invalid year range' });
}
// Set up Server-Sent Events
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Cache-Control'
});
const sendProgress = (data) => {
res.write(`data: ${JSON.stringify(data)}\n\n`);
};
try {
const algorithms = loadAlgorithms();
const diskCache = loadTimelineCache();
let cacheUpdated = false;
const years = [];
for (let year = start; year <= end; year++) {
years.push(year);
}
const timelineData = [];
const algorithmsData = [];
// Initialize timeline structure
for (const year of years) {
timelineData.push({ year });
}
// Count total operations
const totalAlgorithms = Object.keys(algorithms.algorithms).length;
const totalYears = years.length;
const totalOperations = totalAlgorithms * totalYears;
let completedOperations = 0;
let cachedResults = 0;
let fetchedResults = 0;
// Count cached vs fetched upfront
for (const [key, algo] of Object.entries(algorithms.algorithms)) {
for (const year of years) {
const diskCacheKey = getCacheKey(key, year);
if (!isCurrentYear(year) && diskCache[diskCacheKey] !== undefined) {
cachedResults++;
} else {
fetchedResults++;
}
}
}
sendProgress({
type: 'init',
totalOperations,
cachedResults,
fetchedResults,
message: 'Starting timeline data collection...'
});
// Process each algorithm
for (const [key, algo] of Object.entries(algorithms.algorithms)) {
const algorithmTimeline = {
algorithm: key,
name: algo.name,
category: algo.category,
data: []
};
sendProgress({
type: 'algorithm_start',
algorithm: algo.name,
progress: Math.round((completedOperations / totalOperations) * 100),
completed: completedOperations,
total: totalOperations
});
// Get data for each year
for (const year of years) {
const count = await fetchAlgorithmCountByYear(key, algo, year, diskCache);
algorithmTimeline.data.push({ year, count });
// Add to timeline data structure
const yearIndex = timelineData.findIndex(item => item.year === year);
if (yearIndex !== -1) {
timelineData[yearIndex][key] = count;
}
completedOperations++;
sendProgress({
type: 'year_complete',
algorithm: algo.name,
year,
count,
progress: Math.round((completedOperations / totalOperations) * 100),
completed: completedOperations,
total: totalOperations
});
// Check if we made an API call and need to save cache
const diskCacheKey = getCacheKey(key, year);
if (!isCurrentYear(year) && diskCache[diskCacheKey] === count) {
cacheUpdated = true;
}
// Add delay only if we made an actual API call
if (isCurrentYear(year) || diskCache[diskCacheKey] === undefined) {
await delay(500);
}
}
algorithmsData.push(algorithmTimeline);
sendProgress({
type: 'algorithm_complete',
algorithm: algo.name,
progress: Math.round((completedOperations / totalOperations) * 100),
completed: completedOperations,
total: totalOperations
});
}
// Save cache if updated
if (cacheUpdated) {
saveTimelineCache(diskCache);
sendProgress({
type: 'cache_saved',
message: 'Timeline cache updated and saved to disk'
});
}
// Send final results
sendProgress({
type: 'complete',
timelineData,
algorithms: algorithmsData,
yearRange: { start, end },
cacheStats: {
cached: cachedResults,
fetched: fetchedResults
}
});
res.end();
} catch (error) {
sendProgress({
type: 'error',
error: error.message
});
res.end();
}
});
router.get('/timeline', async (req, res) => {
try {
const { startYear = 2015, endYear = 2024 } = req.query;
const start = parseInt(startYear);
const end = parseInt(endYear);
if (start > end || start < 2010 || end > 2024) {
return res.status(400).json({ error: 'Invalid year range' });
}
const algorithms = loadAlgorithms();
const diskCache = loadTimelineCache();
let cacheUpdated = false;
const years = [];
for (let year = start; year <= end; year++) {
years.push(year);
}
const timelineData = [];
const algorithmsData = [];
// Initialize timeline structure
for (const year of years) {
timelineData.push({ year });
}
// Count how many API calls we'll need to make
let totalApiCalls = 0;
let cachedResults = 0;
for (const [key, algo] of Object.entries(algorithms.algorithms)) {
for (const year of years) {
const diskCacheKey = getCacheKey(key, year);
if (!isCurrentYear(year) && diskCache[diskCacheKey] !== undefined) {
cachedResults++;
} else {
totalApiCalls++;
}
}
}
console.log(`Timeline request: ${cachedResults} cached results, ${totalApiCalls} API calls needed`);
// Process each algorithm
for (const [key, algo] of Object.entries(algorithms.algorithms)) {
const algorithmTimeline = {
algorithm: key,
name: algo.name,
category: algo.category,
data: []
};
// Get data for each year
for (const year of years) {
const count = await fetchAlgorithmCountByYear(key, algo, year, diskCache);
algorithmTimeline.data.push({ year, count });
// Add to timeline data structure
const yearIndex = timelineData.findIndex(item => item.year === year);
if (yearIndex !== -1) {
timelineData[yearIndex][key] = count;
}
// Check if we made an API call (not cached) and need to save cache
const diskCacheKey = getCacheKey(key, year);
if (!isCurrentYear(year) && diskCache[diskCacheKey] === count) {
cacheUpdated = true;
}
// Add delay only if we made an actual API call
if (isCurrentYear(year) || diskCache[diskCacheKey] === undefined) {
await delay(500);
}
}
algorithmsData.push(algorithmTimeline);
console.log(`Completed timeline data for ${algo.name}`);
}
// Save updated cache to disk if needed
if (cacheUpdated) {
saveTimelineCache(diskCache);
console.log('Timeline cache updated and saved to disk');
}
res.json({
timelineData,
algorithms: algorithmsData,
yearRange: { start, end },
cacheStats: {
cached: cachedResults,
fetched: totalApiCalls
}
});
} catch (error) {
console.error('Timeline API error:', error);
res.status(500).json({ error: error.message });
}
});
module.exports = router; |