แก้ตัวปิดบรรทัด

This commit is contained in:
Pitchaya Boonsarngsuk
2018-03-22 16:41:50 +00:00
parent b2f5993513
commit 7b322b3ea8

View File

@@ -1,409 +1,409 @@
// Get the width and heigh of the SVG element. // Get the width and heigh of the SVG element.
var width = +document.getElementById('svg').clientWidth, var width = +document.getElementById('svg').clientWidth,
height = +document.getElementById('svg').clientHeight; height = +document.getElementById('svg').clientHeight;
var svg = d3.select("svg") var svg = d3.select("svg")
.call(d3.zoom().scaleExtent([0.0001, 1000000]).on("zoom", function () { .call(d3.zoom().scaleExtent([0.0001, 1000000]).on("zoom", function () {
svg.attr("transform", d3.event.transform); svg.attr("transform", d3.event.transform);
})) }))
.append("g"); .append("g");
var div = d3.select("body").append("div") var div = d3.select("body").append("div")
.attr("class", "tooltip") .attr("class", "tooltip")
.style("opacity", 0); .style("opacity", 0);
var brush = d3.brush() var brush = d3.brush()
.extent([[-9999999, -9999999], [9999999, 9999999]]) .extent([[-9999999, -9999999], [9999999, 9999999]])
.on("end", brushEnded); .on("end", brushEnded);
svg.append("g") svg.append("g")
.attr("class", "brush") .attr("class", "brush")
.call(brush); .call(brush);
//var intercom = Intercom.getInstance(); //var intercom = Intercom.getInstance();
//intercom.on("select", unSelectNodes); //intercom.on("select", unSelectNodes);
var nodes, // as in Data points var nodes, // as in Data points
node, // as in SVG object that have all small circles on screen node, // as in SVG object that have all small circles on screen
props, props,
norm, norm,
p1 = 0, p1 = 0,
p2 = 0, p2 = 0,
size, size,
distanceFunction, distanceFunction,
simulation, simulation,
velocities = [], velocities = [],
rendering = true, // Rendering during the execution. rendering = true, // Rendering during the execution.
forceName = "forces", forceName = "forces",
springForce = false, springForce = false,
tooltipWidth = 0, tooltipWidth = 0,
fileName = "", fileName = "",
selectedData, selectedData,
clickedIndex = -1, clickedIndex = -1,
paused = false, paused = false,
alreadyRanIterations, alreadyRanIterations,
tweakedVerOfLink, tweakedVerOfLink,
manualStop = false; manualStop = false;
// Default parameters // Default parameters
var MULTIPLIER = 50, var MULTIPLIER = 50,
PERPLEXITY = 30, PERPLEXITY = 30,
LEARNING_RATE = 10, LEARNING_RATE = 10,
NEIGHBOUR_SIZE = 10, NEIGHBOUR_SIZE = 10,
SAMPLE_SIZE = 10, SAMPLE_SIZE = 10,
PIVOTS = false, PIVOTS = false,
NUM_PIVOTS = 3, NUM_PIVOTS = 3,
ITERATIONS = 300, ITERATIONS = 300,
FULL_ITERATIONS = 20, FULL_ITERATIONS = 20,
NODE_SIZE = 10, NODE_SIZE = 10,
COLOR_ATTRIBUTE = "", COLOR_ATTRIBUTE = "",
FULL_NEIGHBOUR_SIZE = 10, FULL_NEIGHBOUR_SIZE = 10,
FULL_SAMPLE_SIZE = 10, FULL_SAMPLE_SIZE = 10,
INTERP_ENDING_ITS = 20; INTERP_ENDING_ITS = 20;
// Create a color scheme for a range of numbers. // Create a color scheme for a range of numbers.
var color = d3.scaleOrdinal(d3.schemeCategory10); var color = d3.scaleOrdinal(d3.schemeCategory10);
$(document).ready(function() { $(document).ready(function() {
distanceFunction = calculateDistance; distanceFunction = calculateDistance;
d3.select('#startSimulation').on('click', startHybridSimulation); d3.select('#startSimulation').on('click', startHybridSimulation);
$("#HLParameters").show(); $("#HLParameters").show();
}); });
/** /**
* Parse the data from the provided csv file using Papa Parse library * Parse the data from the provided csv file using Papa Parse library
* @param {file} evt - csv file. * @param {file} evt - csv file.
*/ */
function parseFile(evt) { function parseFile(evt) {
// Clear the previous nodes // Clear the previous nodes
d3.selectAll(".nodes").remove(); d3.selectAll(".nodes").remove();
springForce = false; springForce = false;
fileName = evt.target.files[0].name; fileName = evt.target.files[0].name;
Papa.parse(evt.target.files[0], { Papa.parse(evt.target.files[0], {
header: true, header: true,
dynamicTyping: true, dynamicTyping: true,
skipEmptyLines: true, skipEmptyLines: true,
complete: function (results) { complete: function (results) {
processData(results.data, results.error); processData(results.data, results.error);
} }
}); });
} }
/** /**
* Process the data and pass it into D3 force simulation. * Process the data and pass it into D3 force simulation.
* @param {array} data * @param {array} data
* @param {object} error * @param {object} error
*/ */
function processData(data, error) { function processData(data, error) {
if (error) throw error.message; if (error) throw error.message;
nodes = data; nodes = data;
size = nodes.length; size = nodes.length;
simulation = d3.forceSimulation(); simulation = d3.forceSimulation();
// Calculate normalization parameters for distance fns // Calculate normalization parameters for distance fns
norm = calculateNormalization(nodes); norm = calculateNormalization(nodes);
props = Object.keys(nodes[0]); // Properties to consider by distance fn props = Object.keys(nodes[0]); // Properties to consider by distance fn
COLOR_ATTRIBUTE = props[props.length-1]; COLOR_ATTRIBUTE = props[props.length-1];
var opts = document.getElementById('color_attr').options; var opts = document.getElementById('color_attr').options;
props.forEach(function (d) { props.forEach(function (d) {
opts.add(new Option(d, d, (d === COLOR_ATTRIBUTE) ? true : false)); opts.add(new Option(d, d, (d === COLOR_ATTRIBUTE) ? true : false));
}); });
opts.selectedIndex = props.length-1; opts.selectedIndex = props.length-1;
//props.pop(); //Hide Iris index / last column from the distance function //props.pop(); //Hide Iris index / last column from the distance function
//Put the nodes at (0,0) //Put the nodes at (0,0)
nodes.forEach(function (d) { nodes.forEach(function (d) {
d.x = 0; d.x = 0;
d.y = 0; d.y = 0;
}); });
addNodesToDOM(nodes); addNodesToDOM(nodes);
// Pass the nodes to the D3 force simulation. // Pass the nodes to the D3 force simulation.
simulation simulation
.nodes(nodes) .nodes(nodes)
.stop(); .stop();
ticked(); ticked();
}; };
function addNodesToDOM(data) { function addNodesToDOM(data) {
node = svg.append("g") node = svg.append("g")
.attr("class", "nodes") .attr("class", "nodes")
.selectAll("circle") .selectAll("circle")
.data(data) .data(data)
.enter().append("circle") .enter().append("circle")
.attr("r", NODE_SIZE) .attr("r", NODE_SIZE)
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
// Color code the data points by a property (for Poker Hands, // Color code the data points by a property (for Poker Hands,
// it is a CLASS property). // it is a CLASS property).
.attr("fill", function (d) { .attr("fill", function (d) {
return color(d[COLOR_ATTRIBUTE]); return color(d[COLOR_ATTRIBUTE]);
}) })
.on("mouseover", function (d) { .on("mouseover", function (d) {
div.transition() div.transition()
.duration(200) .duration(200)
.style("opacity", .9); .style("opacity", .9);
div.html(formatTooltip(d)) div.html(formatTooltip(d))
.style("left", (d3.event.pageX) + "px") .style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - (15 * props.length)) + "px") .style("top", (d3.event.pageY - (15 * props.length)) + "px")
.style("width", (6 * tooltipWidth) + "px") .style("width", (6 * tooltipWidth) + "px")
.style("height", (14 * props.length) + "px"); .style("height", (14 * props.length) + "px");
highlightOnHover(d[COLOR_ATTRIBUTE]); highlightOnHover(d[COLOR_ATTRIBUTE]);
}) })
.on("mouseout", function (d) { .on("mouseout", function (d) {
div.transition() div.transition()
.duration(500) .duration(500)
.style("opacity", 0); .style("opacity", 0);
node.attr("opacity", 1); node.attr("opacity", 1);
}) })
.on("click", function (d) { .on("click", function (d) {
console.log("click", clickedIndex); console.log("click", clickedIndex);
if (clickedIndex !== d.index) { if (clickedIndex !== d.index) {
if (springForce) { if (springForce) {
highlightNeighbours(Array.from(simulation.force(forceName).nodeNeighbours(d.index).keys())); highlightNeighbours(Array.from(simulation.force(forceName).nodeNeighbours(d.index).keys()));
clickedIndex = d.index; clickedIndex = d.index;
} }
} else { } else {
node.attr("r", NODE_SIZE).attr("stroke-width", 0); node.attr("r", NODE_SIZE).attr("stroke-width", 0);
clickedIndex = -1; clickedIndex = -1;
} }
}); });
if (selectedData) if (selectedData)
unSelectNodes(selectedData); unSelectNodes(selectedData);
} }
function ticked() { function ticked() {
alreadyRanIterations++; alreadyRanIterations++;
// If rendering is selected, then draw at every iteration. // If rendering is selected, then draw at every iteration.
if (rendering === true) { if (rendering === true) {
node // Each sub-circle in the SVG, update cx and cy node // Each sub-circle in the SVG, update cx and cy
.attr("cx", function (d) { .attr("cx", function (d) {
return d.x*MULTIPLIER; return d.x*MULTIPLIER;
}) })
.attr("cy", function (d) { .attr("cy", function (d) {
return d.y*MULTIPLIER; return d.y*MULTIPLIER;
}); });
} }
// Legacy: Emit the distribution data to allow the drawing of the bar graph // Legacy: Emit the distribution data to allow the drawing of the bar graph
//if (springForce) { //if (springForce) {
// intercom.emit("passedData", simulation.force(forceName).distributionData()); // intercom.emit("passedData", simulation.force(forceName).distributionData());
//} //}
if(manualStop && alreadyRanIterations == ITERATIONS) { if(manualStop && alreadyRanIterations == ITERATIONS) {
ended(); ended();
} }
} }
function ended() { function ended() {
simulation.stop(); simulation.stop();
simulation.force(forceName, null); simulation.force(forceName, null);
if (rendering !== true) { // Never drawn anything before? Now it's time. if (rendering !== true) { // Never drawn anything before? Now it's time.
node node
.attr("cx", function (d) { .attr("cx", function (d) {
return d.x*MULTIPLIER; return d.x*MULTIPLIER;
}) })
.attr("cy", function (d) { .attr("cy", function (d) {
return d.y*MULTIPLIER; return d.y*MULTIPLIER;
}); });
} }
if (p1 !== 0) { if (p1 !== 0) {
// Performance time measurement // Performance time measurement
p2 = performance.now(); p2 = performance.now();
console.log("Execution time: " + (p2 - p1)); console.log("Execution time: " + (p2 - p1));
p1 = 0; p1 = 0;
p2 = 0; p2 = 0;
} }
} }
function brushEnded() { function brushEnded() {
var s = d3.event.selection, var s = d3.event.selection,
results = []; results = [];
if (s) { if (s) {
var x0 = s[0][0] - width / 2, var x0 = s[0][0] - width / 2,
y0 = s[0][1] - height / 2, y0 = s[0][1] - height / 2,
x1 = s[1][0] - width / 2, x1 = s[1][0] - width / 2,
y1 = s[1][1] - height / 2; y1 = s[1][1] - height / 2;
if (nodes) { if (nodes) {
var sel = node.filter(function (d) { var sel = node.filter(function (d) {
if (d.x > x0 && d.x < x1 && d.y > y0 && d.y < y1) { if (d.x > x0 && d.x < x1 && d.y > y0 && d.y < y1) {
return true; return true;
} }
return false; return false;
}).data(); }).data();
results = sel.map(function (a) { return a.index; }); results = sel.map(function (a) { return a.index; });
} }
//intercom.emit("select", { name: fileName, indices: results }); //intercom.emit("select", { name: fileName, indices: results });
d3.select(".brush").call(brush.move, null); d3.select(".brush").call(brush.move, null);
} }
} }
/** /**
* Format the tooltip for the data * Format the tooltip for the data
* @param {*} node * @param {*} node
*/ */
function formatTooltip(node) { function formatTooltip(node) {
var textString = "", var textString = "",
temp = ""; temp = "";
tooltipWidth = 0; tooltipWidth = 0;
props.forEach(function (element) { props.forEach(function (element) {
temp = element + ": " + node[element] + "<br/>"; temp = element + ": " + node[element] + "<br/>";
textString += temp; textString += temp;
if (temp.length > tooltipWidth) { if (temp.length > tooltipWidth) {
tooltipWidth = temp.length; tooltipWidth = temp.length;
} }
}); });
return textString; return textString;
} }
/** /**
* Halt the execution. * Halt the execution.
*/ */
function stopSimulation() { function stopSimulation() {
simulation.stop(); simulation.stop();
if (typeof hybridSimulation !== 'undefined') { if (typeof hybridSimulation !== 'undefined') {
hybridSimulation.stop(); hybridSimulation.stop();
} }
} }
/** /**
* Calculate the average values of the array. * Calculate the average values of the array.
* @param {array} array * @param {array} array
* @return {number} the mean of the array. * @return {number} the mean of the array.
*/ */
function getAverage(array) { function getAverage(array) {
console.log("getAverage", array); console.log("getAverage", array);
var total = 0; var total = 0;
for (var i = 0; i < array.length; i++) { for (var i = 0; i < array.length; i++) {
total += array[i]; total += array[i];
} }
return total / array.length; return total / array.length;
} }
/** /**
* Deselect the nodes to match the selection from other window. * Deselect the nodes to match the selection from other window.
* @param {*} data * @param {*} data
*/ */
function unSelectNodes(data) { function unSelectNodes(data) {
selectedData = data; selectedData = data;
if (fileName === data.name && nodes) { if (fileName === data.name && nodes) {
node node
.classed("notSelected", function (d) { .classed("notSelected", function (d) {
if (data.indices.indexOf(d.index) < 0) { if (data.indices.indexOf(d.index) < 0) {
return true; return true;
} }
return false; return false;
}); });
} }
} }
/** /**
* Highlight the neighbours for neighbour and sampling algorithm * Highlight the neighbours for neighbour and sampling algorithm
* @param {*} indices * @param {*} indices
*/ */
function highlightNeighbours(indices) { function highlightNeighbours(indices) {
node node
.attr("r", function (d) { .attr("r", function (d) {
if (indices.indexOf(d.index) >= 0) { if (indices.indexOf(d.index) >= 0) {
return NODE_SIZE * 2; return NODE_SIZE * 2;
} }
return NODE_SIZE; return NODE_SIZE;
}) })
.attr("stroke-width", function (d) { .attr("stroke-width", function (d) {
if (indices.indexOf(d.index) >= 0) { if (indices.indexOf(d.index) >= 0) {
return NODE_SIZE * 0.2 + "px"; return NODE_SIZE * 0.2 + "px";
} }
return "0px"; return "0px";
}) })
.attr("stroke", "white"); .attr("stroke", "white");
} }
/** /**
* Highlight all the nodes with the same class on hover * Highlight all the nodes with the same class on hover
* @param {*} highlighValue * @param {*} highlighValue
*/ */
function highlightOnHover(highlighValue) { function highlightOnHover(highlighValue) {
node.attr("opacity", function (d) { node.attr("opacity", function (d) {
return (highlighValue === d[COLOR_ATTRIBUTE]) ? 1 : 0.3; return (highlighValue === d[COLOR_ATTRIBUTE]) ? 1 : 0.3;
}); });
} }
/** /**
* Color the nodes according to given attribute. * Color the nodes according to given attribute.
*/ */
function colorToAttribute() { function colorToAttribute() {
node.attr("fill", function (d) { node.attr("fill", function (d) {
return color(d[COLOR_ATTRIBUTE]) return color(d[COLOR_ATTRIBUTE])
}); });
} }
/** /**
* Update the distance range. * Update the distance range.
function updateDistanceRange() { function updateDistanceRange() {
if (springForce) { if (springForce) {
simulation.force(forceName).distanceRange(SELECTED_DISTANCE); simulation.force(forceName).distanceRange(SELECTED_DISTANCE);
} }
} }
/** /**
* Implemented pause/resume functionality * Implemented pause/resume functionality
*/ */
function pauseUnPause() { function pauseUnPause() {
if (simulation) { if (simulation) {
if (paused) { if (paused) {
simulation.force(forceName); simulation.force(forceName);
simulation.restart(); simulation.restart();
d3.select("#pauseButton").text("Pause"); d3.select("#pauseButton").text("Pause");
paused = false; paused = false;
} else { } else {
simulation.stop(); simulation.stop();
d3.select("#pauseButton").text("Resume"); d3.select("#pauseButton").text("Resume");
paused = true; paused = true;
} }
} }
} }
/** /**
* Average distances for each node. * Average distances for each node.
* @param {*} dataNodes * @param {*} dataNodes
* @param {*} properties * @param {*} properties
* @param {*} normalization * @param {*} normalization
function calculateAverageDistance(dataNodes, properties, normalization) { function calculateAverageDistance(dataNodes, properties, normalization) {
var sum = 0, var sum = 0,
n = nodes.length; n = nodes.length;
for (var i = 0; i < n; i++) { for (var i = 0; i < n; i++) {
var sumNode = 0; var sumNode = 0;
for (var j = 0; j < n; j++) { for (var j = 0; j < n; j++) {
if (i !== j) { if (i !== j) {
sumNode += distanceFunction(nodes[i], nodes[j], properties, normalization); sumNode += distanceFunction(nodes[i], nodes[j], properties, normalization);
// console.log(sumNode); // console.log(sumNode);
} }
} }
sum += sumNode / (n - 1); sum += sumNode / (n - 1);
} }
return sum / n; return sum / n;
}*/ }*/