-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
679 lines (544 loc) · 25.2 KB
/
script.js
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
import { animateScalpels } from './animation.js';
document.addEventListener("DOMContentLoaded", function () {
let currentState = 0;
let surgeryData = {};
let cancerData = {};
let genderData = {};
let svgElements = {};
const organPositions = {
"Thyroid": { x: 120, y: 100 },
"Stomach": { x: 180, y: 450 },
"Pancreas": { x: 105, y: 510 },
"Kidneys": { x: 185, y: 525 },
"Heart": { x: 130, y: 360 },
"Liver": { x: 70, y: 430 },
"Intestines": { x: 120, y: 620},
"Reproductive": { x: 120, y: 750 }
};
const steps = document.querySelectorAll(".step");
let title = d3.select("#title").append("h2")
.attr("id", "status-title")
.style("text-align", "center");
const mainContainer = d3.select("#main-container");
const scroller = scrollama();
const visualizationWrapper = mainContainer.append("div")
.attr("id", "visualization-wrapper");
const leftChartsContainer = visualizationWrapper.append("div")
.attr("id", "left-charts-container");
const centerContainer = visualizationWrapper.append("div")
.attr("id", "center-container");
const rightChartsContainer = visualizationWrapper.append("div")
.attr("id", "right-charts-container");
const leftPositions = [
{ id: "Lymphatic-Endocrine", label: "Lymphatic/Endocrine System", organId: "Thyroid", organName: "Thyroid" },
{ id: "Digestive", label: "Digestive System", organId: "Stomach", organName: "Stomach" },
{ id: "Pancreatic-Biliary", label: "Pancreatic/Biliary System", organId: "Pancreas", organName: "Pancreas" },
{ id: "Urinary", label: "Urinary System", organId: "Kidneys", organName: "Kidneys" }
];
const rightPositions = [
{ id: "Cardiovascular", label: "Cardiovascular System", organId: "Heart", organName: "Heart" },
{ id: "Hepatic", label: "Hepatic System", organId: "Liver", organName: "Liver" },
{ id: "Colorectal", label: "Colorectal System", organId: "Intestines", organName: "Intestines" },
{ id: "Reproductive", label: "Reproductive System", organId: "Female_RS", organName: "Reproductive" }
];
const positions = [...leftPositions, ...rightPositions];
leftPositions.forEach(pos => createChartContainer(leftChartsContainer, pos));
rightPositions.forEach(pos => createChartContainer(rightChartsContainer, pos));
const closeButton = document.querySelector("#close-panel");
if (closeButton) {
closeButton.addEventListener("click", function () {
console.log("Close button clicked!");
d3.select("#side-panel")
.classed("show", false)
.style("right", "-350px"); // Move panel off-screen
});
} else {
console.error("Close button not found!");
}
d3.csv("sugeries.csv").then(function (data) {
processData(data);
setTimeout(() => {
createBarCharts();
updateAll();
}, 500); // Delay ensures data is fully processed before rendering
d3.xml("Images/only_organs_removebg.svg").then(function (xml) {
const svgContainer = d3.select("#center-container").append("div")
.attr("id", "svg-container")
.style("width", "50%")
.style("display", "flex")
.style("height", "50vh")
.style("justify-content", "center")
.style("align-items", "center")
.style("position", "relative")
.style("top", "-100px") // Move up by 100px
.style("left", "70px") // Move right by 70px
.style("z-index", "0");
let importedNode = document.importNode(xml.documentElement, true);
importedNode.id = "body-svg";
importedNode.setAttribute("preserveAspectRatio", "xMidYMid meet");
importedNode.setAttribute("width", "100%");
importedNode.setAttribute("height", "100vh");
importedNode.setAttribute("viewBox", "0 0 400 800"); // Adjust viewBox to match your SVG content
svgContainer.node().appendChild(importedNode);
// Delay the appending of the pulsing dot to ensure SVG loads first
setTimeout(() => {
const centerSvg = d3.select("#body-svg");
if (!centerSvg.empty()) {
//console.log("SVG found! Appending pulsing dot...");
const pulsingDot = centerSvg.append("circle")
.attr("class", "pulsing-dot")
.attr("r", 10) // Dot radius
function showPulsingDot(organName) {
if (!organPositions[organName]) return;
const { x, y } = organPositions[organName];
pulsingDot
.interrupt() // Stop any existing transitions
.attr("cx", x)
.attr("cy", y)
.style("display", "block") // Ensure it appears
.transition()
.duration(300)
.style("opacity", 1);
}
function hidePulsingDot() {
pulsingDot
.transition()
.duration(200)
.style("opacity", 0)
.on("end", function () {
d3.select(this).style("display", "none"); // Ensure it's hidden after fade out
});
}
positions.forEach(pos => {
d3.select(`#chart-container-${pos.id}`)
.style("cursor", "pointer") // Ensure hover cursor
.on("mouseenter", () => {
console.log(`Hovering over ${pos.id}`);
showPulsingDot(pos.organName);
})
.on("mouseleave", hidePulsingDot)
.on("click", function () {
if (currentState === 0) return; // No panel for step 0
let content = generatePanelContent(pos.id, currentState);
toggleSidePanel(content);
});;
});
} else {
console.error("Main SVG #body-svg not found! Ensure it loads before appending the pulsing dot.");
}
// Initialize charts now that containers exist
createBarCharts();
updateAll();
}, 500);
});
// Create the pulsing dot container inside the central SVG
const centerSvg = d3.select("#body-svg");
});
function createChartContainer(parentContainer, pos) {
const container = parentContainer.append("div")
.attr("id", `chart-container-${pos.id}`)
.style("display", "flex")
.style("flex-direction", "column") // Stack elements vertically
.style("align-items", "center")
.style("justify-content", "space-between")
.style("margin", "5px")
.style("padding", "5px")
.style("background", "transparent")
.style("border-radius", "8px")
.style("box-shadow", "0 2px 4px rgba(110, 110, 110, 0.1)")
.style("width", "100%")
.style("position", "relative");
// Top Section: Title and Organ Image
const topSection = container.append("div")
.style("display", "flex")
.style("flex-direction", "row") // Arrange title and image in a column
.style("align-items", "center")
.style("width", "100%")
.style("justify-content", "space-between");
// Title
const titleContainer = topSection.append("div")
.style("width", "35%") // Allocate space for title
.style("text-align", "left")
.style("padding-left", "10px");
titleContainer.append("h4")
.text(pos.label)
.style("margin-bottom", "5px")
.style("font-size", "14px");
// Organ Image
const imageContainer = topSection.append("div")
.style("width", "30%") // Allocate space for image
.style("display", "flex")
.style("justify-content", "center")
.style("align-items", "center")
.style("padding-left", "10px");
imageContainer.append("img")
.attr("src", `Images/${pos.organId}.png`)
.attr("width", "45px")
.attr("height", "45px");
// Description
const descriptionContainer = topSection.append("div")
.attr("id", `text-${pos.id}`)
.style("width", "50%") // Allocate space for description
.style("font-size", "12px")
.style("text-align", "left");
// Bottom Section: Bar Container (spanning full width)
const barContainer = container.append("div")
.attr("id", `chart-${pos.id}`);
}
let globalData = []; // Declare a global variable
d3.csv("sugeries.csv").then(data => {
globalData = data; // Store data globally
processData(data); // Process data
createBarCharts(); // Create charts after processing
});
function processData(data) {
data.forEach(d => {
let optype = d.optype.replace(/\//g, "-");
surgeryData[optype] = (surgeryData[optype] || 0) + 1;
let isCancer = /(cancer|carcinoma|malignant|blastoma|tumor|neoplasm|sarcoma|glioma|lymphoma|leukemia|melanoma|mesothelioma|myeloma|teratoma)/i.test(d.dx);
let gender = d.sex;
if (isCancer) {
cancerData[optype] = (cancerData[optype] || 0) + 1;
if (!genderData[optype]) {
genderData[optype] = { total: 0, M: 0, F: 0 };
}
genderData[optype].total += 1;
genderData[optype][gender] += 1;
}
return data.map(d => ({
system: d.system,
total: +d.total_surgeries,
cancer: +d.cancer_surgeries,
male: +d.male_cancer_surgeries,
female: +d.female_cancer_surgeries
}));
});
}
function createBarCharts() {
let totalSurgeries = Object.values(surgeryData).reduce((a, b) => a + b, 0);
positions.forEach(pos => {
let container = d3.select(`#chart-${pos.id}`);
if (container.empty()) {
console.warn(`Missing container: chart-${pos.id}`);
return;
}
// Clear existing SVG
container.selectAll("svg").remove(); // Remove any existing SVG before creating new ones
// Create SVG for bar chart
let svg = container.append("svg")
.attr("width", "100%") // Full width to match the container
.attr("height", "30px");
svgElements[pos.id] = svg;
updateBarChart(pos.id, totalSurgeries);
});
}
function updateBarChart(optype, totalSurgeries) {
let total = surgeryData[optype] ?? 0;
let totalCancer = cancerData[optype] ?? 0;
let maleCancer = genderData[optype]?.M ?? 0;
let femaleCancer = genderData[optype]?.F ?? 0;
let referenceTotal; // This is the new "100%" value
// Avoid division by zero
if (total === 0) total = 1;
if (totalCancer === 0) totalCancer = 1;
let nonCancerCases = total - totalCancer;
let textContent = "";
let data;
if (currentState === 0) {
return; // Do nothing on Step 0
}
else if (currentState === 1) {
referenceTotal = totalSurgeries; // 100% is all surgeries
data = [
{ label: "System-specific Surgery", value: total, color: "red" },
{ label: "Other Surgeries", value: totalSurgeries - total, color: "lightgrey" }
];
textContent = `Out of all surgeries, <b style="color:red">${optype}</b> constituted <b style="color:red">${Math.round((total / totalSurgeries) * 100)}%</b> of the total surgeries.`;
} else if (currentState === 2) {
referenceTotal = total; // Now, system-specific surgeries become 100%
data = [
{ label: "Cancer", value: totalCancer, color: "orange" },
{ label: "Non-Cancer", value: total - totalCancer, color: "lightgrey" }
];
textContent = `Out of all <b style="color:orange">${optype}</b> surgeries, <b style="color:orange">${Math.round((totalCancer / total) * 100)}%</b> were cancer-related.`;
} else if (currentState === 3) {
referenceTotal = totalCancer; // Now, cancer surgeries become 100%
data = [
{ label: "Male Cancer", value: maleCancer, color: "lightblue" },
{ label: "Female Cancer", value: femaleCancer, color: "pink" }
];
textContent = `Women made up <b style="color:pink">${Math.round((femaleCancer / totalCancer) * 100)}%</b> and men <b style="color:lightblue">${Math.round((maleCancer / totalCancer) * 100)}%</b> of cancer-related surgeries.`;
}
// Prevent division by zero
referenceTotal = referenceTotal || 1;
let svg = svgElements[optype];
if (!svg) return;
let container = d3.select(`#chart-${optype}`);
if (container.empty()) {
console.warn(`Container for ${optype} not found`);
return;
}
let totalWidth = container.node().getBoundingClientRect().width || 300; // Fallback to 300px if width is not detected
let bars = svg.selectAll("rect")
.data(data, d => d.label); // Use data join to prevent duplicates
bars.enter()
.append("rect")
.merge(bars)
.transition()
.duration(500)
.attr("x", (d, i) => i === 0 ? 0 : d3.sum(data.slice(0, i), d => d.value) / referenceTotal * totalWidth)
.attr("width", d => (d.value / referenceTotal) * totalWidth)
.attr("height", "25")
.attr("ry", 2) // Rounds the corners vertically
.attr("fill", d => d.color);
bars.exit().remove(); // Ensure old bars are properly removed
d3.select(`#text-${optype}`).html(textContent);
}
function updateAll() {
let totalSurgeries = d3.sum(Object.values(surgeryData));
updateTitle();
updateLegend();
console.log("Current state:", currentState);
positions.forEach(pos => {
updateBarChart(pos.id, totalSurgeries);
});
}
function updateTitle() {
const titles = [
"",
"Analysis of the Distribution of Surgeries by Organs and Systems",
"Distribution of Surgeries Related to Cancer Diagnoses",
"Comparison of Surgeries Performed on Female and Male Cancer Patients by Organ Systems",
"Comparison of Surgeries Performed on Female and Male Cancer Patients by Organ Systems"
];
title.text(titles[currentState]);
}
function updateLegend() {
let legend = d3.select("#legend");
if (currentState === 0) {
// Completely hide the legend at step 0
legend.transition()
.duration(500)
.style("opacity", 0)
.on("end", function() {
d3.select(this).style("display", "none"); // Hide it completely
});
return;
}
// If we are not in step 0, ensure the legend exists and is visible
if (legend.empty()) {
legend = d3.select("body").append("div")
.attr("id", "legend")
.style("display", "none") // Start hidden
.style("opacity", 0);
}
// Ensure legend is visible when moving to step 1+
legend.style("display", "flex")
.transition()
.duration(500)
.style("opacity", 1);
let legendData;
if (currentState === 1) {
legendData = [
{ label: "All Other Surgeries", color: "lightgrey" },
{ label: "System-specific Surgery", color: "red" }
];
} else if (currentState === 2) {
legendData = [
{ label: "Cancer", color: "orange" },
{ label: "Non-Cancer", color: "lightgrey" }
];
} else if (currentState === 3) {
legendData = [
{ label: "Non-Cancer", color: "lightgrey" },
{ label: "Male Cancer", color: "lightblue" },
{ label: "Female Cancer", color: "pink" }
];
} else {
return; // No legend for other steps
}
// Update legend items
let items = legend.selectAll(".legend-item")
.data(legendData);
items.enter()
.append("div")
.attr("class", "legend-item")
.style("display", "flex")
.style("align-items", "center")
.style("margin", "5px")
.merge(items)
.html(d => `<span style="background-color:${d.color}; width:16px; height:16px; margin-right:5px; display:inline-block; border-radius:50%;"></span>${d.label}`);
items.exit().remove();
}
function toggleSidePanel(content) {
console.log("toggleSidePanel triggered!");
const panel = d3.select("#side-panel");
const panelContent = d3.select("#panel-content");
if (panel.classed("show")) {
console.log("Closing Side Panel...");
panel.classed("show", false)
.style("right", "-350px"); //Move off-screen
setTimeout(() => {
panelContent.html(""); // Clear content when closing
}, 300);
} else {
console.log("Opening Side Panel...");
panelContent.html(content);
panel.classed("show", true)
.style("right", "0px"); //Bring on-screen
}
console.log("Panel classes before toggle:", panel.attr("class"));
}
function generatePanelContent(optype, step) {
let content = `<h3>${optype} Data</h3>`;
if (step === 1) {
content += `<p>Diagnosis breakdown for ${optype}:</p>`;
let total = surgeryData[optype] || 1;
let diagnoses = countDiagnoses(optype);
content += formatDiagnosisList(diagnoses, total);
}
else if (step === 2) {
content += `<p><strong>Cancer-related diagnoses:</strong></p>`;
let totalCancer = cancerData[optype] || 1;
let diagnoses = countDiagnoses(optype, true);
content += formatDiagnosisList(diagnoses, totalCancer);
}
else if (step === 3) {
content += `<p><strong>Gender-Specific Cancer Diagnoses</strong></p>`;
let maleDiagnoses = countDiagnosesByGender(optype, 'M');
let femaleDiagnoses = countDiagnosesByGender(optype, 'F');
content += `<h4>Men</h4>`;
content += formatDiagnosisListWithCounts(maleDiagnoses, genderData[optype]?.M || 1);
content += `<h4>Women</h4>`;
content += formatDiagnosisListWithCounts(femaleDiagnoses, genderData[optype]?.F || 1);
}
return content;
}
function countDiagnoses(optype, cancerOnly = false) {
if (!globalData.length) {
console.error("Global data is not loaded yet.");
return {};
}
let filteredData = globalData.filter(d => d.optype.replace(/\//g, "-") === optype);
if (cancerOnly) {
filteredData = filteredData.filter(d =>
/(cancer|carcinoma|malignant|blastoma|tumor|neoplasm|sarcoma|glioma|lymphoma|leukemia|melanoma|mesothelioma|myeloma|teratoma)/i.test(d.dx));
}
let diagnosisCount = {};
filteredData.forEach(d => {
diagnosisCount[d.dx] = (diagnosisCount[d.dx] || 0) + 1;
});
return diagnosisCount;
}
function countDiagnosesByGender(optype, gender) {
if (!globalData.length) {
console.error("Global data is not loaded yet.");
return {};
}
let filteredData = globalData.filter(d =>
d.optype.replace(/\//g, "-") === optype &&
d.sex === gender &&
/(cancer|carcinoma|malignant|blastoma|tumor|neoplasm|sarcoma|glioma|lymphoma|leukemia|melanoma|mesothelioma|myeloma|teratoma)/i.test(d.dx)
);
let diagnosisCount = {};
filteredData.forEach(d => {
diagnosisCount[d.dx] = (diagnosisCount[d.dx] || 0) + 1;
});
return diagnosisCount;
}
function formatDiagnosisListWithCounts(diagnoses, total) {
let content = "<ul>";
let sortedDiagnoses = Object.entries(diagnoses)
.map(([dx, count]) => ({
name: dx,
percentage: ((count / total) * 100).toFixed(2),
cases: count,
total: total
}))
.sort((a, b) => b.percentage - a.percentage);
sortedDiagnoses.forEach(d => {
content += `<li>${d.name}: ${d.percentage}% (${d.cases} cases out of ${d.total})</li>`;
});
content += "</ul>";
return content;
}
function formatDiagnosisList(diagnoses, total) {
let content = "<ul>";
// Convert object entries to an array, sort them by count in descending order
let sortedDiagnoses = Object.entries(diagnoses)
.map(([dx, count]) => ({
name: dx,
percentage: ((count / total) * 100).toFixed(2) // Calculate percentage with 2 decimals
}))
.sort((a, b) => b.percentage - a.percentage); // Sort in descending order
// Create the list items from the sorted array
sortedDiagnoses.forEach(d => {
content += `<li>${d.name}: ${d.percentage}%</li>`;
});
content += "</ul>";
return content;
}
// Add window resize handler
scroller.setup({
step: ".step",
offset: 0.5,
debug: false
}).onStepEnter(response => {
currentState = response.index;
// Ensure animation container exists within #center-container at the beginning
let animationContainer = d3.select("#main-container").select("#animation-container");
if (animationContainer.empty()) {
animationContainer = d3.select("#main-container")
.append("div")
.attr("id", "animation-container");
}
if (currentState === 0) {
d3.select("#side-panel").classed("show", false); // Ensure side panel is hidden on step 0
updateTitle(); // Ensure the title updates when going back to step 0
// Ensure the animation container is always displayed when returning to step 0
animationContainer
.interrupt()
.style("display", "flex")
.style("opacity", 1);
animationContainer.node().offsetHeight; // <-- Forces the browser to recognize the style change
animationContainer.transition()
.duration(800)
.style("opacity", 1)
.style("transition", "opacity 0.5s ease-inout");
// Re-trigger the animation on re-entry to step 0
d3.select("#animation-container").selectAll("*").remove(); // Clear any existing elements
animateScalpels("#animation-container");
animationContainer.transition()
.duration(800)
.style("opacity", 1);
d3.select("#visualization-wrapper")
.transition()
.duration(800)
.style("opacity", 0)
.style("pointer-events", "none");
d3.select("#animation-container")
.transition()
.duration(800)
.style("opacity", 1); // Ensure animation remains visible
}
else if (currentState === 1) {
animationContainer.transition()
.duration(800)
.style("opacity", 0)
.style("display", "none"); // Hides it but doesn't remove it
d3.select("#visualization-wrapper")
.transition()
.duration(500)
.style("opacity", 1)
.style("pointer-events", "auto");
} else {
// Ensure visualizations remain visible in later steps
d3.select("#visualization-wrapper").style("opacity", 1);
}
updateLegend(); // Ensure legend updates on every step change
if (currentState > 0) {
updateAll();
}
});
window.addEventListener("resize", scroller.resize);
});