function createChart(finalJson) {
const root = d3.hierarchy(finalJson);
root.x0 = dy / 2;
root.y0 = 0;
root.descendants().forEach((d, i) => {
d.id = i;
d._children = d.children;
if (d.depth && d.data.name.length !== 7) d.children = null;
});
const svg = d3.create("svg")
.attr("viewBox", [-margin.left, -margin.top, width, dx])
.style("font", "25px sans-serif")
.style("user-select", "none");
const linkStrokeWidthBase = 3;
const gLink = svg.append("g")
.attr("fill", "none")
.attr("stroke-opacity", 0.7)
.attr("stroke-width", linkStrokeWidthBase);
const gNode = svg.append("g")
.attr("cursor", "pointer")
.attr("pointer-events", "all");
let idQueue = [];
function getImagesIdx(nodeData) {
console.log("data:", nodeData);
// }
}
function calculateAverageSimilarity(data) {
// console.log("similarity array:", data.similarity_score);
if (!data.similarity_score || data.similarity_score.length === 0) {
return 0;
}
const sum = data.similarity_score.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
const average = sum / data.similarity_score.length;
// console.log("similarity avg:", average);
return average;
}
const updateLinks = (node) => {
// Check if ID already exists in the queue
for (let i = 0; i < idQueue.length; i++) {
if (idQueue[i].node.id === node.id) {
// console.log(`ID ${node.id} already exists in the queue`);
return;
}
}
if (Array.isArray(node.data.children) && node.data.children.length === 0) {
return; // return if the node has an empty children array
}
// console.log(node.data)
// let imageIdxs = getImagesIdx(node.data);
let imageIdstoShow = null;
if (node.data.img_ids){
// console.log("data image ids: ", node.data.img_ids)
imageIdstoShow = node.data.img_ids
}else if(node.data.children){
imageIdstoShow = Array.from(new Set(node.data.children.reduce((acc, obj) => { return acc.concat(obj.img_ids); }, [])));
// console.log("data children: ", imageIdstoShow)
}
// console.log(node.data.labels);
if (imageIdstoShow === null) {
return;
}
// console.log("selected images: ", imageIdstoShow);
let imgTopic = getImgTid(node.data.name);
if (imgTopic === null) {
return;
}
//In this new version use image ID in the data
// Assign a color to new object based on the color of the previous object
let color;
let divTag;
if (idQueue.length === 0) {
color = "purple";
divTag = "app1";
} else if (idQueue[idQueue.length - 1].color === "purple") {
color = "red";
divTag = "app2";
} else {
color = "purple";
divTag = "app1";
}
// Add new object to queue
if (idQueue.length < 2) {
idQueue.push({ node: node, color: color, divTag: divTag });
} else {
// Replace oldest object with new object
idQueue[0] = idQueue[1];
idQueue[1] = { node: node, color: color, divTag: divTag };
}
gNode.selectAll("circle").attr("fill", d => {
const queueNode = idQueue.find(qNode => qNode.node.id === d.id); // find the corresponding node in idQueue
if (queueNode) {
return queueNode.color; // if node exists in idQueue, use its color
} else {
return d._children ? "#555" : "#999"; // otherwise, use default color
}
}).attr("r", d => {
const queueNode = idQueue.find(qNode => qNode.node.id === d.id); // find the corresponding node in idQueue
if (queueNode) {
return 10; // if node exists in idQueue, use its color
} else {
return 6; // otherwise, use the default size
}
});
let ancestors = null;
ancestors = node.ancestors();
// console.log(idQueue);
gLink.selectAll("path")
.filter(link => !(ancestors.includes(link.source) && ancestors.includes(link.target)))
.attr("stroke", node => {
// console.log("similarity scores:", calculateAverageSimilarity(node.target.data));
return node.target.data.similarity_score ?
simColorScale(calculateAverageSimilarity(node.target.data)) : avgColorScale(avgSimilarity[node.target.data.id]);
})
.attr("stroke-width", linkStrokeWidthBase)
.attr("stroke-opacity", 0.7);
for (let i = 0; i < idQueue.length; i++) {
// console.log(idQueue[i].node);
ancestors = idQueue[i].node.ancestors();
gLink.selectAll("path")
.filter(link => ancestors.includes(link.source) && ancestors.includes(link.target))
.attr("stroke-width", 6)
.attr("stroke-opacity", 1)
.attr("stroke", idQueue[i].color);
}
dispatch.call("circle-clicked", null, { id: imgTopic, tag: divTag, images:imageIdstoShow, labels: node.data.labels, color:color});
};
function update(source) {
const duration = d3.event && d3.event.altKey ? 2500 : 250;
const nodes = root.descendants().reverse();
const links = root.links();
// Compute the new tree layout.
tree(root);
let left = root;
let right = root;
root.eachBefore(node => {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
});
const height = right.x - left.x + margin.top + margin.bottom;
const transition = svg.transition()
.duration(duration)
.attr("viewBox", [-margin.left, left.x - margin.top, width, height])
.tween("resize", window.ResizeObserver ? null : () => () => svg.dispatch("toggle"));
// Update the nodes…
const node = gNode.selectAll("g")
.data(nodes, d => d.id);
// Enter any new nodes at the parent's previous position.
const nodeEnter = node.enter().append("g")
.attr("transform", d => `translate(${source.y0},${source.x0})`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0)
.on("click", (event, d) => {
// console.log(d.data.labels);
d.children = d.children ? null : d._children;
update(d);
// selectImage(d);
updateLinks(d);
});
nodeEnter.append("circle")
.attr("r", 6)
.attr("fill", d => d._children ? "#555" : "#999")
.attr("stroke-width", 15);
nodeEnter.append("text")
.attr("dy", "-0.31em")
.attr("x", -40)
.attr("text-anchor", "start")
.text(d => d.data.labels ? d.data.labels.slice(0, 2).join(', ') : "")
.clone(true).lower()
.attr("stroke-linejoin", "round")
.attr("stroke-width", 5)
.attr("stroke", "white");
// Add title element to show labels information
nodeEnter.append("title")
.text(d => {
let labelStr = d.data.labels ? d.data.labels.join(", ") : "";
let simStr = d.data.similarity_score ? "\nSimilarity: " + calculateAverageSimilarity(d.data) : "";
let imgTopicStr = d.data.img_tid ? ", Image Topic#: " + d.data.img_tid : "";
return labelStr + simStr + imgTopicStr;
});
// Transition nodes to their new position.
const nodeUpdate = node.merge(nodeEnter).transition(transition)
.attr("transform", d => `translate(${d.y},${d.x})`)
.attr("fill-opacity", 1)
.attr("stroke-opacity", 1);
// Transition exiting nodes to the parent's new position.
const nodeExit = node.exit().transition(transition).remove()
.attr("transform", d => `translate(${source.y},${source.x})`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0);
const diagonal = d3.linkHorizontal()
.x(d => d.y)
.y(d => d.x);
// Update the links…
const link = gLink.selectAll("path")
.data(links, d => d.target.id);
// Enter any new links at the parent's previous position.
const linkEnter = link.enter().append("path")
.attr("d", d => {
const o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
}).attr("stroke", d => d.target.data.similarity_score ?
simColorScale(calculateAverageSimilarity(d.target.data)) : avgColorScale(avgSimilarity[d.target.data.id]))
.attr("stroke-width", linkStrokeWidthBase)
.attr("fill", "none")
.attr("stroke-linejoin", "round");
// Transition links to their new position.
link.merge(linkEnter).transition(transition)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition(transition).remove()
.attr("d", d => {
const o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
});
// Stash the old positions for transition.
root.eachBefore(d => {
d.x0 = d.x;
d.y0 = d.y;
});
}
update(root);
// dispatchImg.on("img-clicked", (imageTopic) => {
// // console.log(imageTopic);
// });
return svg.node();
}