Init from given files
This commit is contained in:
commit
61f2be55fe
45 files changed
+34460
No files matched your search
@@ -0,0 +1,291 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
h1 {
|
||||
text-align: center;
|
||||
margin: 10px 0 10px 0;
|
||||
}
|
||||
|
||||
.links line {
|
||||
stroke: #999;
|
||||
stroke-opacity: 0.6;
|
||||
}
|
||||
/*.nodes circle {
|
||||
stroke: #fff;
|
||||
stroke-width: 1.5px;
|
||||
}*/
|
||||
|
||||
circle:hover {
|
||||
fill: #8B0000;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.notSelected {
|
||||
fill: #999;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.highlighted {
|
||||
fill: black;
|
||||
}
|
||||
|
||||
#svg {
|
||||
border-style: solid;
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
.left {
|
||||
float: left;
|
||||
width: 32%;
|
||||
}
|
||||
|
||||
.controls {
|
||||
flex-basis: 200px;
|
||||
padding: 0 5px;
|
||||
}
|
||||
|
||||
.controls input[type="range"] {
|
||||
margin: 0 5% 0.5em 5%;
|
||||
width: 90%;
|
||||
}
|
||||
|
||||
.multiplier {
|
||||
margin: 10px 0 10px 0;
|
||||
}
|
||||
|
||||
.parameters {
|
||||
margin: 10px 0 10px 30px;
|
||||
}
|
||||
|
||||
.checkbox {
|
||||
margin: 10px 0 10px 0;
|
||||
}
|
||||
|
||||
.start {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
div.tooltip {
|
||||
position: absolute;
|
||||
text-align: center;
|
||||
padding: 5px;
|
||||
font: 12px sans-serif;
|
||||
background: lightsteelblue;
|
||||
border: 0px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<body>
|
||||
<h1>Evaluation</h1>
|
||||
<svg id="svg" width="100%" height="600">
|
||||
<div class="left controls">
|
||||
|
||||
<div class="input">
|
||||
<input type="file" id="csv-file" name="files">
|
||||
</div>
|
||||
|
||||
<div class="multiplier">
|
||||
<label title="The size of the nodes">
|
||||
Node size
|
||||
<output id="nodeSizeSliderOutput">10</output>
|
||||
<input type="range" min="5" max="200" value="10" step="5" oninput="d3.select('#nodeSizeSliderOutput').text(value); NODE_SIZE=value; d3.selectAll('circle').attr('r', value)">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="The number that distance is multiplied by in order to improve the visibility of the graph">
|
||||
distanceMultiplier
|
||||
<output id="distanceMultiplierSliderOutput">50</output>
|
||||
<input type="range" min="5" max="1000" value="50" step="5" oninput="d3.select('#distanceMultiplierSliderOutput').text(value); MULTIPLIER=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="Number of iterations before the simulation is stopped">
|
||||
Iterations
|
||||
<output id="iterationsSliderOutput">300</output>
|
||||
<input type="range" min="5" max="5000" value="300" step="5" oninput="d3.select('#iterationsSliderOutput').text(value); ITERATIONS=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="Attribute used for coloring nodes">
|
||||
Color attribute
|
||||
<select id="color_attr" onchange="COLOR_ATTRIBUTE=value; colorToAttribute();">
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="checkbox">
|
||||
<label title="js/">
|
||||
Rendering
|
||||
<input type="checkbox" checked onclick="rendering=!rendering;">
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="start">
|
||||
<button id="startSimulation" form="algorithmForm">Start</button>
|
||||
<button id="pauseButton" onclick="pauseUnPause()">Pause</button>
|
||||
<button onclick="stopSimulation()">Stop</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="left">
|
||||
<p>Select algorithm:</p>
|
||||
<div id="algorithms">
|
||||
<input id="HLButton" type="radio" name="algorithm" onclick="d3.select('#startSimulation').on('click', startHybridSimulation)">Hybrid
|
||||
layout
|
||||
<br>
|
||||
<div id="HLParameters" class="parameters" style="display:none">
|
||||
<div id="pivots">
|
||||
<input id="BFButton" type="radio" name="pivots" checked="checked" onclick="PIVOTS=false;">Brute-force<br>
|
||||
<input id="PButton" type="radio" name="pivots" onclick="PIVOTS=true;">Pivots<br>
|
||||
<div id="numPivots" class="parameters" style="display:none">
|
||||
<label title="The number of pivots">
|
||||
Number of Pivots
|
||||
<output id="numPivotsSliderOutput">3</output><br/>
|
||||
<input type="range" min="1" max="50" value="3" step="1" oninput="d3.select('#numPivotsSliderOutput').text(value); NUM_PIVOTS=value;">
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<br/>
|
||||
<label title="Number of iterations done at the end">
|
||||
Full iterations
|
||||
<output id="fullIterationsSliderOutput">20</output><br/>
|
||||
<input type="range" min="1" max="100" value="20" step="1" oninput="d3.select('#fullIterationsSliderOutput').text(value); FULL_ITERATIONS=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="NeighbourSize">
|
||||
Neighbour Set
|
||||
<output id="hlneighbourSizeSliderOutput">6</output><br/>
|
||||
<input type="range" min="1" max="100" value="6" step="1" oninput="d3.select('#hlneighbourSizeSliderOutput').text(value); NEIGHBOUR_SIZE=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="SampleSize">
|
||||
Sample Set
|
||||
<output id="hlsampleSizeSliderOutput">3</output><br/>
|
||||
<input type="range" min="1" max="100" value="3" step="1" oninput="d3.select('#hlsampleSizeSliderOutput').text(value); SAMPLE_SIZE=value;">
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<input id="NSButton" type="radio" name="algorithm" onclick="d3.select('#startSimulation').on('click', startNeighbourSamplingSimulation)">Neighbour
|
||||
and Sampling<br>
|
||||
<div id="NSParameters" class="parameters" style="display:none">
|
||||
<label title="NeighbourSize">
|
||||
Neighbour Set
|
||||
<output id="neighbourSizeSliderOutput">6</output><br/>
|
||||
<input type="range" min="1" max="100" value="6" step="1" oninput="d3.select('#neighbourSizeSliderOutput').text(value); NEIGHBOUR_SIZE=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="SampleSize">
|
||||
Sample Set
|
||||
<output id="sampleSizeSliderOutput">3</output><br/>
|
||||
<input type="range" min="1" max="100" value="3" step="1" oninput="d3.select('#sampleSizeSliderOutput').text(value); SAMPLE_SIZE=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="DistanceRange">
|
||||
Distance Range
|
||||
<output id="distanceRangeSliderOutput">10</output><br/>
|
||||
<input type="range" min="1" max="100" value="10" step="1" oninput="d3.select('#distanceRangeSliderOutput').text(value); SELECTED_DISTANCE=value;">
|
||||
</label>
|
||||
</div>
|
||||
<input class="noParameters" type="radio" name="algorithm" onclick="d3.select('#startSimulation').on('click', startLinkSimulation)">Link
|
||||
force in D3<br>
|
||||
<input class="noParameters" type="radio" name="algorithm" onclick="d3.select('#startSimulation').on('click', startBarnesHutSimulation)">Barnes-Hut<br>
|
||||
<input id="tSNEButton" type="radio" name="algorithm" onclick="d3.select('#startSimulation').on('click', starttSNE)">t-SNE<br>
|
||||
<div id="tSNEParameters" class="parameters" style="display:none">
|
||||
<label title="Perplexity">
|
||||
Perplexity
|
||||
<output id="perplexitySliderOutput">30</output><br/>
|
||||
<input type="range" min="1" max="500" value="30" step="1" oninput="d3.select('#perplexitySliderOutput').text(value); PERPLEXITY=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="LearningRate">
|
||||
Learning Rate
|
||||
<output id="learningRateSliderOutput">10</output><br/>
|
||||
<input type="range" min="1" max="500" value="10" step="1" oninput="d3.select('#learningRateSliderOutput').text(value); LEARNING_RATE=value;">
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="left">
|
||||
<p>Select distance function:</p>
|
||||
<div id="distance">
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateDistance"> General<br>
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateEuclideanDistance"> Euclidean<br>
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateManhattanDistance"> Manhattan<br>
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateJaccardDissimilarity"> Jaccard<br>
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateDiceDissimilarity"> Dice<br>
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateCosineSimilarity"> Cosine<br>
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateDistancePoker"> Poker Hands<br>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</svg>
|
||||
</body>
|
||||
|
||||
<!-- Load the files and libraries used. -->
|
||||
<script src="js/lib/d3.v4.min.js"></script>
|
||||
<script src="js/lib/papaparse.js"></script>
|
||||
<script src="js/lib/jquery-3.1.1.js"></script>
|
||||
<script src="js/lib/intercom.js"></script>
|
||||
<script src="../build/d3-neighbour-sampling.js"></script>
|
||||
<script src="js/src/neighbourSampling-papaparsing.js"></script>
|
||||
<script src="js/distances/distancePokerHands.js"></script>
|
||||
<script src="js/distances/distance.js"></script>
|
||||
<script src="js/distances/euclideanDistance.js"></script>
|
||||
<script src="js/distances/euclideanDistanceInTSNE.js"></script>
|
||||
<script src="js/distances/manhattanDistance.js"></script>
|
||||
<script src="js/distances/jaccardDissimilarity.js"></script>
|
||||
<script src="js/distances/diceDissimilarity.js"></script>
|
||||
<script src="js/distances/cosineSimilarity.js"></script>
|
||||
<script src="js/distances/normalization.js"></script>
|
||||
<script src="js/distances/numeric.js"></script>
|
||||
|
||||
|
||||
<script>
|
||||
$(document).ready(function () {
|
||||
$("#csv-file").change(function (d) {
|
||||
parseFile(d);
|
||||
$("#color_attr option").remove();
|
||||
$("#pauseButton").text("Pause");
|
||||
paused = false;
|
||||
});
|
||||
|
||||
$("#startSimulation").click(function () {
|
||||
$("#pauseButton").text("Pause");
|
||||
paused = false;
|
||||
});
|
||||
|
||||
$("#tSNEButton").click(function () {
|
||||
$(".parameters").hide();
|
||||
$("#tSNEParameters").show();
|
||||
});
|
||||
|
||||
$("#NSButton").click(function () {
|
||||
$(".parameters").hide();
|
||||
$("#NSParameters").show();
|
||||
});
|
||||
|
||||
$("#HLButton").click(function () {
|
||||
$(".parameters").hide();
|
||||
$("#HLParameters").show();
|
||||
if ($("#PButton").is(":checked")) {
|
||||
$("#numPivots").show();
|
||||
}
|
||||
});
|
||||
|
||||
$("#BFButton").click(function () {
|
||||
$("#numPivots").hide();
|
||||
});
|
||||
|
||||
$("#PButton").click(function () {
|
||||
$("#numPivots").show();
|
||||
});
|
||||
|
||||
$(".noParameters").click(function () {
|
||||
$(".parameters").hide();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,110 @@
|
||||
<!DOCTYPE html>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
/* set the CSS */
|
||||
/* .line {
|
||||
fill: none;
|
||||
stroke: steelblue;
|
||||
stroke-width: 2px;
|
||||
} */
|
||||
|
||||
.chart rect {
|
||||
fill: steelblue;
|
||||
stroke: none;
|
||||
}
|
||||
|
||||
text {
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<body>
|
||||
<!-- <svg width="960" height="600"></svg> -->
|
||||
<!-- load the d3.js library -->
|
||||
<svg class="chart"></svg>
|
||||
<script src="https://d3js.org/d3.v4.min.js"></script>
|
||||
<script src="js/lib/intercom.js"></script>
|
||||
<script>
|
||||
var data,
|
||||
xDomain,
|
||||
yDomain;
|
||||
|
||||
var intercom = Intercom.getInstance();
|
||||
intercom.on("passedData", function (d) {
|
||||
data = [];
|
||||
var tmp = d.distribution;
|
||||
for (var i = 0; i < d.l; i++) {
|
||||
data.push({"index": i, "size": tmp[i]});
|
||||
}
|
||||
xDomain = d.l;
|
||||
yDomain = d.maxSize;
|
||||
showData(data);
|
||||
});
|
||||
|
||||
// set the dimensions and margins of the graph
|
||||
var margin = { top: 20, right: 20, bottom: 90, left: 70 },
|
||||
width = 1500 - margin.left - margin.right,
|
||||
height = 600 - margin.top - margin.bottom;
|
||||
|
||||
// append the svg obgect to the body of the page
|
||||
// appends a 'group' element to 'svg'
|
||||
// moves the 'group' element to the top left margin
|
||||
var chart = d3.select(".chart")
|
||||
.attr("width", width + margin.left + margin.right)
|
||||
.attr("height", height + margin.top + margin.bottom)
|
||||
.append("g")
|
||||
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
|
||||
|
||||
function showData(data) {
|
||||
|
||||
d3.selectAll(".bar").remove();
|
||||
d3.selectAll(".xAxis").remove();
|
||||
d3.selectAll(".yAxis").remove();
|
||||
|
||||
// set the ranges
|
||||
var x = d3.scaleLinear().range([0, width]).domain([0, xDomain]);
|
||||
var y = d3.scaleLinear().range([height, 0]).domain([0, yDomain]);
|
||||
|
||||
var barWidth = width / data.length;
|
||||
|
||||
// Add the X Axis
|
||||
chart.append("g")
|
||||
.attr("class", "xAxis")
|
||||
.attr("transform", "translate(0," + height + ")")
|
||||
.call(d3.axisBottom(x));
|
||||
|
||||
// Add the Y Axis
|
||||
chart.append("g")
|
||||
.attr("class", "yAxis")
|
||||
.call(d3.axisLeft(y));
|
||||
|
||||
chart.selectAll(".bar")
|
||||
.data(data)
|
||||
.enter().append("rect")
|
||||
.attr("class", "bar")
|
||||
.attr("x", function (d) { return x(d.index); })
|
||||
.attr("y", function (d) { return y(d.size); })
|
||||
.attr("height", function (d) { return height - y(d.size); })
|
||||
.attr("width", barWidth);
|
||||
}
|
||||
|
||||
// Add x axis label
|
||||
chart.append("text")
|
||||
.attr("transform",
|
||||
"translate(" + (width / 2) + " ," +
|
||||
(height + margin.top + 30) + ")")
|
||||
.style("text-anchor", "middle")
|
||||
.style("font-size", "22px")
|
||||
.text("Points");
|
||||
|
||||
// Add y axis label
|
||||
chart.append("text")
|
||||
.attr("transform", "rotate(-90)")
|
||||
.attr("y", 0 - margin.left)
|
||||
.attr("x", 0 - (height / 2))
|
||||
.attr("dy", "1em")
|
||||
.style("text-anchor", "middle")
|
||||
.style("font-size", "22px")
|
||||
.text("Number of neighbours");
|
||||
</script>
|
||||
</body>
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Calculate the distances by using the numbers, strings and dates.
|
||||
* @param {node} source
|
||||
* @param {node} target
|
||||
* @param {array} properties - the properties of the nodes.
|
||||
* @return {number} the distance between source and target nodes.
|
||||
*/
|
||||
function calculateCosineSimilarity(source, target, properties, normArgs) {
|
||||
var numerator = 0.0;
|
||||
|
||||
// console.log(properties);
|
||||
// Iterate through every column of data
|
||||
for (var i = 0; i < properties.length; i++) {
|
||||
property = properties[i];
|
||||
if (property.toLowerCase() !== "class" && property.toLowerCase() !== "app" && property.toLowerCase() !== "user" && property.toLowerCase() !== "weekday") {
|
||||
var s = source[property],
|
||||
t = target[property];
|
||||
|
||||
numerator += s * t;
|
||||
}
|
||||
}
|
||||
|
||||
let denominator = squareRooted(source, properties, normArgs) * squareRooted(target, properties, normArgs);
|
||||
|
||||
// console.log(Math.abs(numerator / denominator));
|
||||
return Math.abs(numerator / denominator);
|
||||
}
|
||||
|
||||
function squareRooted(node, properties, normArgs) {
|
||||
var sum = 0.0;
|
||||
|
||||
for (var i = 0, s; i < properties.length; i++) {
|
||||
var s = node[properties[i]];
|
||||
|
||||
sum += s * s;
|
||||
}
|
||||
|
||||
return Math.sqrt(sum);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Calculate the distances by using the numbers, strings and dates.
|
||||
* @param {node} source
|
||||
* @param {node} target
|
||||
* @param {array} properties - the properties of the nodes.
|
||||
* @return {number} the distance between source and target nodes.
|
||||
*/
|
||||
function calculateDiceDissimilarity(source, target, properties, normArgs) {
|
||||
var notShared = 0.0;
|
||||
|
||||
// console.log(properties);
|
||||
// Iterate through every column of data
|
||||
for (var i = 0; i < properties.length; i++) {
|
||||
property = properties[i];
|
||||
if (property.toLowerCase() !== "class" && property.toLowerCase() !== "app" && property.toLowerCase() !== "user" && property.toLowerCase() !== "weekday") {
|
||||
var s = source[property],
|
||||
t = target[property];
|
||||
|
||||
if (s !== t) {
|
||||
notShared++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// console.log(Math.sqrt(sumDiff)/cols);
|
||||
// console.log(cols);
|
||||
return notShared / (notShared + 2 * (properties.length - notShared));
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Calculate the distances by using the numbers, strings and dates.
|
||||
* @param {node} source
|
||||
* @param {node} target
|
||||
* @param {array} properties - the properties of the nodes.
|
||||
* @param {object} normArgs - the normalization arguments.
|
||||
* @return {number} the distance between source and target nodes.
|
||||
*/
|
||||
function calculateDistance(source, target, properties, normArgs) {
|
||||
var val1 = 0.0, val2 = 0.0,
|
||||
sumDiff = 0.0,
|
||||
ordDiff = 1.0,
|
||||
ORD_FACTOR = 0.75,
|
||||
cols = 0,
|
||||
average = normArgs.avg,
|
||||
sigma = normArgs.sig,
|
||||
st_dev = normArgs.st_d;
|
||||
|
||||
// Iterate through every column of data
|
||||
for (var i = 0; i < properties.length; i++) {
|
||||
property = properties[i];
|
||||
if (source.hasOwnProperty(property) && target.hasOwnProperty(property)
|
||||
&& property.toLowerCase() !== "index" ) {
|
||||
var s = source[property],
|
||||
t = target[property];
|
||||
|
||||
// Comparing Floats and Integers
|
||||
if ((isNumeric(s) && isNumeric(t))) {
|
||||
val1 = parseFloat(s);
|
||||
val2 = parseFloat(t);
|
||||
if (sigma[i] != 0) {
|
||||
val1 = (val1 - average[i]) / (st_dev[i] * sigma[i]);
|
||||
val2 = (val2 - average[i]) / (st_dev[i] * sigma[i]);
|
||||
}
|
||||
sumDiff += (val1-val2) * (val1-val2);
|
||||
cols++;
|
||||
// Comparing strings
|
||||
} else if (/[a-zA-Z]/.test(s) && /[a-zA-Z]/.test(t) && s === t) {
|
||||
ordDiff *= ORD_FACTOR;
|
||||
cols++;
|
||||
} else {
|
||||
// Comparing Dates
|
||||
var parsedDateS = Date.parse(s);
|
||||
var parsedDateT = Date.parse(t);
|
||||
if (isNaN(s) && !isNaN(parsedDateS)
|
||||
&& isNaN(t) && !isNaN(parsedDateT)) {
|
||||
|
||||
val1 = parsedDateS.valueOf(),
|
||||
val2 = parsedDateT.valueOf();
|
||||
|
||||
if (sigma[i] !== 0) {
|
||||
val1 = (val1 - average[i]) / (st_dev[i] * sigma[i]);
|
||||
val2 = (val2 - average[i]) / (st_dev[i] * sigma[i]);
|
||||
}
|
||||
sumDiff += (val1-val2) * (val1-val2);
|
||||
cols++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sumDiff = Math.sqrt(sumDiff);
|
||||
sumDiff *= ordDiff;
|
||||
|
||||
if (cols > 0) {
|
||||
sumDiff *= properties.length/cols;
|
||||
}
|
||||
|
||||
console.log(sumDiff);
|
||||
return sumDiff;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* The distance function that is specifically made for Poker Hands data set.
|
||||
* The suit of the cards does not play an important role when finding
|
||||
* the differences in poker hands so it was not used in calculations.
|
||||
* @param {node} source
|
||||
* @param {node} target
|
||||
* @return {number} the distance between source and target nodes.
|
||||
*/
|
||||
function calculateDistancePoker(source, target) {
|
||||
var sumDiff = 0.0,
|
||||
ordDiff = 1.0,
|
||||
ORD_FACTOR = 1.5,
|
||||
cards = ["C1", "C2", "C3", "C4", "C5"],
|
||||
cols = 0;
|
||||
|
||||
// Iterate through cards
|
||||
for (var i = 0; i < cards.length; i++) {
|
||||
card = cards[i];
|
||||
if (source.hasOwnProperty(card) && target.hasOwnProperty(card)) {
|
||||
var s = parseInt(source[card]),
|
||||
t = parseInt(target[card]);
|
||||
// Calculate the squared difference.
|
||||
sumDiff += (s-t) * (s-t);
|
||||
}
|
||||
}
|
||||
|
||||
// Class of poker hands describes the similarities the best
|
||||
// so give it more priority than checking the differences between cards.
|
||||
if (source.hasOwnProperty("CLASS") && target.hasOwnProperty("CLASS")) {
|
||||
var s = parseInt(source["CLASS"]),
|
||||
t = parseInt(target["CLASS"]);
|
||||
|
||||
// If classes differ, then scale them by a factor.
|
||||
if (s !== t) {
|
||||
ordDiff *= (ORD_FACTOR * (Math.abs(s-t)))
|
||||
}
|
||||
}
|
||||
|
||||
sumDiff = Math.sqrt(sumDiff);
|
||||
sumDiff *= ordDiff;
|
||||
|
||||
return sumDiff;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Calculate the distances by using the numbers, strings and dates.
|
||||
* @param {node} source
|
||||
* @param {node} target
|
||||
* @param {array} properties - the properties of the nodes.
|
||||
* @return {number} the distance between source and target nodes.
|
||||
*/
|
||||
function calculateEuclideanDistance(source, target, properties, normArgs) {
|
||||
var sumDiff = 0.0;
|
||||
|
||||
// console.log(normArgs);
|
||||
// Iterate through every column of data
|
||||
for (var i = 0; i < properties.length; i++) {
|
||||
property = properties[i];
|
||||
if (property.toLowerCase() !== "class" && property.toLowerCase() !== "app" && property.toLowerCase() !== "user" && property.toLowerCase() !== "weekday") {
|
||||
var s = source[property],
|
||||
t = target[property];
|
||||
|
||||
if (normArgs.sig[i] !== 0) {
|
||||
s = (s - normArgs.avg[i]) / (2.0 * normArgs.sig[i]);
|
||||
t = (t - normArgs.avg[i]) / (2.0 * normArgs.sig[i]);
|
||||
}
|
||||
sumDiff += (s - t) * (s - t);
|
||||
}
|
||||
}
|
||||
|
||||
// console.log(Math.sqrt(sumDiff)/cols);
|
||||
// console.log(cols);
|
||||
// sumDiff = Math.sqrt(sumDiff);
|
||||
// console.log(sumDiff);
|
||||
return Math.sqrt(sumDiff);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Calculate the distances by using the numbers, strings and dates.
|
||||
* @param {node} source
|
||||
* @param {node} target
|
||||
* @param {array} properties - the properties of the nodes.
|
||||
* @return {number} the distance between source and target nodes.
|
||||
*/
|
||||
function calculateEuclideanDistanceTSNE(source, target, properties, normArgs) {
|
||||
var dotProduct = 0.0,
|
||||
sumX = 0.0,
|
||||
sumY = 0.0;
|
||||
|
||||
// console.log(normArgs);
|
||||
// Iterate through every column of data
|
||||
for (var i = 0; i < properties.length; i++) {
|
||||
property = properties[i];
|
||||
if (source.hasOwnProperty(property) && target.hasOwnProperty(property) &&
|
||||
property.toLowerCase() !== "class") {
|
||||
var s = source[property],
|
||||
t = target[property];
|
||||
|
||||
dotProduct += s * t;
|
||||
|
||||
sumX += s * s;
|
||||
sumY += t * t;
|
||||
}
|
||||
}
|
||||
|
||||
// console.log("Dot", dotProduct);
|
||||
// console.log((-2 * dotProduct) + sumX + sumY);
|
||||
|
||||
return -2 * dotProduct + sumX + sumY;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Calculate the distances by using the numbers, strings and dates.
|
||||
* @param {node} source
|
||||
* @param {node} target
|
||||
* @param {array} properties - the properties of the nodes.
|
||||
* @return {number} the distance between source and target nodes.
|
||||
*/
|
||||
function calculateJaccardDissimilarity(source, target, properties, normArgs) {
|
||||
var notShared = 0.0;
|
||||
|
||||
// console.log(properties);
|
||||
// Iterate through every column of data
|
||||
for (var i = 0; i < properties.length; i++) {
|
||||
property = properties[i];
|
||||
if (property.toLowerCase() !== "class" && property.toLowerCase() !== "app" && property.toLowerCase() !== "user" && property.toLowerCase() !== "weekday") {
|
||||
var s = source[property],
|
||||
t = target[property];
|
||||
|
||||
if (s !== t) {
|
||||
notShared++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// console.log(Math.sqrt(sumDiff)/cols);
|
||||
// console.log(cols);
|
||||
return notShared / properties.length;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Calculate the distances by using the numbers, strings and dates.
|
||||
* @param {node} source
|
||||
* @param {node} target
|
||||
* @param {array} properties - the properties of the nodes.
|
||||
* @return {number} the distance between source and target nodes.
|
||||
*/
|
||||
function calculateManhattanDistance(source, target, properties, normArgs) {
|
||||
var sum = 0.0,
|
||||
cols = 0;
|
||||
|
||||
// console.log(properties);
|
||||
// Iterate through every column of data
|
||||
for (var i = 0; i < properties.length; i++) {
|
||||
property = properties[i];
|
||||
if (property.toLowerCase() !== "class" && property.toLowerCase() !== "app" && property.toLowerCase() !== "user" && property.toLowerCase() !== "weekday") {
|
||||
var s = source[property],
|
||||
t = target[property];
|
||||
|
||||
if (s !== t) {
|
||||
cols++;
|
||||
}
|
||||
|
||||
if (normArgs.sig[i] !== 0) {
|
||||
s = (s - normArgs.avg[i]) / (2.0 * normArgs.sig[i]);
|
||||
t = (t - normArgs.avg[i]) / (2.0 * normArgs.sig[i]);
|
||||
}
|
||||
sum += Math.abs(s - t);
|
||||
}
|
||||
}
|
||||
|
||||
// console.log(Math.sqrt(sumDiff)/cols);
|
||||
return sum * (cols / properties.length);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Calculate the values that are used for normalizing the data.
|
||||
* @param {array} nodes
|
||||
* @return {object} that contains the normalization parameters.
|
||||
*/
|
||||
function calculateNormalization(nodes) {
|
||||
var STANDARD_DEV = 2.0,
|
||||
properties = Object.keys(nodes[0]),
|
||||
sums = calculateSums(nodes, properties),
|
||||
average = [],
|
||||
sigma = [];
|
||||
|
||||
// For each property, calculate mean and sigma.
|
||||
for (var i = 0; i < properties.length; i++) {
|
||||
var avg = sums.sumOfVal[i] / nodes.length;
|
||||
average[i] = avg;
|
||||
sigma[i] = Math.sqrt((sums.sumOfSq[i] - (nodes.length * Math.pow(avg, 2))) / nodes.length);
|
||||
}
|
||||
return {
|
||||
avg: average,
|
||||
sig: sigma,
|
||||
st_d: standardDevation(nodes, properties, average)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
function standardDevation(nodes, properties, avg) {
|
||||
|
||||
var stDev = new Array(properties.length).fill(0)
|
||||
|
||||
for (var i = 0; i < properties.length; i++) {
|
||||
var sum = 0;
|
||||
|
||||
nodes.forEach(function (node) {
|
||||
var val = node[properties[i]];
|
||||
var parsedDate = Date.parse(val);
|
||||
var propAvg = avg[i];
|
||||
|
||||
if (isNaN(val) && !isNaN(parsedDate)) {
|
||||
val = parsedDate.valueOf();
|
||||
} else if (isNumeric(val)) {
|
||||
val = parseFloat(val);
|
||||
// Ignore the strings.
|
||||
} else {
|
||||
val = 0;
|
||||
}
|
||||
|
||||
sum += Math.pow(val - propAvg, 2);
|
||||
});
|
||||
|
||||
stDev[i] = Math.sqrt(sum/nodes.length);
|
||||
}
|
||||
|
||||
return stDev;
|
||||
|
||||
}
|
||||
|
||||
// Calculate the sum of values and the squared sum
|
||||
/**
|
||||
* Calculate the sums of each property.
|
||||
* @param {array} nodes
|
||||
* @param {array} properties - list of properties
|
||||
* @return {object} that contains arrays with sum of values
|
||||
* and the squared sums.
|
||||
*/
|
||||
function calculateSums(nodes, properties) {
|
||||
var sumOfValues = new Array(properties.length).fill(0),
|
||||
sumOfSquares = new Array(properties.length).fill(0);
|
||||
|
||||
// Calculate the sums for each node.
|
||||
nodes.forEach(function (node) {
|
||||
for (var i = 0; i < properties.length; i++) {
|
||||
var val = node[properties[i]];
|
||||
var parsedDate = Date.parse(val);
|
||||
|
||||
if (isNaN(val) && !isNaN(parsedDate)) {
|
||||
sumOfValues[i] += parsedDate.valueOf();
|
||||
sumOfSquares[i] += Math.pow(parsedDate.valueOf(), 2);
|
||||
} else if (isNumeric(val)) {
|
||||
sumOfValues[i] += parseFloat(val);
|
||||
sumOfSquares[i] += Math.pow(parseFloat(val), 2);
|
||||
// Ignore the strings.
|
||||
} else {
|
||||
sumOfValues[i] += 0;
|
||||
sumOfSquares[i] += 0;
|
||||
}
|
||||
}
|
||||
});
|
||||
return {
|
||||
sumOfVal: sumOfValues,
|
||||
sumOfSq: sumOfSquares
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Check if the object (string, number, etc.) contains a number.
|
||||
* @param {object} n - object to check.
|
||||
* @return {Boolean} true, if it is a number, false otherwise.
|
||||
*/
|
||||
function isNumeric(n) {
|
||||
return !isNaN(parseFloat(n)) && isFinite(n);
|
||||
}
|
||||
Vendored
+16866
File diff suppressed because it is too large.
Load diff
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
// https://d3js.org Version 4.3.0. Copyright 2016 Mike Bostock.
|
||||
(function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(t.d3=t.d3||{})})(this,function(t){"use strict";function n(t){return function(n,e){return Ms(t(n),e)}}function e(t,n,e){var r=Math.abs(n-t)/Math.max(0,e),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),o=r/i;return o>=Fs?i*=10:o>=Is?i*=5:o>=Ys&&(i*=2),n<t?-i:i}function r(t){return t.length}function i(){}function o(t,n){var e=new i;if(t instanceof i)t.each(function(t,n){e.set(n,t)});else if(Array.isArray(t)){var r,o=-1,u=t.length;if(null==n)for(;++o<u;)e.set(o,t[o]);else for(;++o<u;)e.set(n(r=t[o],o,t),r)}else if(t)for(var a in t)e.set(a,t[a]);return e}function u(){return{}}function a(t,n,e){t[n]=e}function c(){return o()}function s(t,n,e){t.set(n,e)}function f(){}function l(t,n){var e=new f;if(t instanceof f)t.each(function(t){e.add(t)});else if(t){var r=-1,i=t.length;if(null==n)for(;++r<i;)e.add(t[r]);else for(;++r<i;)e.add(n(t[r],r,t))}return e}function h(t){return+t}function p(t){return t*t}function d(t){return t*(2-t)}function v(t){return((t*=2)<=1?t*t:--t*(2-t)+1)/2}function _(t){return t*t*t}function y(t){return--t*t*t+1}function g(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}function m(t){return 1-Math.cos(t*Tf)}function x(t){return Math.sin(t*Tf)}function b(t){return(1-Math.cos(Mf*t))/2}function w(t){return Math.pow(2,10*t-10)}function M(t){return 1-Math.pow(2,-10*t)}function T(t){return((t*=2)<=1?Math.pow(2,10*t-10):2-Math.pow(2,10-10*t))/2}function N(t){return 1-Math.sqrt(1-t*t)}function k(t){return Math.sqrt(1- --t*t)}function S(t){return((t*=2)<=1?1-Math.sqrt(1-t*t):Math.sqrt(1-(t-=2)*t)+1)/2}function A(t){return 1-E(1-t)}function E(t){return(t=+t)<Nf?Lf*t*t:t<Sf?Lf*(t-=kf)*t+Af:t<Cf?Lf*(t-=Ef)*t+zf:Lf*(t-=Pf)*t+qf}function C(t){return((t*=2)<=1?1-E(1-t):E(t-1)+1)/2}function z(t,n){return t[0]-n[0]||t[1]-n[1]}function P(t){for(var n=t.length,e=[0,1],r=2,i=2;i<n;++i){for(;r>1&&Wf(t[e[r-2]],t[e[r-1]],t[i])<=0;)--r;e[r++]=i}return e.slice(0,r)}function q(){this._x0=this._y0=this._x1=this._y1=null,this._=[]}function L(){return new q}function R(t,n,e,r){if(isNaN(n)||isNaN(e))return t;var i,o,u,a,c,s,f,l,h,p=t._root,d={data:r},v=t._x0,_=t._y0,y=t._x1,g=t._y1;if(!p)return t._root=d,t;for(;p.length;)if((s=n>=(o=(v+y)/2))?v=o:y=o,(f=e>=(u=(_+g)/2))?_=u:g=u,i=p,!(p=p[l=f<<1|s]))return i[l]=d,t;if(a=+t._x.call(null,p.data),c=+t._y.call(null,p.data),n===a&&e===c)return d.next=p,i?i[l]=d:t._root=d,t;do i=i?i[l]=new Array(4):t._root=new Array(4),(s=n>=(o=(v+y)/2))?v=o:y=o,(f=e>=(u=(_+g)/2))?_=u:g=u;while((l=f<<1|s)===(h=(c>=u)<<1|a>=o));return i[h]=p,i[l]=d,t}function U(t){var n,e,r,i,o=t.length,u=new Array(o),a=new Array(o),c=1/0,s=1/0,f=-(1/0),l=-(1/0);for(e=0;e<o;++e)isNaN(r=+this._x.call(null,n=t[e]))||isNaN(i=+this._y.call(null,n))||(u[e]=r,a[e]=i,r<c&&(c=r),r>f&&(f=r),i<s&&(s=i),i>l&&(l=i));for(f<c&&(c=this._x0,f=this._x1),l<s&&(s=this._y0,l=this._y1),this.cover(c,s).cover(f,l),e=0;e<o;++e)R(this,u[e],a[e],t[e]);return this}function D(t){for(var n=0,e=t.length;n<e;++n)this.remove(t[n]);return this}function O(t){return t[0]}function F(t){return t[1]}function I(t,n,e){var r=new Y(null==n?O:n,null==e?F:e,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function Y(t,n,e,r,i,o){this._x=t,this._y=n,this._x0=e,this._y0=r,this._x1=i,this._y1=o,this._root=void 0}function B(t){for(var n={data:t.data},e=n;t=t.next;)e=e.next={data:t.data};return n}function j(t){if(!(t>=1))throw new Error;this._size=t,this._call=this._error=null,this._tasks=[],this._data=[],this._waiting=this._active=this._ended=this._start=0}function H(t){if(!t._start)try{X(t)}catch(n){if(t._tasks[t._ended+t._active-1])W(t,n);else if(!t._data)throw n}}function X(t){for(;t._start=t._waiting&&t._active<t._size;){var n=t._ended+t._active,e=t._tasks[n],r=e.length-1,i=e[r];e[r]=V(t,n),--t._waiting,++t._active,e=i.apply(null,e),t._tasks[n]&&(t._tasks[n]=e||_l)}}function V(t,n){return function(e,r){t._tasks[n]&&(--t._active,++t._ended,t._tasks[n]=null,null==t._error&&(null!=e?W(t,e):(t._data[n]=r,t._waiting?H(t):$(t))))}}function W(t,n){var e,r=t._tasks.length;for(t._error=n,t._data=void 0,t._waiting=NaN;--r>=0;)if((e=t._tasks[r])&&(t._tasks[r]=null,e.abort))try{e.abort()}catch(t){}t._active=NaN,$(t)}function $(t){if(!t._active&&t._call){var n=t._data;t._data=void 0,t._call(t._error,n)}}function Z(t){return new j(arguments.length?+t:1/0)}function G(t){return t.innerRadius}function J(t){return t.outerRadius}function Q(t){return t.startAngle}function K(t){return t.endAngle}function tt(t){return t&&t.padAngle}function nt(t){return t>=1?xl:t<=-1?-xl:Math.asin(t)}function et(t,n,e,r,i,o,u,a){var c=e-t,s=r-n,f=u-i,l=a-o,h=(f*(n-o)-l*(t-i))/(l*c-f*s);return[t+h*c,n+h*s]}function rt(t,n,e,r,i,o,u){var a=t-e,c=n-r,s=(u?o:-o)/Math.sqrt(a*a+c*c),f=s*c,l=-s*a,h=t+f,p=n+l,d=e+f,v=r+l,_=(h+d)/2,y=(p+v)/2,g=d-h,m=v-p,x=g*g+m*m,b=i-o,w=h*v-d*p,M=(m<0?-1:1)*Math.sqrt(Math.max(0,b*b*x-w*w)),T=(w*m-g*M)/x,N=(-w*g-m*M)/x,k=(w*m+g*M)/x,S=(-w*Line truncated
|
||||
}function Pr(t){return t instanceof Date?+t:+new Date(+t)}function qr(t,n,r,i,o,u,a,c,s){function f(e){return(a(e)<e?v:u(e)<e?_:o(e)<e?y:i(e)<e?g:n(e)<e?r(e)<e?m:x:t(e)<e?b:w)(e)}function l(n,r,i,o){if(null==n&&(n=10),"number"==typeof n){var u=Math.abs(i-r)/n,a=Ts(function(t){return t[2]}).right(M,u);a===M.length?(o=e(r/o_,i/o_,n),n=t):a?(a=M[u/M[a-1][2]<M[a][2]/u?a-1:a],o=a[1],n=a[0]):(o=e(r,i,n),n=c)}return null==o?n:n.every(o)}var h=dr(cr,lp),p=h.invert,d=h.domain,v=s(".%L"),_=s(":%S"),y=s("%I:%M"),g=s("%I %p"),m=s("%a %d"),x=s("%b %d"),b=s("%B"),w=s("%Y"),M=[[a,1,Kv],[a,5,5*Kv],[a,15,15*Kv],[a,30,30*Kv],[u,1,t_],[u,5,5*t_],[u,15,15*t_],[u,30,30*t_],[o,1,n_],[o,3,3*n_],[o,6,6*n_],[o,12,12*n_],[i,1,e_],[i,2,2*e_],[r,1,r_],[n,1,i_],[n,3,3*i_],[t,1,o_]];return h.invert=function(t){return new Date(p(t))},h.domain=function(t){return arguments.length?d(Xv.call(t,Pr)):d().map(zr)},h.ticks=function(t,n){var e,r=d(),i=r[0],o=r[r.length-1],u=o<i;return u&&(e=i,i=o,o=e),e=l(t,i,o,n),e=e?e.range(i,o+1):[],u?e.reverse():e},h.tickFormat=function(t,n){return null==n?f:s(n)},h.nice=function(t,n){var e=d();return(t=l(t,e[0],e[e.length-1],n))?d(Qv(e,t)):h},h.copy=function(){return pr(h,qr(t,n,r,i,o,u,a,c,s))},h}function Lr(t){var n=t.length;return function(e){return t[Math.max(0,Math.min(n-1,Math.floor(e*n)))]}}function Rr(t){function n(n){var o=(n-e)/(r-e);return t(i?Math.max(0,Math.min(1,o)):o)}var e=0,r=1,i=!1;return n.domain=function(t){return arguments.length?(e=+t[0],r=+t[1],n):[e,r]},n.clamp=function(t){return arguments.length?(i=!!t,n):i},n.interpolator=function(e){return arguments.length?(t=e,n):t},n.copy=function(){return Rr(t).domain([e,r]).clamp(i)},vr(n)}function Ur(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===w_&&n.documentElement.namespaceURI===w_?n.createElement(t):n.createElementNS(e,t)}}function Dr(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function Or(){return new Fr}function Fr(){this._="@"+(++k_).toString(36)}function Ir(t,n,e){return t=Yr(t,n,e),function(n){var e=n.relatedTarget;e&&(e===this||8&e.compareDocumentPosition(this))||t.call(this,n)}}function Yr(n,e,r){return function(i){var o=t.event;t.event=i;try{n.call(this,this.__data__,e,r)}finally{t.event=o}}}function Br(t){return t.trim().split(/^|\s+/).map(function(t){var n="",e=t.indexOf(".");return e>=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}})}function jr(t){return function(){var n=this.__on;if(n){for(var e,r=0,i=-1,o=n.length;r<o;++r)e=n[r],t.type&&e.type!==t.type||e.name!==t.name?n[++i]=e:this.removeEventListener(e.type,e.listener,e.capture);++i?n.length=i:delete this.__on}}}function Hr(t,n,e){var r=z_.hasOwnProperty(t.type)?Ir:Yr;return function(i,o,u){var a,c=this.__on,s=r(n,o,u);if(c)for(var f=0,l=c.length;f<l;++f)if((a=c[f]).type===t.type&&a.name===t.name)return this.removeEventListener(a.type,a.listener,a.capture),this.addEventListener(a.type,a.listener=s,a.capture=e),void(a.value=n);this.addEventListener(t.type,s,e),a={type:t.type,name:t.name,value:n,listener:s,capture:e},c?c.push(a):this.__on=[a]}}function Xr(n,e,r,i){var o=t.event;n.sourceEvent=t.event,t.event=n;try{return e.apply(r,i)}finally{t.event=o}}function Vr(){}function Wr(){return[]}function $r(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}function Zr(t,n,e,r,i,o){for(var u,a=0,c=n.length,s=o.length;a<s;++a)(u=n[a])?(u.__data__=o[a],r[a]=u):e[a]=new $r(t,o[a]);for(;a<c;++a)(u=n[a])&&(i[a]=u)}function Gr(t,n,e,r,i,o,u){var a,c,s,f={},l=n.length,h=o.length,p=new Array(l);for(a=0;a<l;++a)(c=n[a])&&(p[a]=s=X_+u.call(c,c.__data__,a,n),s in f?i[a]=c:f[s]=c);for(a=0;a<h;++a)s=X_+u.call(t,o[a],a,o),(c=f[s])?(r[a]=c,c.__data__=o[a],f[s]=null):e[a]=new $r(t,o[a]);for(a=0;a<l;++a)(c=n[a])&&f[p[a]]===c&&(i[a]=c)}function Jr(t,n){return t<n?-1:t>n?1:t>=n?0:NaN}function Qr(t){return function(){this.removeAttribute(t)}}function Kr(t){return function(){this.removeAttributeNS(t.space,t.local)}}function ti(t,n){return function(){this.setAttribute(t,n)}}function ni(t,n){return function(){this.setAttributeNS(t.space,t.local,n)}}function ei(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttribute(t):this.setAttribute(t,e)}}function ri(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}}function ii(t){return function(){this.style.removeProperty(t)}}function oi(t,n,e){return function(){this.style.setProperty(t,n,e)}}function ui(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}function ai(t){return function(){delete this[t]}}function ci(t,n){return function(){this[t]=n}}function si(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}function fi(t){return t.trim().split(/^|\s+/)}function li(t){return t.classList||new hi(t)}function
Line truncated
|
||||
return c&&s?t:t(1)}):t.each(function(){var t=this,o=arguments,u=t.__brush,a=n.input("function"==typeof e?e.apply(t,o):e,u.extent),c=i(t,o).beforestart();Py(t),u.selection=null==a||da(a)?null:a,r.call(t),c.start().brush().end()})},o.prototype={beforestart:function(){return 1===++this.active&&(this.state.emitter=this,this.starting=!0),this},start:function(){return this.starting&&(this.starting=!1,this.emit("start")),this},brush:function(){return this.emit("brush"),this},end:function(){return 0===--this.active&&(delete this.state.emitter,this.emit("end")),this},emit:function(t){Xr(new xm(e,t,n.output(this.state.selection)),l.apply,l,[t,this.that,this.args])}},e.extent=function(t){return arguments.length?(s="function"==typeof t?t:mm([[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]]),e):s},e.filter=function(t){return arguments.length?(f="function"==typeof t?t:mm(!!t),e):f},e.handleSize=function(t){return arguments.length?(h=+t,e):h},e.on=function(){var t=l.on.apply(l,arguments);return t===l?e:t},e}function ma(t){return function(n,e){return t(n.source.value+n.target.value,e.source.value+e.target.value)}}function xa(t){return t.source}function ba(t){return t.target}function wa(t){return t.radius}function Ma(t){return t.startAngle}function Ta(t){return t.endAngle}function Na(){this.reset()}function ka(t,n,e){var r=t.s=n+e,i=r-n,o=r-i;t.t=n-o+(e-i)}function Sa(t){return t>1?0:t<-1?kx:Math.acos(t)}function Aa(t){return t>1?Sx:t<-1?-Sx:Math.asin(t)}function Ea(t){return(t=Ix(t/2))*t}function Ca(){}function za(t,n){t&&Xx.hasOwnProperty(t.type)&&Xx[t.type](t,n)}function Pa(t,n,e){var r,i=-1,o=t.length-e;for(n.lineStart();++i<o;)r=t[i],n.point(r[0],r[1],r[2]);n.lineEnd()}function qa(t,n){var e=-1,r=t.length;for(n.polygonStart();++e<r;)Pa(t[e],n,1);n.polygonEnd()}function La(){Zx.point=Ua}function Ra(){Da(Vm,Wm)}function Ua(t,n){Zx.point=Da,Vm=t,Wm=n,t*=zx,n*=zx,$m=t,Zm=Rx(n=n/2+Ax),Gm=Ix(n)}function Da(t,n){t*=zx,n*=zx,n=n/2+Ax;var e=t-$m,r=e>=0?1:-1,i=r*e,o=Rx(n),u=Ix(n),a=Gm*u,c=Zm*o+a*Rx(i),s=a*r*Ix(i);Wx.add(Lx(s,c)),$m=t,Zm=o,Gm=u}function Oa(t){return[Lx(t[1],t[0]),Aa(t[2])]}function Fa(t){var n=t[0],e=t[1],r=Rx(e);return[r*Rx(n),r*Ix(n),Ix(e)]}function Ia(t,n){return t[0]*n[0]+t[1]*n[1]+t[2]*n[2]}function Ya(t,n){return[t[1]*n[2]-t[2]*n[1],t[2]*n[0]-t[0]*n[2],t[0]*n[1]-t[1]*n[0]]}function Ba(t,n){t[0]+=n[0],t[1]+=n[1],t[2]+=n[2]}function ja(t,n){return[t[0]*n,t[1]*n,t[2]*n]}function Ha(t){var n=Bx(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=n,t[1]/=n,t[2]/=n}function Xa(t,n){ox.push(ux=[Jm=t,Km=t]),n<Qm&&(Qm=n),n>tx&&(tx=n)}function Va(t,n){var e=Fa([t*zx,n*zx]);if(ix){var r=Ya(ix,e),i=[r[1],-r[0],0],o=Ya(i,r);Ha(o),o=Oa(o);var u,a=t-nx,c=a>0?1:-1,s=o[0]*Cx*c,f=Px(a)>180;f^(c*nx<s&&s<c*t)?(u=o[1]*Cx,u>tx&&(tx=u)):(s=(s+360)%360-180,f^(c*nx<s&&s<c*t)?(u=-o[1]*Cx,u<Qm&&(Qm=u)):(n<Qm&&(Qm=n),n>tx&&(tx=n))),f?t<nx?Qa(Jm,t)>Qa(Jm,Km)&&(Km=t):Qa(t,Km)>Qa(Jm,Km)&&(Jm=t):Km>=Jm?(t<Jm&&(Jm=t),t>Km&&(Km=t)):t>nx?Qa(Jm,t)>Qa(Jm,Km)&&(Km=t):Qa(t,Km)>Qa(Jm,Km)&&(Jm=t)}else Xa(t,n);ix=e,nx=t}function Wa(){Qx.point=Va}function $a(){ux[0]=Jm,ux[1]=Km,Qx.point=Xa,ix=null}function Za(t,n){if(ix){var e=t-nx;Jx.add(Px(e)>180?e+(e>0?360:-360):e)}else ex=t,rx=n;Zx.point(t,n),Va(t,n)}function Ga(){Zx.lineStart()}function Ja(){Za(ex,rx),Zx.lineEnd(),Px(Jx)>Tx&&(Jm=-(Km=180)),ux[0]=Jm,ux[1]=Km,ix=null}function Qa(t,n){return(n-=t)<0?n+360:n}function Ka(t,n){return t[0]-n[0]}function tc(t,n){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:n<t[0]||t[1]<n}function nc(t,n){t*=zx,n*=zx;var e=Rx(n);ec(e*Rx(t),e*Ix(t),Ix(n))}function ec(t,n,e){++ax,sx+=(t-sx)/ax,fx+=(n-fx)/ax,lx+=(e-lx)/ax}function rc(){tb.point=ic}function ic(t,n){t*=zx,n*=zx;var e=Rx(n);xx=e*Rx(t),bx=e*Ix(t),wx=Ix(n),tb.point=oc,ec(xx,bx,wx)}function oc(t,n){t*=zx,n*=zx;var e=Rx(n),r=e*Rx(t),i=e*Ix(t),o=Ix(n),u=Lx(Bx((u=bx*o-wx*i)*u+(u=wx*r-xx*o)*u+(u=xx*i-bx*r)*u),xx*r+bx*i+wx*o);cx+=u,hx+=u*(xx+(xx=r)),px+=u*(bx+(bx=i)),dx+=u*(wx+(wx=o)),ec(xx,bx,wx)}function uc(){tb.point=nc}function ac(){tb.point=sc}function cc(){fc(gx,mx),tb.point=nc}function sc(t,n){gx=t,mx=n,t*=zx,n*=zx,tb.point=fc;var e=Rx(n);xx=e*Rx(t),bx=e*Ix(t),wx=Ix(n),ec(xx,bx,wx)}function fc(t,n){t*=zx,n*=zx;var e=Rx(n),r=e*Rx(t),i=e*Ix(t),o=Ix(n),u=bx*o-wx*i,a=wx*r-xx*o,c=xx*i-bx*r,s=Bx(u*u+a*a+c*c),f=xx*r+bx*i+wx*o,l=s&&-Sa(f)/s,h=Lx(s,f);vx+=l*u,_x+=l*a,yx+=l*c,cx+=h,hx+=h*(xx+(xx=r)),px+=h*(bx+(bx=i)),dx+=h*(wx+(wx=o)),ec(xx,bx,wx)}function lc(t,n){return[t>kx?t-Ex:t<-kx?t+Ex:t,n]}function hc(t,n,e){return(t%=Ex)?n||e?rb(dc(t),vc(n,e)):dc(t):n||e?vc(n,e):lc}function pc(t){return function(n,e){return n+=t,[n>kx?n-Ex:n<-kx?n+Ex:n,e]}}function dc(t){var n=pc(t);return n.invert=pc(-t),n}function vc(t,n){function e(t,n){var e=Rx(n),a=Rx(t)*e,c=Ix(t)*e,s=Ix(n),f=s*r+a*i;return[Lx(c*o-f*u,a*r-s*i),Aa(f*o+c*u)]}var r=Rx(t),i=Ix(t),o=Rx(n),u=Ix(n);return e.invert=function(t,n){var e=Rx(n),a=Rx(t)*e,c=Ix(t)*e,s=Ix(n),f=s*o-c*u;return[Lx(c*o+s*u,a*r+f*i),Aa(f*r-a*i)]},e}function _c(t,n,e,r,i,o){if(e){var u=Rx(n),a=Ix(n),c=r*e;null==i?(i=n+r*Ex,o=Line truncated
|
||||
return function(){return t}},gl=1e-12,ml=Math.PI,xl=ml/2,bl=2*ml,wl=function(){function t(){var t,s,f=+n.apply(this,arguments),l=+e.apply(this,arguments),h=o.apply(this,arguments)-xl,p=u.apply(this,arguments)-xl,d=Math.abs(p-h),v=p>h;if(c||(c=t=L()),l<f&&(s=l,l=f,f=s),l>gl)if(d>bl-gl)c.moveTo(l*Math.cos(h),l*Math.sin(h)),c.arc(0,0,l,h,p,!v),f>gl&&(c.moveTo(f*Math.cos(p),f*Math.sin(p)),c.arc(0,0,f,p,h,v));else{var _,y,g=h,m=p,x=h,b=p,w=d,M=d,T=a.apply(this,arguments)/2,N=T>gl&&(i?+i.apply(this,arguments):Math.sqrt(f*f+l*l)),k=Math.min(Math.abs(l-f)/2,+r.apply(this,arguments)),S=k,A=k;if(N>gl){var E=nt(N/f*Math.sin(T)),C=nt(N/l*Math.sin(T));(w-=2*E)>gl?(E*=v?1:-1,x+=E,b-=E):(w=0,x=b=(h+p)/2),(M-=2*C)>gl?(C*=v?1:-1,g+=C,m-=C):(M=0,g=m=(h+p)/2)}var z=l*Math.cos(g),P=l*Math.sin(g),q=f*Math.cos(b),R=f*Math.sin(b);if(k>gl){var U=l*Math.cos(m),D=l*Math.sin(m),O=f*Math.cos(x),F=f*Math.sin(x);if(d<ml){var I=w>gl?et(z,P,O,F,U,D,q,R):[q,R],Y=z-I[0],B=P-I[1],j=U-I[0],H=D-I[1],X=1/Math.sin(Math.acos((Y*j+B*H)/(Math.sqrt(Y*Y+B*B)*Math.sqrt(j*j+H*H)))/2),V=Math.sqrt(I[0]*I[0]+I[1]*I[1]);S=Math.min(k,(f-V)/(X-1)),A=Math.min(k,(l-V)/(X+1))}}M>gl?A>gl?(_=rt(O,F,z,P,l,A,v),y=rt(U,D,q,R,l,A,v),c.moveTo(_.cx+_.x01,_.cy+_.y01),A<k?c.arc(_.cx,_.cy,A,Math.atan2(_.y01,_.x01),Math.atan2(y.y01,y.x01),!v):(c.arc(_.cx,_.cy,A,Math.atan2(_.y01,_.x01),Math.atan2(_.y11,_.x11),!v),c.arc(0,0,l,Math.atan2(_.cy+_.y11,_.cx+_.x11),Math.atan2(y.cy+y.y11,y.cx+y.x11),!v),c.arc(y.cx,y.cy,A,Math.atan2(y.y11,y.x11),Math.atan2(y.y01,y.x01),!v))):(c.moveTo(z,P),c.arc(0,0,l,g,m,!v)):c.moveTo(z,P),f>gl&&w>gl?S>gl?(_=rt(q,R,U,D,f,-S,v),y=rt(z,P,O,F,f,-S,v),c.lineTo(_.cx+_.x01,_.cy+_.y01),S<k?c.arc(_.cx,_.cy,S,Math.atan2(_.y01,_.x01),Math.atan2(y.y01,y.x01),!v):(c.arc(_.cx,_.cy,S,Math.atan2(_.y01,_.x01),Math.atan2(_.y11,_.x11),!v),c.arc(0,0,f,Math.atan2(_.cy+_.y11,_.cx+_.x11),Math.atan2(y.cy+y.y11,y.cx+y.x11),v),c.arc(y.cx,y.cy,S,Math.atan2(y.y11,y.x11),Math.atan2(y.y01,y.x01),!v))):c.arc(0,0,f,b,x,v):c.lineTo(q,R)}else c.moveTo(0,0);if(c.closePath(),t)return c=null,t+""||null}var n=G,e=J,r=yl(0),i=null,o=Q,u=K,a=tt,c=null;return t.centroid=function(){var t=(+n.apply(this,arguments)+ +e.apply(this,arguments))/2,r=(+o.apply(this,arguments)+ +u.apply(this,arguments))/2-ml/2;return[Math.cos(r)*t,Math.sin(r)*t]},t.innerRadius=function(e){return arguments.length?(n="function"==typeof e?e:yl(+e),t):n},t.outerRadius=function(n){return arguments.length?(e="function"==typeof n?n:yl(+n),t):e},t.cornerRadius=function(n){return arguments.length?(r="function"==typeof n?n:yl(+n),t):r},t.padRadius=function(n){return arguments.length?(i=null==n?null:"function"==typeof n?n:yl(+n),t):i},t.startAngle=function(n){return arguments.length?(o="function"==typeof n?n:yl(+n),t):o},t.endAngle=function(n){return arguments.length?(u="function"==typeof n?n:yl(+n),t):u},t.padAngle=function(n){return arguments.length?(a="function"==typeof n?n:yl(+n),t):a},t.context=function(n){return arguments.length?(c=null==n?null:n,t):c},t};it.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:this._context.lineTo(t,n)}}};var Ml=function(t){return new it(t)},Tl=function(){function t(t){var a,c,s,f=t.length,l=!1;for(null==i&&(u=o(s=L())),a=0;a<=f;++a)!(a<f&&r(c=t[a],a,t))===l&&((l=!l)?u.lineStart():u.lineEnd()),l&&u.point(+n(c,a,t),+e(c,a,t));if(s)return u=null,s+""||null}var n=ot,e=ut,r=yl(!0),i=null,o=Ml,u=null;return t.x=function(e){return arguments.length?(n="function"==typeof e?e:yl(+e),t):n},t.y=function(n){return arguments.length?(e="function"==typeof n?n:yl(+n),t):e},t.defined=function(n){return arguments.length?(r="function"==typeof n?n:yl(!!n),t):r},t.curve=function(n){return arguments.length?(o=n,null!=i&&(u=o(i)),t):o},t.context=function(n){return arguments.length?(null==n?i=u=null:u=o(i=n),t):i},t},Nl=function(){function t(t){var n,f,l,h,p,d=t.length,v=!1,_=new Array(d),y=new Array(d);for(null==a&&(s=c(p=L())),n=0;n<=d;++n){if(!(n<d&&u(h=t[n],n,t))===v)if(v=!v)f=n,s.areaStart(),s.lineStart();else{for(s.lineEnd(),s.lineStart(),l=n-1;l>=f;--l)s.point(_[l],y[l]);s.lineEnd(),s.areaEnd()}v&&(_[n]=+e(h,n,t),y[n]=+i(h,n,t),s.point(r?+r(h,n,t):_[n],o?+o(h,n,t):y[n]))}if(p)return s=null,p+""||null}function n(){return Tl().defined(u).curve(c).context(a)}var e=ot,r=null,i=yl(0),o=ut,u=yl(!0),a=null,c=Ml,s=null;return t.x=function(n){return arguments.length?(e="function"==typeof n?n:yl(+n),r=null,t):e},t.x0=function(n){return arguments.length?(e="function"==typeof n?n:yl(+n),t):e},t.x1=function(n){return arguments.length?(r=null==n?null:"function"==typeof n?n:yl(+n),t):r},t.y=function(n){return arguments.length?(i="function"==typeof n?n:yl(+n),o=null,t):i},Line truncated
|
||||
return e},Rp={value:function(){}};qn.prototype=Pn.prototype={constructor:qn,on:function(t,n){var e,r=this._,i=Ln(t+"",r),o=-1,u=i.length;{if(!(arguments.length<2)){if(null!=n&&"function"!=typeof n)throw new Error("invalid callback: "+n);for(;++o<u;)if(e=(t=i[o]).type)r[e]=Un(r[e],t.name,n);else if(null==n)for(e in r)r[e]=Un(r[e],t.name,null);return this}for(;++o<u;)if((e=(t=i[o]).type)&&(e=Rn(r[e],t.name)))return e}},copy:function(){var t={},n=this._;for(var e in n)t[e]=n[e].slice();return new qn(t)},call:function(t,n){if((e=arguments.length-2)>0)for(var e,r,i=new Array(e),o=0;o<e;++o)i[o]=arguments[o+2];if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(r=this._[t],o=0,e=r.length;o<e;++o)r[o].value.apply(n,i)},apply:function(t,n,e){if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(var r=this._[t],i=0,o=r.length;i<o;++i)r[i].value.apply(n,e)}};var Up,Dp,Op=function(t){function n(t,n){var r,i,o=e(t,function(t,e){return r?r(t,e-1):(i=t,void(r=n?On(t,n):Dn(t)))});return o.columns=i,o}function e(t,n){function e(){if(f>=s)return u;if(i)return i=!1,o;var n,e=f;if(34===t.charCodeAt(e)){for(var r=e;r++<s;)if(34===t.charCodeAt(r)){if(34!==t.charCodeAt(r+1))break;++r}return f=r+2,n=t.charCodeAt(r+1),13===n?(i=!0,10===t.charCodeAt(r+2)&&++f):10===n&&(i=!0),t.slice(e+1,r).replace(/""/g,'"')}for(;f<s;){var a=1;if(n=t.charCodeAt(f++),10===n)i=!0;else if(13===n)i=!0,10===t.charCodeAt(f)&&(++f,++a);else if(n!==c)continue;return t.slice(e,f-a)}return t.slice(e)}for(var r,i,o={},u={},a=[],s=t.length,f=0,l=0;(r=e())!==u;){for(var h=[];r!==o&&r!==u;)h.push(r),r=e();n&&null==(h=n(h,l++))||a.push(h)}return a}function r(n,e){return null==e&&(e=Fn(n)),[e.map(u).join(t)].concat(n.map(function(n){return e.map(function(t){return u(n[t])}).join(t)})).join("\n")}function i(t){return t.map(o).join("\n")}function o(n){return n.map(u).join(t)}function u(t){return null==t?"":a.test(t+="")?'"'+t.replace(/\"/g,'""')+'"':t}var a=new RegExp('["'+t+"\n]"),c=t.charCodeAt(0);return{parse:n,parseRows:e,format:r,formatRows:i}},Fp=Op(","),Ip=Fp.parse,Yp=Fp.parseRows,Bp=Fp.format,jp=Fp.formatRows,Hp=Op("\t"),Xp=Hp.parse,Vp=Hp.parseRows,Wp=Hp.format,$p=Hp.formatRows,Zp=function(t,n){function e(t){var n,e=f.status;if(!e&&Yn(f)||e>=200&&e<300||304===e){if(u)try{n=u.call(r,f)}catch(t){return void c.call("error",r,t)}else n=f;c.call("load",r,n)}else c.call("error",r,t)}var r,i,u,a,c=Pn("beforesend","progress","load","error"),s=o(),f=new XMLHttpRequest,l=null,h=null,p=0;if("undefined"==typeof XDomainRequest||"withCredentials"in f||!/^(http(s)?:)?\/\//.test(t)||(f=new XDomainRequest),"onload"in f?f.onload=f.onerror=f.ontimeout=e:f.onreadystatechange=function(t){f.readyState>3&&e(t)},f.onprogress=function(t){c.call("progress",r,t)},r={header:function(t,n){return t=(t+"").toLowerCase(),arguments.length<2?s.get(t):(null==n?s.remove(t):s.set(t,n+""),r)},mimeType:function(t){return arguments.length?(i=null==t?null:t+"",r):i},responseType:function(t){return arguments.length?(a=t,r):a},timeout:function(t){return arguments.length?(p=+t,r):p},user:function(t){return arguments.length<1?l:(l=null==t?null:t+"",r)},password:function(t){return arguments.length<1?h:(h=null==t?null:t+"",r)},response:function(t){return u=t,r},get:function(t,n){return r.send("GET",t,n)},post:function(t,n){return r.send("POST",t,n)},send:function(n,e,o){return f.open(n,t,!0,l,h),null==i||s.has("accept")||s.set("accept",i+",*/*"),f.setRequestHeader&&s.each(function(t,n){f.setRequestHeader(n,t)}),null!=i&&f.overrideMimeType&&f.overrideMimeType(i),null!=a&&(f.responseType=a),p>0&&(f.timeout=p),null==o&&"function"==typeof e&&(o=e,e=null),null!=o&&1===o.length&&(o=In(o)),null!=o&&r.on("error",o).on("load",function(t){o(null,t)}),c.call("beforesend",r,f),f.send(null==e?null:e),r},abort:function(){return f.abort(),r},on:function(){var t=c.on.apply(c,arguments);return t===c?r:t}},null!=n){if("function"!=typeof n)throw new Error("invalid callback: "+n);return r.get(n)}return r},Gp=function(t,n){return function(e,r){var i=Zp(e).mimeType(t).response(n);if(null!=r){if("function"!=typeof r)throw new Error("invalid callback: "+r);return i.get(r)}return i}},Jp=Gp("text/html",function(t){return document.createRange().createContextualFragment(t.responseText)}),Qp=Gp("application/json",function(t){return JSON.parse(t.responseText)}),Kp=Gp("text/plain",function(t){return t.responseText}),td=Gp("application/xml",function(t){var n=t.responseXML;if(!n)throw new Error("parse error");return n}),nd=function(t,n){return function(e,r,i){arguments.length<3&&(i=r,r=null);var o=Zp(e).mimeType(t);return o.row=function(t){return arguments.length?o.response(Bn(n,r=t)):r},o.row(r),i?o.get(i):o}},ed=nd("text/csv",Ip),rd=nd("text/tab-separated-values",Xp),id=0,od=0,ud=0,ad=1e3,cd=0,sd=0,fd=0,ld="object"==typeof performance&&performance.now?performance:Date,hd="function"==typeof requestAnimationFrame?requestAnimationFrame:function(t){setTimeout(t,17)};Xn.prototype=Vn.prototype={constructor:XLine truncated
|
||||
for(var r=this._groups,i=r.length,o=[],u=[],a=0;a<i;++a)for(var c,s=r[a],f=s.length,l=0;l<f;++l)if(c=s[l]){for(var h,p=t.call(c,c.__data__,l,s),d=Ri(c,e),v=0,_=p.length;v<_;++v)(h=p[v])&&zy(h,n,e,v,p,d);o.push(p),u.push(c)}return new so(o,u,n,e)},Wy=Pi.prototype.constructor,$y=function(){return new Wy(this._groups,this._parents)},Zy=function(t,n,e){var r="transform"==(t+="")?bp:Ry;return null==n?this.styleTween(t,eo(t,r)).on("end.style."+t,ro(t)):this.styleTween(t,"function"==typeof n?oo(t,r,Fi(this,"style."+t,n)):io(t,r,n),e)},Gy=function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,uo(t,n,null==e?"":e))},Jy=function(t){return this.tween("text","function"==typeof t?co(Fi(this,"text",t)):ao(null==t?"":t+""))},Qy=function(){for(var t=this._name,n=this._id,e=lo(),r=this._groups,i=r.length,o=0;o<i;++o)for(var u,a=r[o],c=a.length,s=0;s<c;++s)if(u=a[s]){var f=Ri(u,n);zy(u,t,e,s,a,{time:f.time+f.delay+f.duration,delay:0,duration:f.duration,ease:f.ease})}return new so(r,this._parents,t,e)},Ky=0,tg=Pi.prototype;so.prototype=fo.prototype={constructor:so,select:Xy,selectAll:Vy,filter:Yy,merge:By,selection:$y,transition:Qy,call:tg.call,nodes:tg.nodes,node:tg.node,size:tg.size,empty:tg.empty,each:tg.each,on:jy,attr:Uy,attrTween:Dy,style:Zy,styleTween:Gy,text:Jy,remove:Hy,tween:Ly,delay:Oy,duration:Fy,ease:Iy};var ng={time:null,delay:0,duration:250,ease:g},eg=function(t){var n,e;t instanceof so?(n=t._id,t=t._name):(n=lo(),(e=ng).time=jn(),t=null==t?null:t+"");for(var r=this._groups,i=r.length,o=0;o<i;++o)for(var u,a=r[o],c=a.length,s=0;s<c;++s)(u=a[s])&&zy(u,t,n,s,a,e||ho(u,n));return new so(r,this._parents,t,n)};Pi.prototype.interrupt=qy,Pi.prototype.transition=eg;var rg=[null],ig=function(t,n){var e,r,i=t.__transition;if(i){n=null==n?null:n+"";for(r in i)if((e=i[r]).state>Ny&&e.name===n)return new so([[t]],rg,n,+r)}return null},og=Array.prototype.slice,ug=function(t){return t},ag=1,cg=2,sg=3,fg=4,lg=1e-6,hg=function(){function t(t){var o,u=0;t.eachAfter(function(t){var e=t.children;e?(t.x=To(e),t.y=ko(e)):(t.x=o?u+=n(t,o):0,t.y=0,o=t)});var a=Ao(t),c=Eo(t),s=a.x-n(a,c)/2,f=c.x+n(c,a)/2;return t.eachAfter(i?function(n){n.x=(n.x-t.x)*e,n.y=(t.y-n.y)*r}:function(n){n.x=(n.x-s)/(f-s)*e,n.y=(1-(t.y?n.y/t.y:1))*r})}var n=Mo,e=1,r=1,i=!1;return t.separation=function(e){return arguments.length?(n=e,t):n},t.size=function(n){return arguments.length?(i=!1,e=+n[0],r=+n[1],t):i?null:[e,r]},t.nodeSize=function(n){return arguments.length?(i=!0,e=+n[0],r=+n[1],t):i?[e,r]:null},t},pg=function(t){var n,e,r,i,o=this,u=[o];do for(n=u.reverse(),u=[];o=n.pop();)if(t(o),e=o.children)for(r=0,i=e.length;r<i;++r)u.push(e[r]);while(u.length);return this},dg=function(t){for(var n,e,r=this,i=[r];r=i.pop();)if(t(r),n=r.children)for(e=n.length-1;e>=0;--e)i.push(n[e]);return this},vg=function(t){for(var n,e,r,i=this,o=[i],u=[];i=o.pop();)if(u.push(i),n=i.children)for(e=0,r=n.length;e<r;++e)o.push(n[e]);for(;i=u.pop();)t(i);return this},_g=function(t){return this.eachAfter(function(n){for(var e=+t(n.data)||0,r=n.children,i=r&&r.length;--i>=0;)e+=r[i].value;n.value=e})},yg=function(t){return this.eachBefore(function(n){n.children&&n.children.sort(t)})},gg=function(t){for(var n=this,e=Co(n,t),r=[n];n!==e;)n=n.parent,r.push(n);for(var i=r.length;t!==e;)r.splice(i,0,t),t=t.parent;return r},mg=function(){for(var t=this,n=[t];t=t.parent;)n.push(t);return n},xg=function(){var t=[];return this.each(function(n){t.push(n)}),t},bg=function(){var t=[];return this.eachBefore(function(n){n.children||t.push(n)}),t},wg=function(){var t=this,n=[];return t.each(function(e){e!==t&&n.push({source:e.parent,target:e})}),n};Uo.prototype=zo.prototype={constructor:Uo,each:pg,eachAfter:vg,eachBefore:dg,sum:_g,sort:yg,path:gg,ancestors:mg,descendants:xg,leaves:bg,links:wg,copy:Po};var Mg=function(t){for(var n,e=(t=t.slice()).length,r=null,i=r;e;){var o=new Do(t[e-1]);i=i?i.next=o:r=o,t[n]=t[--e]}return{head:r,tail:i}},Tg=function(t){return Fo(Mg(t),[])},Ng=function(t){return Wo(t),t},kg=function(t){return function(){return t}},Sg=function(){function t(t){return t.x=e/2,t.y=r/2,n?t.eachBefore(Qo(n)).eachAfter(Ko(i,.5)).eachBefore(tu(1)):t.eachBefore(Qo(Jo)).eachAfter(Ko(Go,1)).eachAfter(Ko(i,t.r/Math.min(e,r))).eachBefore(tu(Math.min(e,r)/(2*t.r))),t}var n=null,e=1,r=1,i=Go;return t.radius=function(e){return arguments.length?(n=$o(e),t):n},t.size=function(n){return arguments.length?(e=+n[0],r=+n[1],t):[e,r]},t.padding=function(n){return arguments.length?(i="function"==typeof n?n:kg(+n),t):i},t},Ag=function(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1)},Eg=function(t,n,e,r,i){for(var o,u=t.children,a=-1,c=u.length,s=t.value&&(r-n)/t.value;++a<c;)o=u[a],o.y0=e,o.y1=i,o.x0=n,o.x1=n+=o.value*s},Cg=function(){function t(t){var u=t.height+1;return t.x0=t.y0=i,t.x1=e,t.y1=r/u,t.eachBefore(n(r,u)),o&&t.eaLine truncated
|
||||
},Bx=Math.sqrt,jx=Math.tan,Hx={Feature:function(t,n){za(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r<i;)za(e[r].geometry,n)}},Xx={Sphere:function(t,n){n.sphere()},Point:function(t,n){t=t.coordinates,n.point(t[0],t[1],t[2])},MultiPoint:function(t,n){for(var e=t.coordinates,r=-1,i=e.length;++r<i;)t=e[r],n.point(t[0],t[1],t[2])},LineString:function(t,n){Pa(t.coordinates,n,0)},MultiLineString:function(t,n){for(var e=t.coordinates,r=-1,i=e.length;++r<i;)Pa(e[r],n,0)},Polygon:function(t,n){qa(t.coordinates,n)},MultiPolygon:function(t,n){for(var e=t.coordinates,r=-1,i=e.length;++r<i;)qa(e[r],n)},GeometryCollection:function(t,n){for(var e=t.geometries,r=-1,i=e.length;++r<i;)za(e[r],n)}},Vx=function(t,n){t&&Hx.hasOwnProperty(t.type)?Hx[t.type](t,n):za(t,n)},Wx=Xm(),$x=Xm(),Zx={point:Ca,lineStart:Ca,lineEnd:Ca,polygonStart:function(){Wx.reset(),Zx.lineStart=La,Zx.lineEnd=Ra},polygonEnd:function(){var t=+Wx;$x.add(t<0?Ex+t:t),this.lineStart=this.lineEnd=this.point=Ca},sphere:function(){$x.add(Ex)}},Gx=function(t){return $x.reset(),Vx(t,Zx),2*$x},Jx=Xm(),Qx={point:Xa,lineStart:Wa,lineEnd:$a,polygonStart:function(){Qx.point=Za,Qx.lineStart=Ga,Qx.lineEnd=Ja,Jx.reset(),Zx.polygonStart()},polygonEnd:function(){Zx.polygonEnd(),Qx.point=Xa,Qx.lineStart=Wa,Qx.lineEnd=$a,Wx<0?(Jm=-(Km=180),Qm=-(tx=90)):Jx>Tx?tx=90:Jx<-Tx&&(Qm=-90),ux[0]=Jm,ux[1]=Km}},Kx=function(t){var n,e,r,i,o,u,a;if(tx=Km=-(Jm=Qm=1/0),ox=[],Vx(t,Qx),e=ox.length){for(ox.sort(Ka),n=1,r=ox[0],o=[r];n<e;++n)i=ox[n],tc(r,i[0])||tc(r,i[1])?(Qa(r[0],i[1])>Qa(r[0],r[1])&&(r[1]=i[1]),Qa(i[0],r[1])>Qa(r[0],r[1])&&(r[0]=i[0])):o.push(r=i);for(u=-(1/0),e=o.length-1,n=0,r=o[e];n<=e;r=i,++n)i=o[n],(a=Qa(r[1],i[0]))>u&&(u=a,Jm=i[0],Km=r[1])}return ox=ux=null,Jm===1/0||Qm===1/0?[[NaN,NaN],[NaN,NaN]]:[[Jm,Qm],[Km,tx]]},tb={sphere:Ca,point:nc,lineStart:rc,lineEnd:uc,polygonStart:function(){tb.lineStart=ac,tb.lineEnd=cc},polygonEnd:function(){tb.lineStart=rc,tb.lineEnd=uc}},nb=function(t){ax=cx=sx=fx=lx=hx=px=dx=vx=_x=yx=0,Vx(t,tb);var n=vx,e=_x,r=yx,i=n*n+e*e+r*r;return i<Nx&&(n=hx,e=px,r=dx,cx<Tx&&(n=sx,e=fx,r=lx),i=n*n+e*e+r*r,i<Nx)?[NaN,NaN]:[Lx(e,n)*Cx,Aa(r/Bx(i))*Cx]},eb=function(t){return function(){return t}},rb=function(t,n){function e(e,r){return e=t(e,r),n(e[0],e[1])}return t.invert&&n.invert&&(e.invert=function(e,r){return e=n.invert(e,r),e&&t.invert(e[0],e[1])}),e};lc.invert=lc;var ib,ob,ub,ab,cb,sb,fb,lb,hb,pb,db,vb=function(t){function n(n){return n=t(n[0]*zx,n[1]*zx),n[0]*=Cx,n[1]*=Cx,n}return t=hc(t[0]*zx,t[1]*zx,t.length>2?t[2]*zx:0),n.invert=function(n){return n=t.invert(n[0]*zx,n[1]*zx),n[0]*=Cx,n[1]*=Cx,n},n},_b=function(){function t(t,n){e.push(t=r(t,n)),t[0]*=Cx,t[1]*=Cx}function n(){var t=i.apply(this,arguments),n=o.apply(this,arguments)*zx,c=u.apply(this,arguments)*zx;return e=[],r=hc(-t[0]*zx,-t[1]*zx,0).invert,_c(a,n,c,1),t={type:"Polygon",coordinates:[e]},e=r=null,t}var e,r,i=eb([0,0]),o=eb(90),u=eb(6),a={point:t};return n.center=function(t){return arguments.length?(i="function"==typeof t?t:eb([+t[0],+t[1]]),n):i},n.radius=function(t){return arguments.length?(o="function"==typeof t?t:eb(+t),n):o},n.precision=function(t){return arguments.length?(u="function"==typeof t?t:eb(+t),n):u},n},yb=function(){var t,n=[];return{point:function(n,e){t.push([n,e])},lineStart:function(){n.push(t=[])},lineEnd:Ca,rejoin:function(){n.length>1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}},gb=function(t,n,e,r,i,o){var u,a=t[0],c=t[1],s=n[0],f=n[1],l=0,h=1,p=s-a,d=f-c;if(u=e-a,p||!(u>0)){if(u/=p,p<0){if(u<l)return;u<h&&(h=u)}else if(p>0){if(u>h)return;u>l&&(l=u)}if(u=i-a,p||!(u<0)){if(u/=p,p<0){if(u>h)return;u>l&&(l=u)}else if(p>0){if(u<l)return;u<h&&(h=u)}if(u=r-c,d||!(u>0)){if(u/=d,d<0){if(u<l)return;u<h&&(h=u)}else if(d>0){if(u>h)return;u>l&&(l=u)}if(u=o-c,d||!(u<0)){if(u/=d,d<0){if(u>h)return;u>l&&(l=u)}else if(d>0){if(u<l)return;u<h&&(h=u)}return l>0&&(t[0]=a+l*p,t[1]=c+l*d),h<1&&(n[0]=a+h*p,n[1]=c+h*d),!0}}}}},mb=function(t,n){return Px(t[0]-n[0])<Tx&&Px(t[1]-n[1])<Tx},xb=function(t,n,e,r,i){var o,u,a=[],c=[];if(t.forEach(function(t){if(!((n=t.length-1)<=0)){var n,e,r=t[0],u=t[n];if(mb(r,u)){for(i.lineStart(),o=0;o<n;++o)i.point((r=t[o])[0],r[1]);return void i.lineEnd()}a.push(e=new gc(r,t,null,!0)),c.push(e.o=new gc(r,null,e,!1)),a.push(e=new gc(u,t,null,!1)),c.push(e.o=new gc(u,null,e,!0))}}),a.length){for(c.sort(n),mc(a),mc(c),o=0,u=c.length;o<u;++o)c[o].e=e=!e;for(var s,f,l=a[0];;){for(var h=l,p=!0;h.v;)if((h=h.n)===l)return;s=h.z,i.lineStart();do{if(h.v=h.o.v=!0,h.e){if(p)for(o=0,u=s.length;o<u;++o)i.point((f=s[o])[0],f[1]);else r(h.x,h.n.x,1,i);h=h.n}else{if(p)for(s=h.p.z,o=s.length-1;o>=0;--o)i.point((f=s[o])[0],f[1]);else r(h.x,h.p.x,-1,i);h=h.p}h=h.o,s=h.z,p=!p}while(!h.v);i.lineEnd()}}},bb=1e9,wb=-bb,Mb=function(){var t,n,e,r=0,i=0,o=960,u=500;return e={stream:function(e){return t&&n===e?t:t=xc(r,i,o,u)(n=e)},extent:function(a){return arguments.length?(r=+a[0][0],i=+a[0][Line truncated
|
||||
@@ -0,0 +1,413 @@
|
||||
/*! intercom.js | https://github.com/diy/intercom.js | Apache License (v2) */
|
||||
|
||||
var Intercom = (function() {
|
||||
|
||||
// --- lib/events.js ---
|
||||
|
||||
var EventEmitter = function() {};
|
||||
|
||||
EventEmitter.createInterface = function(space) {
|
||||
var methods = {};
|
||||
|
||||
methods.on = function(name, fn) {
|
||||
if (typeof this[space] === 'undefined') {
|
||||
this[space] = {};
|
||||
}
|
||||
if (!this[space].hasOwnProperty(name)) {
|
||||
this[space][name] = [];
|
||||
}
|
||||
this[space][name].push(fn);
|
||||
};
|
||||
|
||||
methods.off = function(name, fn) {
|
||||
if (typeof this[space] === 'undefined') return;
|
||||
if (this[space].hasOwnProperty(name)) {
|
||||
util.removeItem(fn, this[space][name]);
|
||||
}
|
||||
};
|
||||
|
||||
methods.trigger = function(name) {
|
||||
if (typeof this[space] !== 'undefined' && this[space].hasOwnProperty(name)) {
|
||||
var args = Array.prototype.slice.call(arguments, 1);
|
||||
for (var i = 0; i < this[space][name].length; i++) {
|
||||
this[space][name][i].apply(this[space][name][i], args);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return methods;
|
||||
};
|
||||
|
||||
var pvt = EventEmitter.createInterface('_handlers');
|
||||
EventEmitter.prototype._on = pvt.on;
|
||||
EventEmitter.prototype._off = pvt.off;
|
||||
EventEmitter.prototype._trigger = pvt.trigger;
|
||||
|
||||
var pub = EventEmitter.createInterface('handlers');
|
||||
EventEmitter.prototype.on = function() {
|
||||
pub.on.apply(this, arguments);
|
||||
Array.prototype.unshift.call(arguments, 'on');
|
||||
this._trigger.apply(this, arguments);
|
||||
};
|
||||
EventEmitter.prototype.off = pub.off;
|
||||
EventEmitter.prototype.trigger = pub.trigger;
|
||||
|
||||
// --- lib/localstorage.js ---
|
||||
|
||||
var localStorage = window.localStorage;
|
||||
if (typeof localStorage === 'undefined') {
|
||||
localStorage = {
|
||||
getItem : function() {},
|
||||
setItem : function() {},
|
||||
removeItem : function() {}
|
||||
};
|
||||
}
|
||||
|
||||
// --- lib/util.js ---
|
||||
|
||||
var util = {};
|
||||
|
||||
util.guid = (function() {
|
||||
var S4 = function() {
|
||||
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
|
||||
};
|
||||
return function() {
|
||||
return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
|
||||
};
|
||||
})();
|
||||
|
||||
util.throttle = function(delay, fn) {
|
||||
var last = 0;
|
||||
return function() {
|
||||
var now = (new Date()).getTime();
|
||||
if (now - last > delay) {
|
||||
last = now;
|
||||
fn.apply(this, arguments);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
util.extend = function(a, b) {
|
||||
if (typeof a === 'undefined' || !a) { a = {}; }
|
||||
if (typeof b === 'object') {
|
||||
for (var key in b) {
|
||||
if (b.hasOwnProperty(key)) {
|
||||
a[key] = b[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
return a;
|
||||
};
|
||||
|
||||
util.removeItem = function(item, array) {
|
||||
for (var i = array.length - 1; i >= 0; i--) {
|
||||
if (array[i] === item) {
|
||||
array.splice(i, 1);
|
||||
}
|
||||
}
|
||||
return array;
|
||||
};
|
||||
|
||||
// --- lib/intercom.js ---
|
||||
|
||||
/**
|
||||
* A cross-window broadcast service built on top
|
||||
* of the HTML5 localStorage API. The interface
|
||||
* mimic socket.io in design.
|
||||
*
|
||||
* @author Brian Reavis <brian@thirdroute.com>
|
||||
* @constructor
|
||||
*/
|
||||
|
||||
var Intercom = function() {
|
||||
var self = this;
|
||||
var now = (new Date()).getTime();
|
||||
|
||||
this.origin = util.guid();
|
||||
this.lastMessage = now;
|
||||
this.bindings = [];
|
||||
this.receivedIDs = {};
|
||||
this.previousValues = {};
|
||||
|
||||
var storageHandler = function() { self._onStorageEvent.apply(self, arguments); };
|
||||
if (window.attachEvent) { document.attachEvent('onstorage', storageHandler); }
|
||||
else { window.addEventListener('storage', storageHandler, false); };
|
||||
};
|
||||
|
||||
Intercom.prototype._transaction = function(fn) {
|
||||
var TIMEOUT = 1000;
|
||||
var WAIT = 20;
|
||||
|
||||
var self = this;
|
||||
var executed = false;
|
||||
var listening = false;
|
||||
var waitTimer = null;
|
||||
|
||||
var lock = function() {
|
||||
if (executed) return;
|
||||
|
||||
var now = (new Date()).getTime();
|
||||
var activeLock = parseInt(localStorage.getItem(INDEX_LOCK) || 0);
|
||||
if (activeLock && now - activeLock < TIMEOUT) {
|
||||
if (!listening) {
|
||||
self._on('storage', lock);
|
||||
listening = true;
|
||||
}
|
||||
waitTimer = window.setTimeout(lock, WAIT);
|
||||
return;
|
||||
}
|
||||
executed = true;
|
||||
localStorage.setItem(INDEX_LOCK, now);
|
||||
|
||||
fn();
|
||||
unlock();
|
||||
};
|
||||
|
||||
var unlock = function() {
|
||||
if (listening) { self._off('storage', lock); }
|
||||
if (waitTimer) { window.clearTimeout(waitTimer); }
|
||||
localStorage.removeItem(INDEX_LOCK);
|
||||
};
|
||||
|
||||
lock();
|
||||
};
|
||||
|
||||
Intercom.prototype._cleanup_emit = util.throttle(100, function() {
|
||||
var self = this;
|
||||
|
||||
this._transaction(function() {
|
||||
var now = (new Date()).getTime();
|
||||
var threshold = now - THRESHOLD_TTL_EMIT;
|
||||
var changed = 0;
|
||||
|
||||
var messages = JSON.parse(localStorage.getItem(INDEX_EMIT) || '[]');
|
||||
for (var i = messages.length - 1; i >= 0; i--) {
|
||||
if (messages[i].timestamp < threshold) {
|
||||
messages.splice(i, 1);
|
||||
changed++;
|
||||
}
|
||||
}
|
||||
if (changed > 0) {
|
||||
localStorage.setItem(INDEX_EMIT, JSON.stringify(messages));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Intercom.prototype._cleanup_once = util.throttle(100, function() {
|
||||
var self = this;
|
||||
|
||||
this._transaction(function() {
|
||||
var timestamp, ttl, key;
|
||||
var table = JSON.parse(localStorage.getItem(INDEX_ONCE) || '{}');
|
||||
var now = (new Date()).getTime();
|
||||
var changed = 0;
|
||||
|
||||
for (key in table) {
|
||||
if (self._once_expired(key, table)) {
|
||||
delete table[key];
|
||||
changed++;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed > 0) {
|
||||
localStorage.setItem(INDEX_ONCE, JSON.stringify(table));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Intercom.prototype._once_expired = function(key, table) {
|
||||
if (!table) return true;
|
||||
if (!table.hasOwnProperty(key)) return true;
|
||||
if (typeof table[key] !== 'object') return true;
|
||||
var ttl = table[key].ttl || THRESHOLD_TTL_ONCE;
|
||||
var now = (new Date()).getTime();
|
||||
var timestamp = table[key].timestamp;
|
||||
return timestamp < now - ttl;
|
||||
};
|
||||
|
||||
Intercom.prototype._localStorageChanged = function(event, field) {
|
||||
if (event && event.key) {
|
||||
return event.key === field;
|
||||
}
|
||||
|
||||
var currentValue = localStorage.getItem(field);
|
||||
if (currentValue === this.previousValues[field]) {
|
||||
return false;
|
||||
}
|
||||
this.previousValues[field] = currentValue;
|
||||
return true;
|
||||
};
|
||||
|
||||
Intercom.prototype._onStorageEvent = function(event) {
|
||||
event = event || window.event;
|
||||
var self = this;
|
||||
|
||||
if (this._localStorageChanged(event, INDEX_EMIT)) {
|
||||
this._transaction(function() {
|
||||
var now = (new Date()).getTime();
|
||||
var data = localStorage.getItem(INDEX_EMIT);
|
||||
var messages = JSON.parse(data || '[]');
|
||||
for (var i = 0; i < messages.length; i++) {
|
||||
if (messages[i].origin === self.origin) continue;
|
||||
if (messages[i].timestamp < self.lastMessage) continue;
|
||||
if (messages[i].id) {
|
||||
if (self.receivedIDs.hasOwnProperty(messages[i].id)) continue;
|
||||
self.receivedIDs[messages[i].id] = true;
|
||||
}
|
||||
self.trigger(messages[i].name, messages[i].payload);
|
||||
}
|
||||
self.lastMessage = now;
|
||||
});
|
||||
}
|
||||
|
||||
this._trigger('storage', event);
|
||||
};
|
||||
|
||||
Intercom.prototype._emit = function(name, message, id) {
|
||||
id = (typeof id === 'string' || typeof id === 'number') ? String(id) : null;
|
||||
if (id && id.length) {
|
||||
if (this.receivedIDs.hasOwnProperty(id)) return;
|
||||
this.receivedIDs[id] = true;
|
||||
}
|
||||
|
||||
var packet = {
|
||||
id : id,
|
||||
name : name,
|
||||
origin : this.origin,
|
||||
timestamp : (new Date()).getTime(),
|
||||
payload : message
|
||||
};
|
||||
|
||||
var self = this;
|
||||
this._transaction(function() {
|
||||
var data = localStorage.getItem(INDEX_EMIT) || '[]';
|
||||
var delimiter = (data === '[]') ? '' : ',';
|
||||
data = [data.substring(0, data.length - 1), delimiter, JSON.stringify(packet), ']'].join('');
|
||||
localStorage.setItem(INDEX_EMIT, data);
|
||||
self.trigger(name, message);
|
||||
|
||||
window.setTimeout(function() { self._cleanup_emit(); }, 50);
|
||||
});
|
||||
};
|
||||
|
||||
Intercom.prototype.bind = function(object, options) {
|
||||
for (var i = 0; i < Intercom.bindings.length; i++) {
|
||||
var binding = Intercom.bindings[i].factory(object, options || null, this);
|
||||
if (binding) { this.bindings.push(binding); }
|
||||
}
|
||||
};
|
||||
|
||||
Intercom.prototype.emit = function(name, message) {
|
||||
this._emit.apply(this, arguments);
|
||||
this._trigger('emit', name, message);
|
||||
};
|
||||
|
||||
Intercom.prototype.once = function(key, fn, ttl) {
|
||||
if (!Intercom.supported) return;
|
||||
|
||||
var self = this;
|
||||
this._transaction(function() {
|
||||
var data = JSON.parse(localStorage.getItem(INDEX_ONCE) || '{}');
|
||||
if (!self._once_expired(key, data)) return;
|
||||
|
||||
data[key] = {};
|
||||
data[key].timestamp = (new Date()).getTime();
|
||||
if (typeof ttl === 'number') {
|
||||
data[key].ttl = ttl * 1000;
|
||||
}
|
||||
|
||||
localStorage.setItem(INDEX_ONCE, JSON.stringify(data));
|
||||
fn();
|
||||
|
||||
window.setTimeout(function() { self._cleanup_once(); }, 50);
|
||||
});
|
||||
};
|
||||
|
||||
util.extend(Intercom.prototype, EventEmitter.prototype);
|
||||
|
||||
Intercom.bindings = [];
|
||||
Intercom.supported = (typeof localStorage !== 'undefined');
|
||||
|
||||
var INDEX_EMIT = 'intercom';
|
||||
var INDEX_ONCE = 'intercom_once';
|
||||
var INDEX_LOCK = 'intercom_lock';
|
||||
|
||||
var THRESHOLD_TTL_EMIT = 50000;
|
||||
var THRESHOLD_TTL_ONCE = 1000 * 3600;
|
||||
|
||||
Intercom.destroy = function() {
|
||||
localStorage.removeItem(INDEX_LOCK);
|
||||
localStorage.removeItem(INDEX_EMIT);
|
||||
localStorage.removeItem(INDEX_ONCE);
|
||||
};
|
||||
|
||||
Intercom.getInstance = (function() {
|
||||
var intercom = null;
|
||||
return function() {
|
||||
if (!intercom) {
|
||||
intercom = new Intercom();
|
||||
}
|
||||
return intercom;
|
||||
};
|
||||
})();
|
||||
|
||||
// --- lib/bindings/socket.js ---
|
||||
|
||||
/**
|
||||
* Socket.io binding for intercom.js.
|
||||
*
|
||||
* - When a message is received on the socket, it's emitted on intercom.
|
||||
* - When a message is emitted via intercom, it's sent over the socket.
|
||||
*
|
||||
* @author Brian Reavis <brian@thirdroute.com>
|
||||
*/
|
||||
|
||||
var SocketBinding = function(socket, options, intercom) {
|
||||
options = util.extend({
|
||||
id : null,
|
||||
send : true,
|
||||
receive : true
|
||||
}, options);
|
||||
|
||||
if (options.receive) {
|
||||
var watchedEvents = [];
|
||||
var onEventAdded = function(name, fn) {
|
||||
if (watchedEvents.indexOf(name) === -1) {
|
||||
watchedEvents.push(name);
|
||||
socket.on(name, function(data) {
|
||||
var id = (typeof options.id === 'function') ? options.id(name, data) : null;
|
||||
var emit = (typeof options.receive === 'function') ? options.receive(name, data) : true;
|
||||
if (emit || typeof emit !== 'boolean') {
|
||||
intercom._emit(name, data, id);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
for (var name in intercom.handlers) {
|
||||
for (var i = 0; i < intercom.handlers[name].length; i++) {
|
||||
onEventAdded(name, intercom.handlers[name][i]);
|
||||
}
|
||||
}
|
||||
|
||||
intercom._on('on', onEventAdded);
|
||||
}
|
||||
|
||||
if (options.send) {
|
||||
intercom._on('emit', function(name, message) {
|
||||
var emit = (typeof options.send === 'function') ? options.send(name, message) : true;
|
||||
if (emit || typeof emit !== 'boolean') {
|
||||
socket.emit(name, message);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
SocketBinding.factory = function(object, options, intercom) {
|
||||
if (typeof object.socket === 'undefined') { return false };
|
||||
return new SocketBinding(object, options, intercom);
|
||||
};
|
||||
|
||||
Intercom.bindings.push(SocketBinding);
|
||||
return Intercom;
|
||||
})();
|
||||
Vendored
+12
@@ -0,0 +1,12 @@
|
||||
/*! intercom.js | https://github.com/diy/intercom.js | Apache License (v2) */
|
||||
var Intercom=function(){var g=function(){};g.createInterface=function(b){return{on:function(a,c){"undefined"===typeof this[b]&&(this[b]={});this[b].hasOwnProperty(a)||(this[b][a]=[]);this[b][a].push(c)},off:function(a,c){"undefined"!==typeof this[b]&&this[b].hasOwnProperty(a)&&i.removeItem(c,this[b][a])},trigger:function(a){if("undefined"!==typeof this[b]&&this[b].hasOwnProperty(a))for(var c=Array.prototype.slice.call(arguments,1),e=0;e<this[b][a].length;e++)this[b][a][e].apply(this[b][a][e],c)}}};
|
||||
var m=g.createInterface("_handlers");g.prototype._on=m.on;g.prototype._off=m.off;g.prototype._trigger=m.trigger;var n=g.createInterface("handlers");g.prototype.on=function(){n.on.apply(this,arguments);Array.prototype.unshift.call(arguments,"on");this._trigger.apply(this,arguments)};g.prototype.off=n.off;g.prototype.trigger=n.trigger;var f=window.localStorage;"undefined"===typeof f&&(f={getItem:function(){},setItem:function(){},removeItem:function(){}});var i={},h=function(){return(65536*(1+Math.random())|
|
||||
0).toString(16).substring(1)};i.guid=function(){return h()+h()+"-"+h()+"-"+h()+"-"+h()+"-"+h()+h()+h()};i.throttle=function(b,a){var c=0;return function(){var e=(new Date).getTime();e-c>b&&(c=e,a.apply(this,arguments))}};i.extend=function(b,a){if("undefined"===typeof b||!b)b={};if("object"===typeof a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b};i.removeItem=function(b,a){for(var c=a.length-1;0<=c;c--)a[c]===b&&a.splice(c,1);return a};var d=function(){var b=this,a=(new Date).getTime();
|
||||
this.origin=i.guid();this.lastMessage=a;this.bindings=[];this.receivedIDs={};this.previousValues={};a=function(){b._onStorageEvent.apply(b,arguments)};window.attachEvent?document.attachEvent("onstorage",a):window.addEventListener("storage",a,!1)};d.prototype._transaction=function(b){var a=this,c=!1,e=!1,p=null,d=function(){if(!c){var g=(new Date).getTime(),s=parseInt(f.getItem(l)||0);s&&1E3>g-s?(e||(a._on("storage",d),e=!0),p=window.setTimeout(d,20)):(c=!0,f.setItem(l,g),b(),e&&a._off("storage",d),
|
||||
p&&window.clearTimeout(p),f.removeItem(l))}};d()};d.prototype._cleanup_emit=i.throttle(100,function(){this._transaction(function(){for(var b=(new Date).getTime()-t,a=0,c=JSON.parse(f.getItem(j)||"[]"),e=c.length-1;0<=e;e--)c[e].timestamp<b&&(c.splice(e,1),a++);0<a&&f.setItem(j,JSON.stringify(c))})});d.prototype._cleanup_once=i.throttle(100,function(){var b=this;this._transaction(function(){var a,c=JSON.parse(f.getItem(k)||"{}");(new Date).getTime();var e=0;for(a in c)b._once_expired(a,c)&&(delete c[a],
|
||||
e++);0<e&&f.setItem(k,JSON.stringify(c))})});d.prototype._once_expired=function(b,a){if(!a||!a.hasOwnProperty(b)||"object"!==typeof a[b])return!0;var c=a[b].ttl||u,e=(new Date).getTime();return a[b].timestamp<e-c};d.prototype._localStorageChanged=function(b,a){if(b&&b.key)return b.key===a;var c=f.getItem(a);if(c===this.previousValues[a])return!1;this.previousValues[a]=c;return!0};d.prototype._onStorageEvent=function(b){var b=b||window.event,a=this;this._localStorageChanged(b,j)&&this._transaction(function(){for(var b=
|
||||
(new Date).getTime(),e=f.getItem(j),e=JSON.parse(e||"[]"),d=0;d<e.length;d++)if(e[d].origin!==a.origin&&!(e[d].timestamp<a.lastMessage)){if(e[d].id){if(a.receivedIDs.hasOwnProperty(e[d].id))continue;a.receivedIDs[e[d].id]=!0}a.trigger(e[d].name,e[d].payload)}a.lastMessage=b});this._trigger("storage",b)};d.prototype._emit=function(b,a,c){if((c="string"===typeof c||"number"===typeof c?String(c):null)&&c.length){if(this.receivedIDs.hasOwnProperty(c))return;this.receivedIDs[c]=!0}var e={id:c,name:b,origin:this.origin,
|
||||
timestamp:(new Date).getTime(),payload:a},d=this;this._transaction(function(){var c=f.getItem(j)||"[]",c=[c.substring(0,c.length-1),"[]"===c?"":",",JSON.stringify(e),"]"].join("");f.setItem(j,c);d.trigger(b,a);window.setTimeout(function(){d._cleanup_emit()},50)})};d.prototype.bind=function(b,a){for(var c=0;c<d.bindings.length;c++){var e=d.bindings[c].factory(b,a||null,this);e&&this.bindings.push(e)}};d.prototype.emit=function(b,a){this._emit.apply(this,arguments);this._trigger("emit",b,a)};d.prototype.once=
|
||||
function(b,a,c){if(d.supported){var e=this;this._transaction(function(){var d=JSON.parse(f.getItem(k)||"{}");e._once_expired(b,d)&&(d[b]={},d[b].timestamp=(new Date).getTime(),"number"===typeof c&&(d[b].ttl=1E3*c),f.setItem(k,JSON.stringify(d)),a(),window.setTimeout(function(){e._cleanup_once()},50))})}};i.extend(d.prototype,g.prototype);d.bindings=[];d.supported="undefined"!==typeof f;var j="intercom",k="intercom_once",l="intercom_lock",t=5E4,u=36E5;d.destroy=function(){f.removeItem(l);f.removeItem(j);
|
||||
f.removeItem(k)};var q=null;d.getInstance=function(){q||(q=new d);return q};var r=function(b,a,c){a=i.extend({id:null,send:!0,receive:!0},a);if(a.receive){var d=[],f=function(f){-1===d.indexOf(f)&&(d.push(f),b.on(f,function(b){var d="function"===typeof a.id?a.id(f,b):null,e="function"===typeof a.receive?a.receive(f,b):!0;(e||"boolean"!==typeof e)&&c._emit(f,b,d)}))},g;for(g in c.handlers)for(var h=0;h<c.handlers[g].length;h++)f(g,c.handlers[g][h]);c._on("on",f)}a.send&&c._on("emit",function(c,d){var e=
|
||||
"function"===typeof a.send?a.send(c,d):!0;(e||"boolean"!==typeof e)&&b.emit(c,d)})};r.factory=function(b,a,c){return"undefined"===typeof b.socket?!1:new r(b,a,c)};d.bindings.push(r);return d}();
|
||||
Vendored
+10220
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,390 @@
|
||||
(function () {
|
||||
var isCommonJS = typeof module !== 'undefined' && module.exports;
|
||||
var isNode = !(typeof window !== 'undefined' && this === window);
|
||||
var setImmediate = setImmediate || function (cb) {
|
||||
setTimeout(cb, 0);
|
||||
};
|
||||
var Worker = isNode ? require(__dirname + '/Worker.js') : self.Worker;
|
||||
var URL = typeof self !== 'undefined' ? (self.URL ? self.URL : self.webkitURL) : null;
|
||||
var _supports = (isNode || self.Worker) ? true : false; // node always supports parallel
|
||||
|
||||
function extend(from, to) {
|
||||
if (!to) to = {};
|
||||
for (var i in from) {
|
||||
if (to[i] === undefined) to[i] = from[i];
|
||||
}
|
||||
return to;
|
||||
}
|
||||
|
||||
function Operation() {
|
||||
this._callbacks = [];
|
||||
this._errCallbacks = [];
|
||||
|
||||
this._resolved = 0;
|
||||
this._result = null;
|
||||
}
|
||||
|
||||
Operation.prototype.resolve = function (err, res) {
|
||||
if (!err) {
|
||||
this._resolved = 1;
|
||||
this._result = res;
|
||||
|
||||
for (var i = 0; i < this._callbacks.length; ++i) {
|
||||
this._callbacks[i](res);
|
||||
}
|
||||
} else {
|
||||
this._resolved = 2;
|
||||
this._result = err;
|
||||
|
||||
for (var iE = 0; iE < this._errCallbacks.length; ++iE) {
|
||||
this._errCallbacks[iE](err);
|
||||
}
|
||||
}
|
||||
|
||||
this._callbacks = [];
|
||||
this._errCallbacks = [];
|
||||
};
|
||||
|
||||
Operation.prototype.then = function (cb, errCb) {
|
||||
if (this._resolved === 1) { // result
|
||||
if (cb) {
|
||||
cb(this._result);
|
||||
}
|
||||
|
||||
return;
|
||||
} else if (this._resolved === 2) { // error
|
||||
if (errCb) {
|
||||
errCb(this._result);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (cb) {
|
||||
this._callbacks[this._callbacks.length] = cb;
|
||||
}
|
||||
|
||||
if (errCb) {
|
||||
this._errCallbacks[this._errCallbacks.length] = errCb;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
var defaults = {
|
||||
evalPath: isNode ? __dirname + '/eval.js' : null,
|
||||
maxWorkers: isNode ? require('os').cpus().length : (navigator.hardwareConcurrency || 4),
|
||||
synchronous: true,
|
||||
env: {},
|
||||
envNamespace: 'env'
|
||||
};
|
||||
|
||||
function Parallel(data, options) {
|
||||
this.data = data;
|
||||
this.options = extend(defaults, options);
|
||||
this.operation = new Operation();
|
||||
this.operation.resolve(null, this.data);
|
||||
this.requiredScripts = [];
|
||||
this.requiredFunctions = [];
|
||||
}
|
||||
|
||||
// static method
|
||||
Parallel.isSupported = function () { return _supports; }
|
||||
|
||||
Parallel.prototype.getWorkerSource = function (cb, env) {
|
||||
var that = this;
|
||||
var preStr = '';
|
||||
var i = 0;
|
||||
if (!isNode && this.requiredScripts.length !== 0) {
|
||||
preStr += 'importScripts("' + this.requiredScripts.join('","') + '");\r\n';
|
||||
}
|
||||
|
||||
for (i = 0; i < this.requiredFunctions.length; ++i) {
|
||||
if (this.requiredFunctions[i].name) {
|
||||
preStr += 'var ' + this.requiredFunctions[i].name + ' = ' + this.requiredFunctions[i].fn.toString() + ';';
|
||||
} else {
|
||||
preStr += this.requiredFunctions[i].fn.toString();
|
||||
}
|
||||
}
|
||||
|
||||
env = JSON.stringify(env || {});
|
||||
|
||||
var ns = this.options.envNamespace;
|
||||
|
||||
if (isNode) {
|
||||
return preStr + 'process.on("message", function(e) {global.' + ns + ' = ' + env + ';process.send(JSON.stringify((' + cb.toString() + ')(JSON.parse(e).data)))})';
|
||||
} else {
|
||||
return preStr + 'self.onmessage = function(e) {var global = {}; global.' + ns + ' = ' + env + ';self.postMessage((' + cb.toString() + ')(e.data))}';
|
||||
}
|
||||
};
|
||||
|
||||
Parallel.prototype.require = function () {
|
||||
var args = Array.prototype.slice.call(arguments, 0),
|
||||
func;
|
||||
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
func = args[i];
|
||||
|
||||
if (typeof func === 'string') {
|
||||
this.requiredScripts.push(func);
|
||||
} else if (typeof func === 'function') {
|
||||
this.requiredFunctions.push({ fn: func });
|
||||
} else if (typeof func === 'object') {
|
||||
this.requiredFunctions.push(func);
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
Parallel.prototype._spawnWorker = function (cb, env) {
|
||||
var wrk;
|
||||
var src = this.getWorkerSource(cb, env);
|
||||
if (isNode) {
|
||||
wrk = new Worker(this.options.evalPath);
|
||||
wrk.postMessage(src);
|
||||
} else {
|
||||
if (Worker === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
if (this.requiredScripts.length !== 0) {
|
||||
if (this.options.evalPath !== null) {
|
||||
wrk = new Worker(this.options.evalPath);
|
||||
wrk.postMessage(src);
|
||||
} else {
|
||||
throw new Error('Can\'t use required scripts without eval.js!');
|
||||
}
|
||||
} else if (!URL) {
|
||||
throw new Error('Can\'t create a blob URL in this browser!');
|
||||
} else {
|
||||
var blob = new Blob([src], { type: 'text/javascript' });
|
||||
var url = URL.createObjectURL(blob);
|
||||
|
||||
wrk = new Worker(url);
|
||||
}
|
||||
} catch (e) {
|
||||
if (this.options.evalPath !== null) { // blob/url unsupported, cross-origin error
|
||||
wrk = new Worker(this.options.evalPath);
|
||||
wrk.postMessage(src);
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return wrk;
|
||||
};
|
||||
|
||||
Parallel.prototype.spawn = function (cb, env) {
|
||||
var that = this;
|
||||
var newOp = new Operation();
|
||||
|
||||
env = extend(this.options.env, env || {});
|
||||
|
||||
this.operation.then(function () {
|
||||
var wrk = that._spawnWorker(cb, env);
|
||||
if (wrk !== undefined) {
|
||||
wrk.onmessage = function (msg) {
|
||||
wrk.terminate();
|
||||
that.data = msg.data;
|
||||
newOp.resolve(null, that.data);
|
||||
};
|
||||
wrk.onerror = function (e) {
|
||||
wrk.terminate();
|
||||
newOp.resolve(e, null);
|
||||
};
|
||||
wrk.postMessage(that.data);
|
||||
} else if (that.options.synchronous) {
|
||||
setImmediate(function () {
|
||||
try {
|
||||
that.data = cb(that.data);
|
||||
newOp.resolve(null, that.data);
|
||||
} catch (e) {
|
||||
newOp.resolve(e, null);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
throw new Error('Workers do not exist and synchronous operation not allowed!');
|
||||
}
|
||||
});
|
||||
this.operation = newOp;
|
||||
return this;
|
||||
};
|
||||
|
||||
Parallel.prototype._spawnMapWorker = function (i, cb, done, env, wrk) {
|
||||
var that = this;
|
||||
|
||||
if (!wrk) wrk = that._spawnWorker(cb, env);
|
||||
|
||||
if (wrk !== undefined) {
|
||||
wrk.onmessage = function (msg) {
|
||||
that.data[i] = msg.data;
|
||||
done(null, wrk);
|
||||
};
|
||||
wrk.onerror = function (e) {
|
||||
wrk.terminate();
|
||||
done(e);
|
||||
};
|
||||
wrk.postMessage(that.data[i]);
|
||||
} else if (that.options.synchronous) {
|
||||
setImmediate(function () {
|
||||
that.data[i] = cb(that.data[i]);
|
||||
done();
|
||||
});
|
||||
} else {
|
||||
throw new Error('Workers do not exist and synchronous operation not allowed!');
|
||||
}
|
||||
};
|
||||
|
||||
Parallel.prototype.map = function (cb, env) {
|
||||
env = extend(this.options.env, env || {});
|
||||
|
||||
if (!this.data.length) {
|
||||
return this.spawn(cb, env);
|
||||
}
|
||||
|
||||
var that = this;
|
||||
var startedOps = 0;
|
||||
var doneOps = 0;
|
||||
function done(err, wrk) {
|
||||
if (err) {
|
||||
newOp.resolve(err, null);
|
||||
} else if (++doneOps === that.data.length) {
|
||||
newOp.resolve(null, that.data);
|
||||
if (wrk) wrk.terminate();
|
||||
} else if (startedOps < that.data.length) {
|
||||
that._spawnMapWorker(startedOps++, cb, done, env, wrk);
|
||||
} else {
|
||||
if (wrk) wrk.terminate();
|
||||
}
|
||||
}
|
||||
|
||||
var newOp = new Operation();
|
||||
this.operation.then(function () {
|
||||
for (; startedOps - doneOps < that.options.maxWorkers && startedOps < that.data.length; ++startedOps) {
|
||||
that._spawnMapWorker(startedOps, cb, done, env);
|
||||
}
|
||||
}, function (err) {
|
||||
newOp.resolve(err, null);
|
||||
});
|
||||
this.operation = newOp;
|
||||
return this;
|
||||
};
|
||||
|
||||
Parallel.prototype._spawnReduceWorker = function (data, cb, done, env, wrk) {
|
||||
var that = this;
|
||||
if (!wrk) wrk = that._spawnWorker(cb, env);
|
||||
|
||||
if (wrk !== undefined) {
|
||||
wrk.onmessage = function (msg) {
|
||||
that.data[that.data.length] = msg.data;
|
||||
done(null, wrk);
|
||||
};
|
||||
wrk.onerror = function (e) {
|
||||
wrk.terminate();
|
||||
done(e, null);
|
||||
}
|
||||
wrk.postMessage(data);
|
||||
} else if (that.options.synchronous) {
|
||||
setImmediate(function () {
|
||||
that.data[that.data.length] = cb(data);
|
||||
done();
|
||||
});
|
||||
} else {
|
||||
throw new Error('Workers do not exist and synchronous operation not allowed!');
|
||||
}
|
||||
};
|
||||
|
||||
Parallel.prototype.reduce = function (cb, env) {
|
||||
env = extend(this.options.env, env || {});
|
||||
|
||||
if (!this.data.length) {
|
||||
throw new Error('Can\'t reduce non-array data');
|
||||
}
|
||||
|
||||
var runningWorkers = 0;
|
||||
var that = this;
|
||||
function done(err, wrk) {
|
||||
--runningWorkers;
|
||||
if (err) {
|
||||
newOp.resolve(err, null);
|
||||
} else if (that.data.length === 1 && runningWorkers === 0) {
|
||||
that.data = that.data[0];
|
||||
newOp.resolve(null, that.data);
|
||||
if (wrk) wrk.terminate();
|
||||
} else if (that.data.length > 1) {
|
||||
++runningWorkers;
|
||||
that._spawnReduceWorker([that.data[0], that.data[1]], cb, done, env, wrk);
|
||||
that.data.splice(0, 2);
|
||||
} else {
|
||||
if (wrk) wrk.terminate();
|
||||
}
|
||||
}
|
||||
|
||||
var newOp = new Operation();
|
||||
this.operation.then(function () {
|
||||
if (that.data.length === 1) {
|
||||
newOp.resolve(null, that.data[0]);
|
||||
} else {
|
||||
for (var i = 0; i < that.options.maxWorkers && i < Math.floor(that.data.length / 2) ; ++i) {
|
||||
++runningWorkers;
|
||||
that._spawnReduceWorker([that.data[i * 2], that.data[i * 2 + 1]], cb, done, env);
|
||||
}
|
||||
|
||||
that.data.splice(0, i * 2);
|
||||
}
|
||||
});
|
||||
this.operation = newOp;
|
||||
return this;
|
||||
};
|
||||
|
||||
Parallel.prototype.then = function (cb, errCb) {
|
||||
var that = this;
|
||||
var newOp = new Operation();
|
||||
errCb = typeof errCb === 'function' ? errCb : function(){};
|
||||
|
||||
this.operation.then(function () {
|
||||
var retData;
|
||||
|
||||
try {
|
||||
if (cb) {
|
||||
retData = cb(that.data);
|
||||
if (retData !== undefined) {
|
||||
that.data = retData;
|
||||
}
|
||||
}
|
||||
newOp.resolve(null, that.data);
|
||||
} catch (e) {
|
||||
if (errCb) {
|
||||
retData = errCb(e);
|
||||
if (retData !== undefined) {
|
||||
that.data = retData;
|
||||
}
|
||||
|
||||
newOp.resolve(null, that.data);
|
||||
} else {
|
||||
newOp.resolve(null, e);
|
||||
}
|
||||
}
|
||||
}, function (err) {
|
||||
if (errCb) {
|
||||
var retData = errCb(err);
|
||||
if (retData !== undefined) {
|
||||
that.data = retData;
|
||||
}
|
||||
|
||||
newOp.resolve(null, that.data);
|
||||
} else {
|
||||
newOp.resolve(null, err);
|
||||
}
|
||||
});
|
||||
this.operation = newOp;
|
||||
return this;
|
||||
};
|
||||
|
||||
if (isCommonJS) {
|
||||
module.exports = Parallel;
|
||||
} else {
|
||||
self.Parallel = Parallel;
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,195 @@
|
||||
function doInterpolation(sampleSet, remainderSet, interpSubset, properties) {
|
||||
var distance = calculateDistancePoker;
|
||||
// var distance = calculateEuclideanDistance;
|
||||
|
||||
console.log("Brute-force");
|
||||
|
||||
for (var i = 0; i < remainderSet.length; i++) {
|
||||
var node = remainderSet[i],
|
||||
minNode = sampleSet[0],
|
||||
minDist = 0,
|
||||
sampleCache = [];
|
||||
|
||||
minDist = distance(node, minNode, properties);
|
||||
|
||||
for (var j = 1, sample; j < sampleSet.length; j++) {
|
||||
sample = sampleSet[j];
|
||||
if ((sample !== node) && (distance(node, sample, properties) < minDist)) {
|
||||
minDist = distance(node, sample, properties);
|
||||
minNode = sample;
|
||||
}
|
||||
}
|
||||
|
||||
// console.log()
|
||||
|
||||
for (var k = 0; k < interpSubset.length; k++) {
|
||||
sampleCache[k] = distance(node, interpSubset[k], properties);
|
||||
}
|
||||
var radius = distance(node, minNode, properties);
|
||||
placeNearToNearestNeighbour(node, minNode, interpSubset, sampleCache, radius);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function placeNearToNearestNeighbour(node, minNode, sample, sampleCache, radius) {
|
||||
var
|
||||
dist0 = 0.0,
|
||||
dist90 = 0.0,
|
||||
dist180 = 0.0,
|
||||
dist270 = 0.0,
|
||||
lowBound = 0.0,
|
||||
highBound = 0.0;
|
||||
|
||||
dist0 = sumDistToSample(node, centerPoint(0, radius, minNode.x, minNode.y), sample, sampleCache);
|
||||
dist90 = sumDistToSample(node, centerPoint(90, radius, minNode.x, minNode.y), sample, sampleCache);
|
||||
dist180 = sumDistToSample(node, centerPoint(180, radius, minNode.x, minNode.y), sample, sampleCache);
|
||||
dist270 = sumDistToSample(node, centerPoint(270, radius, minNode.x, minNode.y), sample, sampleCache);
|
||||
|
||||
// console.log(dist0, dist90, dist180, dist270);
|
||||
|
||||
// Determine the closest quadrant
|
||||
|
||||
if (dist0 == dist180) {
|
||||
if (dist90 > dist270)
|
||||
lowBound = highBound = 270;
|
||||
else
|
||||
lowBound = highBound = 90;
|
||||
|
||||
} else if (dist90 == dist270) {
|
||||
if (dist0 > dist180)
|
||||
lowBound = highBound = 180;
|
||||
else
|
||||
lowBound = highBound = 0;
|
||||
} else if (dist0 > dist180) {
|
||||
if (dist90 > dist270) {
|
||||
lowBound = 180;
|
||||
highBound = 270;
|
||||
} else {
|
||||
lowBound = 90;
|
||||
highBound = 180;
|
||||
}
|
||||
} else {
|
||||
if (dist90 > dist270) {
|
||||
lowBound = 270;
|
||||
highBound = 360;
|
||||
} else {
|
||||
lowBound = 0;
|
||||
highBound = 90;
|
||||
}
|
||||
}
|
||||
|
||||
var angle = binarySearch(lowBound, highBound, minNode.x, minNode.y, radius, node, sample, sampleCache);
|
||||
var newPoint = centerPoint(angle, radius, minNode.x, minNode.y);
|
||||
|
||||
// console.log(newPoint);
|
||||
node.x = newPoint.x;
|
||||
node.y = newPoint.y;
|
||||
|
||||
// for (var i = 0; i < 20; i++) {
|
||||
// var forces = sumForcesToSample(node, sample, sampleCache);
|
||||
// // console.log(forces);
|
||||
// node.x += forces.x;
|
||||
// node.y += forces.y;
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
|
||||
function centerPoint(angle, radius, posX, posY) {
|
||||
var x = posX + Math.cos(toRadians(angle) * radius);
|
||||
var y = posY + Math.sin(toRadians(angle) * radius);
|
||||
|
||||
return {
|
||||
x: x,
|
||||
y: y
|
||||
};
|
||||
}
|
||||
|
||||
function toRadians(degrees) {
|
||||
return degrees * (Math.PI / 180);
|
||||
}
|
||||
|
||||
function sumDistToSample(node, point, sample, sampleCache) {
|
||||
var total = 0.0;
|
||||
// console.log(total, sample);
|
||||
|
||||
for (var i = 0; i < sample.length; i++) {
|
||||
var s = sample[i];
|
||||
var realDist = Math.hypot(s.x - point.x, s.y - point.y);
|
||||
var desDist = sampleCache[i];
|
||||
total += Math.abs(realDist - desDist);
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
|
||||
function sumForcesToSample(node, sample, sampleCache) {
|
||||
var x = 0,
|
||||
y = 0,
|
||||
// len = 0,
|
||||
dist = 0,
|
||||
force,
|
||||
SPRING_FORCE = 0.7;
|
||||
|
||||
for (var i = 0, unitX, unitY; i < sample.length; i++) {
|
||||
var s = sample[i];
|
||||
if (s !== node) {
|
||||
unitX = s.x - node.x;
|
||||
unitY = s.y - node.y;
|
||||
|
||||
// Normalize coordinates
|
||||
len = Math.sqrt(unitX * unitX + unitY * unitY);
|
||||
unitX /= len;
|
||||
unitY /= len;
|
||||
|
||||
console.log(unitX, unitY);
|
||||
|
||||
var realDist = Math.sqrt(unitX * unitX + unitY * unitY);
|
||||
var desDist = sampleCache[i];
|
||||
dist += realDist - desDist;
|
||||
force = (SPRING_FORCE * dist);
|
||||
|
||||
x += unitX * force;
|
||||
y += unitY * force;
|
||||
}
|
||||
|
||||
x *= (1.0 / sample.length);
|
||||
y *= (1.0 / sample.length);
|
||||
|
||||
return {
|
||||
x: x,
|
||||
y: y
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function binarySearch(lb, hb, x, y, r, node, sample, sampleCache) {
|
||||
while (lb <= hb) {
|
||||
var mid = Math.round((lb + hb) / 2);
|
||||
|
||||
if ((mid === lb) || (mid === hb)) {
|
||||
if (sumDistToSample(node, centerPoint(lb, r, x, y), sample, sampleCache) >=
|
||||
sumDistToSample(node, centerPoint(hb, r, x, y), sample, sampleCache)) {
|
||||
return hb;
|
||||
} else {
|
||||
return lb;
|
||||
}
|
||||
} else {
|
||||
var distMidLeft = sumDistToSample(node, centerPoint(mid + 1, r, x, y), sample, sampleCache);
|
||||
var distMidRight = sumDistToSample(node, centerPoint(mid - 1, r, x, y), sample, sampleCache);
|
||||
var distMid = sumDistToSample(node, centerPoint(mid, r, x, y), sample, sampleCache);
|
||||
|
||||
if (distMid > distMidLeft) {
|
||||
lb = mid + 1;
|
||||
} else if (distMid > distMidRight) {
|
||||
hb = mid - 1;
|
||||
} else {
|
||||
return mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
function doInterpolationPivots(sampleSet, remainderSet, interpSubset, properties) {
|
||||
var distance = calculateDistancePoker;
|
||||
// var distance = calculateEuclideanDistance;
|
||||
|
||||
// Pivot based parent finding
|
||||
|
||||
var numBuckets = Math.floor(Math.sqrt(sampleSet.length)),
|
||||
// numPivots = Math.floor(Math.sqrt(sampleSet.length)),
|
||||
numPivots = 3,
|
||||
parents = [],
|
||||
maxDists = [],
|
||||
bucketWidths = [],
|
||||
pivotsBuckets = [];
|
||||
|
||||
console.log("Parents, pivots=", numPivots);
|
||||
|
||||
var pivots = createRandomSample(sampleSet.concat(remainderSet), sampleSet.length, numPivots);
|
||||
|
||||
for (var i = 0; i < numPivots; i++) {
|
||||
pivotsBuckets[i] = [];
|
||||
for (var j = 0; j < numBuckets; j++) {
|
||||
pivotsBuckets[i][j] = [];
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-processing
|
||||
var fullDists = []
|
||||
for (var i = 0; i < sampleSet.length; i++) {
|
||||
fullDists[i] = [];
|
||||
}
|
||||
|
||||
for (var j = 0, maxDist = -1; j < numPivots; j++) {
|
||||
var c1 = pivots[j];
|
||||
for (var i = 0; i < sampleSet.length; i++) {
|
||||
var c2 = sampleSet[i];
|
||||
if (c1 !== c2) {
|
||||
var dist = distance(c1, c2, properties);
|
||||
// console.log(dist, c1, c2);
|
||||
if (dist > maxDist) {
|
||||
maxDist = dist;
|
||||
}
|
||||
fullDists[i][j] = dist;
|
||||
} else {
|
||||
fullDists[i][j] = 0.0001;
|
||||
}
|
||||
}
|
||||
maxDists.push(maxDist);
|
||||
bucketWidths.push(maxDist / numBuckets);
|
||||
}
|
||||
|
||||
// console.log(fullDists);
|
||||
|
||||
for (var j = 0; j < numPivots; j++) {
|
||||
var bucketWidth = bucketWidths[j];
|
||||
for (var i = 0; i < sampleSet.length; i++) {
|
||||
var tmp = pivotsBuckets[j][Math.floor((fullDists[i][j] - 0.0001) / bucketWidth)];
|
||||
// pivotsBuckets[j][Math.floor((fullDists[i][j] - 0.0001) / bucketWidth)].push(sampleSet[i]);
|
||||
// console.log(tmp, i, j, bucketWidth, Math.floor((fullDists[i][j] - 0.0001) / bucketWidth));
|
||||
tmp.push(sampleSet[i]);
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < remainderSet.length; i++) {
|
||||
var node = remainderSet[i],
|
||||
minNode = sampleSet[0],
|
||||
minDist = 0,
|
||||
sampleCache = [];
|
||||
|
||||
// Pivot based parent search
|
||||
|
||||
var node = remainderSet[i];
|
||||
var clDist = Number.MAX_VALUE;
|
||||
for (var p = 0; p < numPivots; p++) {
|
||||
var comp = pivots[p];
|
||||
var bucketWidth = bucketWidths[p];
|
||||
if (node !== comp) {
|
||||
var dist = distance(node, comp, properties);
|
||||
bNum = Math.floor((dist - 0.0001) / bucketWidth);
|
||||
if (bNum >= numBuckets) {
|
||||
bNum = numBuckets - 1;
|
||||
} else if (bNum < 0) {
|
||||
bNum = 0;
|
||||
}
|
||||
var bucketContents = pivotsBuckets[p][bNum];
|
||||
for (var w = 0; w < bucketContents.length; w++) {
|
||||
var c1 = bucketContents[w];
|
||||
if (c1 != node) {
|
||||
dist = distance(c1, node, properties);
|
||||
if (dist <= clDist) {
|
||||
clDist = dist;
|
||||
minNode = bucketContents[w];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for (var k = 0; k < interpSubset.length; k++) {
|
||||
sampleCache[k] = distance(node, interpSubset[k], properties);
|
||||
}
|
||||
var radius = distance(node, minNode, properties);
|
||||
placeNearToNearestNeighbour(node, minNode, interpSubset, sampleCache, radius);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function placeNearToNearestNeighbour(node, minNode, sample, sampleCache, radius) {
|
||||
var
|
||||
dist0 = 0.0,
|
||||
dist90 = 0.0,
|
||||
dist180 = 0.0,
|
||||
dist270 = 0.0,
|
||||
lowBound = 0.0,
|
||||
highBound = 0.0;
|
||||
|
||||
dist0 = sumDistToSample(node, centerPoint(0, radius, minNode.x, minNode.y), sample, sampleCache);
|
||||
dist90 = sumDistToSample(node, centerPoint(90, radius, minNode.x, minNode.y), sample, sampleCache);
|
||||
dist180 = sumDistToSample(node, centerPoint(180, radius, minNode.x, minNode.y), sample, sampleCache);
|
||||
dist270 = sumDistToSample(node, centerPoint(270, radius, minNode.x, minNode.y), sample, sampleCache);
|
||||
|
||||
// console.log(dist0, dist90, dist180, dist270);
|
||||
|
||||
// Determine the closest quadrant
|
||||
|
||||
if (dist0 == dist180) {
|
||||
if (dist90 > dist270)
|
||||
lowBound = highBound = 270;
|
||||
else
|
||||
lowBound = highBound = 90;
|
||||
|
||||
} else if (dist90 == dist270) {
|
||||
if (dist0 > dist180)
|
||||
lowBound = highBound = 180;
|
||||
else
|
||||
lowBound = highBound = 0;
|
||||
} else if (dist0 > dist180) {
|
||||
if (dist90 > dist270) {
|
||||
lowBound = 180;
|
||||
highBound = 270;
|
||||
} else {
|
||||
lowBound = 90;
|
||||
highBound = 180;
|
||||
}
|
||||
} else {
|
||||
if (dist90 > dist270) {
|
||||
lowBound = 270;
|
||||
highBound = 360;
|
||||
} else {
|
||||
lowBound = 0;
|
||||
highBound = 90;
|
||||
}
|
||||
}
|
||||
|
||||
var angle = binarySearch(lowBound, highBound, minNode.x, minNode.y, radius, node, sample, sampleCache);
|
||||
var newPoint = centerPoint(angle, radius, minNode.x, minNode.y);
|
||||
|
||||
// console.log(newPoint);
|
||||
node.x = newPoint.x;
|
||||
node.y = newPoint.y;
|
||||
|
||||
// for (var i = 0; i < 20; i++) {
|
||||
// var forces = sumForcesToSample(node, sample, sampleCache);
|
||||
// // console.log(forces);
|
||||
// node.x += forces.x;
|
||||
// node.y += forces.y;
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
|
||||
function centerPoint(angle, radius, posX, posY) {
|
||||
var x = posX + Math.cos(toRadians(angle) * radius);
|
||||
var y = posY + Math.sin(toRadians(angle) * radius);
|
||||
|
||||
return {
|
||||
x: x,
|
||||
y: y
|
||||
};
|
||||
}
|
||||
|
||||
function toRadians(degrees) {
|
||||
return degrees * (Math.PI / 180);
|
||||
}
|
||||
|
||||
function sumDistToSample(node, point, sample, sampleCache) {
|
||||
var total = 0.0;
|
||||
// console.log(total, sample);
|
||||
|
||||
for (var i = 0; i < sample.length; i++) {
|
||||
var s = sample[i];
|
||||
var realDist = Math.hypot(s.x - point.x, s.y - point.y);
|
||||
var desDist = sampleCache[i];
|
||||
total += Math.abs(realDist - desDist);
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
|
||||
function sumForcesToSample(node, sample, sampleCache) {
|
||||
var x = 0,
|
||||
y = 0,
|
||||
// len = 0,
|
||||
dist = 0,
|
||||
force,
|
||||
SPRING_FORCE = 0.7;
|
||||
|
||||
for (var i = 0, unitX, unitY; i < sample.length; i++) {
|
||||
var s = sample[i];
|
||||
if (s !== node) {
|
||||
unitX = s.x - node.x;
|
||||
unitY = s.y - node.y;
|
||||
|
||||
// Normalize coordinates
|
||||
len = Math.sqrt(unitX * unitX + unitY * unitY);
|
||||
unitX /= len;
|
||||
unitY /= len;
|
||||
|
||||
console.log(unitX, unitY);
|
||||
|
||||
var realDist = Math.sqrt(unitX * unitX + unitY * unitY);
|
||||
var desDist = sampleCache[i];
|
||||
dist += realDist - desDist;
|
||||
force = (SPRING_FORCE * dist);
|
||||
|
||||
x += unitX * force;
|
||||
y += unitY * force;
|
||||
}
|
||||
|
||||
x *= (1.0 / sample.length);
|
||||
y *= (1.0 / sample.length);
|
||||
|
||||
return {
|
||||
x: x,
|
||||
y: y
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function binarySearch(lb, hb, x, y, r, node, sample, sampleCache) {
|
||||
while (lb <= hb) {
|
||||
var mid = Math.round((lb + hb) / 2);
|
||||
|
||||
if ((mid === lb) || (mid === hb)) {
|
||||
if (sumDistToSample(node, centerPoint(lb, r, x, y), sample, sampleCache) >=
|
||||
sumDistToSample(node, centerPoint(hb, r, x, y), sample, sampleCache)) {
|
||||
return hb;
|
||||
} else {
|
||||
return lb;
|
||||
}
|
||||
} else {
|
||||
var distMidLeft = sumDistToSample(node, centerPoint(mid + 1, r, x, y), sample, sampleCache);
|
||||
var distMidRight = sumDistToSample(node, centerPoint(mid - 1, r, x, y), sample, sampleCache);
|
||||
var distMid = sumDistToSample(node, centerPoint(mid, r, x, y), sample, sampleCache);
|
||||
|
||||
if (distMid > distMidLeft) {
|
||||
lb = mid + 1;
|
||||
} else if (distMid > distMidRight) {
|
||||
hb = mid - 1;
|
||||
} else {
|
||||
return mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
@@ -0,0 +1,579 @@
|
||||
// Get the width and heigh of the SVG element.
|
||||
var width = +document.getElementById('svg').clientWidth,
|
||||
height = +document.getElementById('svg').clientHeight;
|
||||
|
||||
var svg = d3.select("svg")
|
||||
.call(d3.zoom().scaleExtent([0.0001, 1000000]).on("zoom", function () {
|
||||
svg.attr("transform", d3.event.transform);
|
||||
}))
|
||||
.append("g");
|
||||
|
||||
|
||||
var div = d3.select("body").append("div")
|
||||
.attr("class", "tooltip")
|
||||
.style("opacity", 0);
|
||||
|
||||
var brush = d3.brush()
|
||||
.extent([[-9999999, -9999999], [9999999, 9999999]])
|
||||
.on("end", brushEnded);
|
||||
|
||||
svg.append("g")
|
||||
.attr("class", "brush")
|
||||
.call(brush);
|
||||
|
||||
var intercom = Intercom.getInstance();
|
||||
|
||||
intercom.on("select", unSelectNodes);
|
||||
|
||||
var imgs = svg.selectAll("image");
|
||||
|
||||
var links = [],
|
||||
nodes,
|
||||
node,
|
||||
props,
|
||||
norm,
|
||||
p1 = 0,
|
||||
p2 = 0,
|
||||
size,
|
||||
distanceFunction,
|
||||
simulation,
|
||||
velocities = [],
|
||||
rendering = true, // Rendering during the execution.
|
||||
forceName = "forces",
|
||||
springForce = false,
|
||||
tooltipWidth = 0,
|
||||
fileName = "",
|
||||
selectedData,
|
||||
clickedIndex = -1;
|
||||
|
||||
// Default parameters
|
||||
var MULTIPLIER = 50,
|
||||
PERPLEXITY = 30,
|
||||
LEARNING_RATE = 10,
|
||||
NEIGHBOUR_SIZE = 6,
|
||||
SAMPLE_SIZE = 3,
|
||||
PIVOTS = false,
|
||||
NUM_PIVOTS = 3,
|
||||
ITERATIONS = 300,
|
||||
FULL_ITERATIONS = 20,
|
||||
NODE_SIZE = 10,
|
||||
COLOR_ATTRIBUTE = "";
|
||||
|
||||
// Create a color scheme for a range of numbers.
|
||||
var color = d3.scaleOrdinal(d3.schemeCategory10);
|
||||
|
||||
/**
|
||||
* Parse the data from the provided csv file using Papa Parse library
|
||||
* @param {file} evt - csv file.
|
||||
*/
|
||||
function parseFile(evt) {
|
||||
// Clear the previous nodes
|
||||
d3.selectAll(".nodes").remove();
|
||||
springForce = false;
|
||||
|
||||
fileName = evt.target.files[0].name;
|
||||
|
||||
Papa.parse(evt.target.files[0], {
|
||||
header: true,
|
||||
dynamicTyping: true,
|
||||
skipEmptyLines: true,
|
||||
complete: function (results) {
|
||||
processData(results.data, results.error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the data and pass it into D3 force simulation.
|
||||
* @param {array} data
|
||||
* @param {object} error
|
||||
*/
|
||||
function processData(data, error) {
|
||||
if (error) throw error.message;
|
||||
|
||||
nodes = data;
|
||||
|
||||
// Number of iterations before stopping.
|
||||
size = nodes.length;
|
||||
|
||||
console.log("Number of iterations: ", ITERATIONS);
|
||||
|
||||
// Start by placing the nodes at the center (its starting positions).
|
||||
simulation = d3.forceSimulation();
|
||||
|
||||
console.log("n =", nodes.length);
|
||||
|
||||
// Calculate normalization arguments and get the list of
|
||||
// properties of the nodes.
|
||||
norm = calculateNormalization(nodes);
|
||||
props = Object.keys(nodes[0]);
|
||||
COLOR_ATTRIBUTE = props[0];
|
||||
|
||||
var opts = document.getElementById('color_attr').options;
|
||||
|
||||
props.forEach(function (d) {
|
||||
opts.add(new Option(d, d, (d === COLOR_ATTRIBUTE) ? true : false));
|
||||
});
|
||||
|
||||
// Add the nodes to DOM.
|
||||
node = svg.append("g")
|
||||
.attr("class", "nodes")
|
||||
.selectAll("circle")
|
||||
.data(nodes)
|
||||
.enter().append("circle")
|
||||
.attr("r", NODE_SIZE)
|
||||
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
|
||||
// Color code the data points by a property (for Poker Hands,
|
||||
// it is a CLASS property).
|
||||
.attr("fill", function (d) {
|
||||
return color(d[COLOR_ATTRIBUTE]);
|
||||
})
|
||||
.on("mouseover", function (d) {
|
||||
highlightOnHover(d[COLOR_ATTRIBUTE]);
|
||||
})
|
||||
.on("mouseout", function (d) {
|
||||
div.transition()
|
||||
.duration(500)
|
||||
.style("opacity", 0);
|
||||
node.attr("opacity", 1);
|
||||
})
|
||||
.on("click", function (d) {
|
||||
if (clickedIndex !== d.index) {
|
||||
highlightNeighbours(d.index, springForce ? Array.from(simulation.force(forceName).nodeNeighbours(d.index).keys()) : []);
|
||||
clickedIndex = d.index;
|
||||
} else {
|
||||
svg.selectAll("image").remove();
|
||||
node.attr("r", NODE_SIZE).attr("stroke-width", 0);
|
||||
clickedIndex = -1;
|
||||
}
|
||||
});
|
||||
|
||||
// Pass the nodes to the D3 force simulation.
|
||||
simulation
|
||||
.nodes(nodes)
|
||||
.on("tick", ticked)
|
||||
.on("end", ended);
|
||||
|
||||
function ticked() {
|
||||
// If rendering is selected, then draw at every iteration.
|
||||
if (rendering === true) {
|
||||
node
|
||||
.attr("cx", function (d) {
|
||||
return d.x;
|
||||
})
|
||||
.attr("cy", function (d) {
|
||||
return d.y;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function ended() {
|
||||
if (rendering !== true) {
|
||||
node
|
||||
.attr("cx", function (d) {
|
||||
return d.x;
|
||||
})
|
||||
.attr("cy", function (d) {
|
||||
return d.y;
|
||||
});
|
||||
}
|
||||
|
||||
if (p1 !== 0) {
|
||||
// Performance time measurement
|
||||
p2 = performance.now();
|
||||
console.log("Execution time: " + (p2 - p1));
|
||||
// Do not calculate stress for data sets bigger than 100 000.
|
||||
// if (nodes.length <= 100000) {
|
||||
// console.log("Stress: ", simulation.force(forceName).stress());
|
||||
// }
|
||||
p1 = 0;
|
||||
p2 = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
function brushEnded() {
|
||||
var s = d3.event.selection,
|
||||
results = [];
|
||||
|
||||
if (s) {
|
||||
|
||||
var x0 = s[0][0] - width / 2,
|
||||
y0 = s[0][1] - height / 2,
|
||||
x1 = s[1][0] - width / 2,
|
||||
y1 = s[1][1] - height / 2;
|
||||
|
||||
if (nodes) {
|
||||
var sel = node.filter(function (d) {
|
||||
if (d.x > x0 && d.x < x1 && d.y > y0 && d.y < y1) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}).data();
|
||||
|
||||
results = sel.map(function (a) { return a.index; });
|
||||
}
|
||||
|
||||
intercom.emit("select", { name: fileName, indices: results });
|
||||
|
||||
d3.select(".brush").call(brush.move, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the Chalmers' 1996 algorithm and start simulation.
|
||||
*/
|
||||
function startNeighbourSamplingSimulation() {
|
||||
springForce = true;
|
||||
simulation.stop();
|
||||
p1 = performance.now();
|
||||
|
||||
simulation
|
||||
.alphaDecay(1 - Math.pow(0.001, 1 / ITERATIONS))
|
||||
.force(forceName, d3.forceNeighbourSamplingDistance()
|
||||
// Set the parameters for the algorithm (optional).
|
||||
.neighbourSize(NEIGHBOUR_SIZE)
|
||||
.sampleSize(SAMPLE_SIZE)
|
||||
.multiplier(MULTIPLIER)
|
||||
// The distance function that will be used to calculate distances
|
||||
// between nodes.
|
||||
.distance(function (s, t) {
|
||||
return distanceFunction(s, t, props, norm);
|
||||
}));
|
||||
// Restart the simulation.
|
||||
console.log(simulation.force(forceName).neighbourSize(), simulation.force(forceName).sampleSize());
|
||||
simulation.alpha(1).restart();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the hybrid layout algorithm and start simulation.
|
||||
*/
|
||||
function startHybridSimulation() {
|
||||
springForce = false;
|
||||
d3.selectAll(".nodes").remove();
|
||||
simulation.stop();
|
||||
p1 = performance.now();
|
||||
|
||||
hybridSimulation = d3.hybridSimulation(nodes);
|
||||
|
||||
hybridSimulation
|
||||
.multiplier(MULTIPLIER)
|
||||
.sampleIterations(ITERATIONS)
|
||||
.pivots(PIVOTS)
|
||||
.numPivots(NUM_PIVOTS)
|
||||
.fullIterations(FULL_ITERATIONS)
|
||||
.neighbourSize(NEIGHBOUR_SIZE)
|
||||
.sampleSize(SAMPLE_SIZE);
|
||||
|
||||
var sample = hybridSimulation.sample();
|
||||
var remainder = hybridSimulation.remainder();
|
||||
|
||||
// Add the nodes to DOM.
|
||||
node = svg.append("g")
|
||||
.attr("class", "nodes")
|
||||
.selectAll("circle")
|
||||
.data(sample)
|
||||
.enter().append("circle")
|
||||
.attr("r", NODE_SIZE)
|
||||
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
|
||||
// Color code the data points by a property (for Poker Hands,
|
||||
// it is a CLASS property).
|
||||
.attr("fill", function (d) {
|
||||
return color(d[COLOR_ATTRIBUTE])
|
||||
})
|
||||
.on("mouseover", function (d) {
|
||||
div.transition()
|
||||
.duration(200)
|
||||
.style("opacity", .9);
|
||||
div.html(formatTooltip(d))
|
||||
.style("left", (d3.event.pageX) + "px")
|
||||
.style("top", (d3.event.pageY - (15 * props.length)) + "px")
|
||||
.style("width", (6 * tooltipWidth) + "px")
|
||||
.style("height", (14 * props.length) + "px");
|
||||
highlightOnHover(d[COLOR_ATTRIBUTE]);
|
||||
})
|
||||
.on("mouseout", function (d) {
|
||||
div.transition()
|
||||
.duration(500)
|
||||
.style("opacity", 0);
|
||||
node.attr("opacity", 1);
|
||||
});
|
||||
|
||||
if (selectedData) {
|
||||
unSelectNodes(selectedData);
|
||||
}
|
||||
|
||||
hybridSimulation
|
||||
.distance(distanceFunction);
|
||||
|
||||
hybridSimulation
|
||||
.on("sampleTick", tickedHybrid)
|
||||
.on("fullTick", tickedHybrid)
|
||||
.on("startFull", started)
|
||||
.on("end", endedHybrid);
|
||||
|
||||
|
||||
function tickedHybrid() {
|
||||
if (rendering === true) {
|
||||
node
|
||||
.attr("cx", function (d) {
|
||||
return d.x;
|
||||
})
|
||||
.attr("cy", function (d) {
|
||||
return d.y;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function started() {
|
||||
d3.selectAll(".nodes").remove();
|
||||
// Add the nodes to DOM.
|
||||
node = svg.append("g")
|
||||
.attr("class", "nodes")
|
||||
.selectAll("circle")
|
||||
.data(nodes)
|
||||
.enter().append("circle")
|
||||
.attr("r", NODE_SIZE)
|
||||
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
|
||||
// Color code the data points by a property (for Poker Hands,
|
||||
// it is a CLASS property).
|
||||
.attr("fill", function (d) {
|
||||
return color(d[COLOR_ATTRIBUTE])
|
||||
})
|
||||
.on("mouseover", function (d) {
|
||||
div.transition()
|
||||
.duration(200)
|
||||
.style("opacity", .9);
|
||||
div.html(formatTooltip(d))
|
||||
.style("left", (d3.event.pageX) + "px")
|
||||
.style("top", (d3.event.pageY - (15 * props.length)) + "px")
|
||||
.style("width", (6 * tooltipWidth) + "px")
|
||||
.style("height", (14 * props.length) + "px");
|
||||
highlightOnHover(d[COLOR_ATTRIBUTE]);
|
||||
})
|
||||
.on("mouseout", function (d) {
|
||||
div.transition()
|
||||
.duration(500)
|
||||
.style("opacity", 0);
|
||||
node.attr("opacity", 1);
|
||||
});
|
||||
|
||||
if (selectedData) {
|
||||
unSelectNodes(selectedData);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
function endedHybrid() {
|
||||
if (rendering !== true) {
|
||||
node
|
||||
.attr("cx", function (d) {
|
||||
return d.x;
|
||||
})
|
||||
.attr("cy", function (d) {
|
||||
return d.y;
|
||||
});
|
||||
}
|
||||
|
||||
// Performance time measurement
|
||||
p2 = performance.now();
|
||||
console.log("Execution time: " + (p2 - p1));
|
||||
// Do not calculate stress for data sets bigger than 100 000.
|
||||
// if (nodes.length <= 100000) {
|
||||
// console.log("Stress: ", hybridSimulation.stress());
|
||||
// }
|
||||
p1 = 0;
|
||||
p2 = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Initialize the t-SNE algorithm and start simulation.
|
||||
*/
|
||||
function starttSNE() {
|
||||
springForce = false;
|
||||
simulation.stop();
|
||||
p1 = performance.now();
|
||||
|
||||
simulation
|
||||
.alphaDecay(1 - Math.pow(0.001, 1 / ITERATIONS))
|
||||
.force(forceName, d3.tSNE()
|
||||
// Set the parameter for the algorithm (optional).
|
||||
.perplexity(PERPLEXITY)
|
||||
.learningRate(LEARNING_RATE)
|
||||
// The distance function that will be used to calculate distances
|
||||
// between nodes.
|
||||
.distance(function (s, t) {
|
||||
return distanceFunction(s, t, props, norm) * MULTIPLIER;
|
||||
}));
|
||||
// Restart the simulation.
|
||||
console.log(simulation.force(forceName).perplexity(), simulation.force(forceName).learningRate());
|
||||
simulation.alpha(1).restart();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the Barnes-Hut algorithm and start simulation.
|
||||
*/
|
||||
function startBarnesHutSimulation() {
|
||||
springForce = false;
|
||||
simulation.stop();
|
||||
p1 = performance.now();
|
||||
|
||||
simulation
|
||||
.alphaDecay(1 - Math.pow(0.001, 1 / ITERATIONS))
|
||||
.force(forceName, d3.forceBarnesHut()
|
||||
// The distance function that will be used to calculate distances
|
||||
// between nodes.
|
||||
.distance(function (s, t) {
|
||||
return distanceFunction(s, t, props, norm) * MULTIPLIER;
|
||||
}));
|
||||
// Restart the simulation.
|
||||
simulation.alpha(1).restart();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the link force algorithm and start simulation.
|
||||
*/
|
||||
function startLinkSimulation() {
|
||||
springForce = false;
|
||||
simulation.stop();
|
||||
p1 = performance.now();
|
||||
|
||||
// Initialize link array.
|
||||
nodes = simulation.nodes();
|
||||
for (i = 0; i < nodes.length; i++) {
|
||||
for (j = 0; j < nodes.length; j++) {
|
||||
if (i !== j) {
|
||||
links.push({
|
||||
source: nodes[i],
|
||||
target: nodes[j],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add the links to the simulation.
|
||||
simulation.force(forceName, d3.forceLink().links(links));
|
||||
|
||||
simulation
|
||||
.alphaDecay(1 - Math.pow(0.001, 1 / ITERATIONS))
|
||||
.force(forceName)
|
||||
// The distance function that will be used to calculate distances
|
||||
// between nodes.
|
||||
.distance(function (n) {
|
||||
return distanceFunction(n.source, n.target, props, norm) * MULTIPLIER;
|
||||
})
|
||||
// Set the parameter for the algorithm (optional).
|
||||
.strength(1);
|
||||
// Restart the simulation.
|
||||
simulation.alpha(1).restart();
|
||||
}
|
||||
|
||||
/**
|
||||
* Halt the execution.
|
||||
*/
|
||||
function stopSimulation() {
|
||||
simulation.stop();
|
||||
if (typeof hybridSimulation !== 'undefined') {
|
||||
hybridSimulation.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the average values of the array.
|
||||
* @param {array} array
|
||||
* @return {number} the mean of the array.
|
||||
*/
|
||||
function getAverage(array) {
|
||||
var total = 0;
|
||||
for (var i = 0; i < array.length; i++) {
|
||||
total += array[i];
|
||||
}
|
||||
return total / array.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deselect the nodes to match the selection from other window.
|
||||
* @param {*} data
|
||||
*/
|
||||
function unSelectNodes(data) {
|
||||
|
||||
selectedData = data;
|
||||
|
||||
if (fileName === data.name && nodes) {
|
||||
node
|
||||
.classed("notSelected", function (d) {
|
||||
if (data.indices.indexOf(d.index) < 0) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Highlight the neighbours for neighbour and sampling algorithm and show the corresponding MNIST images for each node.
|
||||
* @param {*} indices
|
||||
*/
|
||||
function highlightNeighbours(index, indices) {
|
||||
var selectedNodes = [nodes[index]];
|
||||
indices.forEach(function (i) {
|
||||
selectedNodes.push(nodes[i]);
|
||||
});
|
||||
|
||||
var ratio = NODE_SIZE / 10;
|
||||
|
||||
svg.selectAll("image").remove();
|
||||
imgs.data(selectedNodes).enter()
|
||||
.append("svg:image")
|
||||
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
|
||||
.attr("xlink:href", function (d) {
|
||||
return "data/mnist/images/" + d.index + ".png";
|
||||
})
|
||||
.attr("x", function (d) {
|
||||
return d.x + (ratio * 20);
|
||||
})
|
||||
.attr("y", function (d) {
|
||||
return d.y - (ratio * 20);
|
||||
})
|
||||
.attr("width", ratio * 28)
|
||||
.attr("height", ratio * 28);
|
||||
|
||||
|
||||
node
|
||||
.attr("r", function (d) {
|
||||
if (indices.indexOf(d.index) >= 0) {
|
||||
return NODE_SIZE * 2;
|
||||
}
|
||||
return NODE_SIZE;
|
||||
})
|
||||
.attr("stroke-width", function (d) {
|
||||
if (indices.indexOf(d.index) >= 0) {
|
||||
return NODE_SIZE * 0.2 + "px";
|
||||
}
|
||||
return "0px";
|
||||
})
|
||||
.attr("stroke", "white");
|
||||
}
|
||||
|
||||
/**
|
||||
* Highlight all the nodes with the same class on hover
|
||||
* @param {*} highlighValue
|
||||
*/
|
||||
function highlightOnHover(highlighValue) {
|
||||
node.attr("opacity", function (d) {
|
||||
return (highlighValue === d[COLOR_ATTRIBUTE]) ? 1 : 0.3;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Color the nodes according to given attribute.
|
||||
*/
|
||||
function colorToAttribute() {
|
||||
node.attr("fill", function (d) {
|
||||
return color(d[COLOR_ATTRIBUTE])
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
// Get the width and heigh of the SVG element.
|
||||
var width = +document.getElementById('svg').clientWidth,
|
||||
height = +document.getElementById('svg').clientHeight;
|
||||
|
||||
var svg = d3.select("svg")
|
||||
.call(d3.zoom().scaleExtent([0.0001, 1000000]).on("zoom", function () {
|
||||
svg.attr("transform", d3.event.transform);
|
||||
}))
|
||||
.append("g");
|
||||
|
||||
|
||||
var div = d3.select("body").append("div")
|
||||
.attr("class", "tooltip")
|
||||
.style("opacity", 0);
|
||||
|
||||
var brush = d3.brush()
|
||||
.extent([[-9999999, -9999999], [9999999, 9999999]])
|
||||
.on("end", brushEnded);
|
||||
|
||||
svg.append("g")
|
||||
.attr("class", "brush")
|
||||
.call(brush);
|
||||
|
||||
var intercom = Intercom.getInstance();
|
||||
|
||||
intercom.on("select", unSelectNodes);
|
||||
|
||||
var links = [],
|
||||
nodes,
|
||||
node,
|
||||
props,
|
||||
norm,
|
||||
p1 = 0,
|
||||
p2 = 0,
|
||||
size,
|
||||
distanceFunction,
|
||||
simulation,
|
||||
velocities = [],
|
||||
rendering = true, // Rendering during the execution.
|
||||
forceName = "forces",
|
||||
springForce = false,
|
||||
tooltipWidth = 0,
|
||||
fileName = "",
|
||||
selectedData,
|
||||
clickedIndex = -1,
|
||||
paused = false;
|
||||
|
||||
// Default parameters
|
||||
var MULTIPLIER = 50,
|
||||
PERPLEXITY = 30,
|
||||
LEARNING_RATE = 10,
|
||||
NEIGHBOUR_SIZE = 6,
|
||||
SAMPLE_SIZE = 3,
|
||||
PIVOTS = false,
|
||||
NUM_PIVOTS = 3,
|
||||
ITERATIONS = 300,
|
||||
FULL_ITERATIONS = 20,
|
||||
NODE_SIZE = 10,
|
||||
COLOR_ATTRIBUTE = "",
|
||||
SELECTED_DISTANCE = 10;
|
||||
|
||||
// Create a color scheme for a range of numbers.
|
||||
var color = d3.scaleOrdinal(d3.schemeCategory10);
|
||||
|
||||
/**
|
||||
* Parse the data from the provided csv file using Papa Parse library
|
||||
* @param {file} evt - csv file.
|
||||
*/
|
||||
function parseFile(evt) {
|
||||
// Clear the previous nodes
|
||||
d3.selectAll(".nodes").remove();
|
||||
springForce = false;
|
||||
|
||||
fileName = evt.target.files[0].name;
|
||||
|
||||
Papa.parse(evt.target.files[0], {
|
||||
header: true,
|
||||
dynamicTyping: true,
|
||||
skipEmptyLines: true,
|
||||
complete: function (results) {
|
||||
processData(results.data, results.error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the data and pass it into D3 force simulation.
|
||||
* @param {array} data
|
||||
* @param {object} error
|
||||
*/
|
||||
function processData(data, error) {
|
||||
if (error) throw error.message;
|
||||
|
||||
nodes = data;
|
||||
|
||||
// Number of iterations before stopping.
|
||||
size = nodes.length;
|
||||
|
||||
console.log("Number of iterations: ", ITERATIONS);
|
||||
|
||||
// Start by placing the nodes at the center (its starting positions).
|
||||
simulation = d3.forceSimulation();
|
||||
|
||||
//Put the nodes in random starting positions
|
||||
nodes.forEach(function (d) {
|
||||
d.x = (Math.random()-0.5) * 100000;
|
||||
d.y = (Math.random()-0.5) * 100000;
|
||||
});
|
||||
|
||||
console.log("n =", nodes.length);
|
||||
// Calculate normalization arguments and get the list of
|
||||
// properties of the nodes.
|
||||
norm = calculateNormalization(nodes);
|
||||
props = Object.keys(nodes[0]);
|
||||
COLOR_ATTRIBUTE = props[0];
|
||||
|
||||
var opts = document.getElementById('color_attr').options;
|
||||
|
||||
props.forEach(function (d) {
|
||||
opts.add(new Option(d, d, (d === COLOR_ATTRIBUTE) ? true : false));
|
||||
});
|
||||
|
||||
// Add the nodes to DOM.
|
||||
node = svg.append("g")
|
||||
.attr("class", "nodes")
|
||||
.selectAll("circle")
|
||||
.data(nodes)
|
||||
.enter().append("circle")
|
||||
.attr("r", NODE_SIZE)
|
||||
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
|
||||
// Color code the data points by a property (for Poker Hands,
|
||||
// it is a CLASS property).
|
||||
.attr("fill", function (d) {
|
||||
return color(d[COLOR_ATTRIBUTE]);
|
||||
})
|
||||
.on("mouseover", function (d) {
|
||||
div.transition()
|
||||
.duration(200)
|
||||
.style("opacity", .9);
|
||||
div.html(formatTooltip(d))
|
||||
.style("left", (d3.event.pageX) + "px")
|
||||
.style("top", (d3.event.pageY - (15 * props.length)) + "px")
|
||||
.style("width", (6 * tooltipWidth) + "px")
|
||||
.style("height", (14 * props.length) + "px");
|
||||
highlightOnHover(d[COLOR_ATTRIBUTE]);
|
||||
})
|
||||
.on("mouseout", function (d) {
|
||||
div.transition()
|
||||
.duration(500)
|
||||
.style("opacity", 0);
|
||||
node.attr("opacity", 1);
|
||||
})
|
||||
.on("click", function (d) {
|
||||
if (clickedIndex !== d.index) {
|
||||
if (springForce) {
|
||||
highlightNeighbours(Array.from(simulation.force(forceName).nodeNeighbours(d.index).keys()));
|
||||
clickedIndex = d.index;
|
||||
}
|
||||
} else {
|
||||
node.attr("r", NODE_SIZE).attr("stroke-width", 0);
|
||||
clickedIndex = -1;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Pass the nodes to the D3 force simulation.
|
||||
simulation
|
||||
.nodes(nodes)
|
||||
.on("tick", ticked)
|
||||
.on("end", ended);
|
||||
|
||||
|
||||
function ticked() {
|
||||
// If rendering is selected, then draw at every iteration.
|
||||
if (rendering === true) {
|
||||
node
|
||||
.attr("cx", function (d) {
|
||||
return d.x;
|
||||
})
|
||||
.attr("cy", function (d) {
|
||||
return d.y;
|
||||
});
|
||||
}
|
||||
// Emit the distribution data to allow the drawing of the bar graph
|
||||
if (springForce) {
|
||||
intercom.emit("passedData", simulation.force(forceName).distributionData());
|
||||
}
|
||||
}
|
||||
|
||||
function ended() {
|
||||
if (rendering !== true) {
|
||||
node
|
||||
.attr("cx", function (d) {
|
||||
return d.x;
|
||||
})
|
||||
.attr("cy", function (d) {
|
||||
return d.y;
|
||||
});
|
||||
}
|
||||
|
||||
if (p1 !== 0) {
|
||||
// Performance time measurement
|
||||
p2 = performance.now();
|
||||
console.log("Execution time: " + (p2 - p1));
|
||||
// Do not calculate stress for data sets bigger than 100 000.
|
||||
// if (nodes.length <= 100000) {
|
||||
// console.log("Stress: ", simulation.force(forceName).stress());
|
||||
// }
|
||||
// console.log(simulation.force(forceName).nodeNeighbours());
|
||||
p1 = 0;
|
||||
p2 = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
function brushEnded() {
|
||||
var s = d3.event.selection,
|
||||
results = [];
|
||||
|
||||
if (s) {
|
||||
|
||||
var x0 = s[0][0] - width / 2,
|
||||
y0 = s[0][1] - height / 2,
|
||||
x1 = s[1][0] - width / 2,
|
||||
y1 = s[1][1] - height / 2;
|
||||
|
||||
if (nodes) {
|
||||
var sel = node.filter(function (d) {
|
||||
if (d.x > x0 && d.x < x1 && d.y > y0 && d.y < y1) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}).data();
|
||||
|
||||
results = sel.map(function (a) { return a.index; });
|
||||
}
|
||||
|
||||
intercom.emit("select", { name: fileName, indices: results });
|
||||
|
||||
d3.select(".brush").call(brush.move, null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Format the tooltip for the data
|
||||
* @param {*} node
|
||||
*/
|
||||
function formatTooltip(node) {
|
||||
var textString = "",
|
||||
temp = "";
|
||||
|
||||
tooltipWidth = 0;
|
||||
props.forEach(function (element) {
|
||||
temp = element + ": " + node[element] + "<br/>";
|
||||
textString += temp;
|
||||
if (temp.length > tooltipWidth) {
|
||||
tooltipWidth = temp.length;
|
||||
}
|
||||
});
|
||||
return textString;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Initialize the Chalmers' 1996 algorithm and start simulation.
|
||||
*/
|
||||
function startNeighbourSamplingSimulation() {
|
||||
springForce = true;
|
||||
simulation.stop();
|
||||
p1 = performance.now();
|
||||
|
||||
simulation
|
||||
.alphaDecay(1 - Math.pow(0.001, 1 / ITERATIONS))
|
||||
.force(forceName, d3.forceNeighbourSamplingDistance()
|
||||
// Set the parameters for the algorithm (optional).
|
||||
.neighbourSize(NEIGHBOUR_SIZE)
|
||||
.sampleSize(SAMPLE_SIZE)
|
||||
// .freeness(0.5)
|
||||
.multiplier(MULTIPLIER)
|
||||
.distanceRange(SELECTED_DISTANCE)
|
||||
// The distance function that will be used to calculate distances
|
||||
// between nodes.
|
||||
.distance(function (s, t) {
|
||||
return distanceFunction(s, t, props, norm);
|
||||
}));
|
||||
// Restart the simulation.
|
||||
console.log(simulation.force(forceName).neighbourSize(), simulation.force(forceName).sampleSize());
|
||||
simulation.alpha(1).restart();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Initialize the hybrid layout algorithm and start simulation.
|
||||
*/
|
||||
function startHybridSimulation() {
|
||||
springForce = false;
|
||||
d3.selectAll(".nodes").remove();
|
||||
simulation.stop();
|
||||
p1 = performance.now();
|
||||
|
||||
hybridSimulation = d3.hybridSimulation(nodes);
|
||||
|
||||
hybridSimulation
|
||||
.multiplier(MULTIPLIER)
|
||||
.sampleIterations(ITERATIONS)
|
||||
.pivots(PIVOTS)
|
||||
.numPivots(NUM_PIVOTS)
|
||||
.fullIterations(FULL_ITERATIONS)
|
||||
.neighbourSize(NEIGHBOUR_SIZE)
|
||||
.sampleSize(SAMPLE_SIZE);
|
||||
|
||||
var sample = hybridSimulation.sample();
|
||||
var remainder = hybridSimulation.remainder();
|
||||
|
||||
// Add the nodes to DOM.
|
||||
node = svg.append("g")
|
||||
.attr("class", "nodes")
|
||||
.selectAll("circle")
|
||||
.data(sample)
|
||||
.enter().append("circle")
|
||||
.attr("r", NODE_SIZE)
|
||||
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
|
||||
// Color code the data points by a property (for Poker Hands,
|
||||
// it is a CLASS property).
|
||||
.attr("fill", function (d) {
|
||||
return color(d[COLOR_ATTRIBUTE])
|
||||
})
|
||||
.on("mouseover", function (d) {
|
||||
div.transition()
|
||||
.duration(200)
|
||||
.style("opacity", .9);
|
||||
div.html(formatTooltip(d))
|
||||
.style("left", (d3.event.pageX) + "px")
|
||||
.style("top", (d3.event.pageY - (15 * props.length)) + "px")
|
||||
.style("width", (6 * tooltipWidth) + "px")
|
||||
.style("height", (14 * props.length) + "px");
|
||||
highlightOnHover(d[COLOR_ATTRIBUTE]);
|
||||
})
|
||||
.on("mouseout", function (d) {
|
||||
div.transition()
|
||||
.duration(500)
|
||||
.style("opacity", 0);
|
||||
node.attr("opacity", 1);
|
||||
});
|
||||
|
||||
if (selectedData) {
|
||||
unSelectNodes(selectedData);
|
||||
}
|
||||
|
||||
hybridSimulation
|
||||
.distance(distanceFunction);
|
||||
|
||||
hybridSimulation
|
||||
.on("sampleTick", tickedHybrid)
|
||||
.on("fullTick", tickedHybrid)
|
||||
.on("startFull", started)
|
||||
.on("end", endedHybrid);
|
||||
|
||||
|
||||
function tickedHybrid() {
|
||||
if (rendering === true) {
|
||||
node
|
||||
.attr("cx", function (d) {
|
||||
return d.x;
|
||||
})
|
||||
.attr("cy", function (d) {
|
||||
return d.y;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function started() {
|
||||
d3.selectAll(".nodes").remove();
|
||||
// Add the nodes to DOM.
|
||||
node = svg.append("g")
|
||||
.attr("class", "nodes")
|
||||
.selectAll("circle")
|
||||
.data(nodes)
|
||||
.enter().append("circle")
|
||||
.attr("r", NODE_SIZE)
|
||||
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
|
||||
// Color code the data points by a property (for Poker Hands,
|
||||
// it is a CLASS property).
|
||||
.attr("fill", function (d) {
|
||||
return color(d[COLOR_ATTRIBUTE])
|
||||
})
|
||||
.on("mouseover", function (d) {
|
||||
div.transition()
|
||||
.duration(200)
|
||||
.style("opacity", .9);
|
||||
div.html(formatTooltip(d))
|
||||
.style("left", (d3.event.pageX) + "px")
|
||||
.style("top", (d3.event.pageY - (15 * props.length)) + "px")
|
||||
.style("width", (6 * tooltipWidth) + "px")
|
||||
.style("height", (14 * props.length) + "px");
|
||||
highlightOnHover(d[COLOR_ATTRIBUTE]);
|
||||
})
|
||||
.on("mouseout", function (d) {
|
||||
div.transition()
|
||||
.duration(500)
|
||||
.style("opacity", 0);
|
||||
node.attr("opacity", 1);
|
||||
});
|
||||
|
||||
if (selectedData) {
|
||||
unSelectNodes(selectedData);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
function endedHybrid() {
|
||||
if (rendering !== true) {
|
||||
node
|
||||
.attr("cx", function (d) {
|
||||
return d.x;
|
||||
})
|
||||
.attr("cy", function (d) {
|
||||
return d.y;
|
||||
});
|
||||
}
|
||||
|
||||
// Performance time measurement
|
||||
p2 = performance.now();
|
||||
console.log("Execution time: " + (p2 - p1));
|
||||
// Do not calculate stress for data sets bigger than 100 000.
|
||||
// if (nodes.length <= 100000) {
|
||||
// console.log("Stress: ", hybridSimulation.stress());
|
||||
// }
|
||||
p1 = 0;
|
||||
p2 = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Initialize the t-SNE algorithm and start simulation.
|
||||
*/
|
||||
function starttSNE() {
|
||||
springForce = false;
|
||||
simulation.stop();
|
||||
p1 = performance.now();
|
||||
|
||||
simulation
|
||||
.alphaDecay(1 - Math.pow(0.001, 1 / ITERATIONS))
|
||||
.force(forceName, d3.tSNE()
|
||||
// Set the parameter for the algorithm (optional).
|
||||
.perplexity(PERPLEXITY)
|
||||
.learningRate(LEARNING_RATE)
|
||||
// The distance function that will be used to calculate distances
|
||||
// between nodes.
|
||||
.distance(function (s, t) {
|
||||
return distanceFunction(s, t, props, norm) * MULTIPLIER;
|
||||
}));
|
||||
// Restart the simulation.
|
||||
console.log(simulation.force(forceName).perplexity(), simulation.force(forceName).learningRate());
|
||||
simulation.alpha(1).restart();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the Barnes-Hut algorithm and start simulation.
|
||||
*/
|
||||
function startBarnesHutSimulation() {
|
||||
springForce = false;
|
||||
simulation.stop();
|
||||
p1 = performance.now();
|
||||
|
||||
simulation
|
||||
.alphaDecay(1 - Math.pow(0.001, 1 / ITERATIONS))
|
||||
.force(forceName, d3.forceBarnesHut()
|
||||
// The distance function that will be used to calculate distances
|
||||
// between nodes.
|
||||
.distance(function (s, t) {
|
||||
return distanceFunction(s, t, props, norm) * MULTIPLIER;
|
||||
}));
|
||||
// Restart the simulation.
|
||||
simulation.alpha(1).restart();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the link force algorithm and start simulation.
|
||||
*/
|
||||
function startLinkSimulation() {
|
||||
springForce = false;
|
||||
simulation.stop();
|
||||
p1 = performance.now();
|
||||
|
||||
// Initialize link array.
|
||||
nodes = simulation.nodes();
|
||||
for (i = 0; i < nodes.length; i++) {
|
||||
for (j = 0; j < nodes.length; j++) {
|
||||
if (i !== j) {
|
||||
links.push({
|
||||
source: nodes[i],
|
||||
target: nodes[j],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add the links to the simulation.
|
||||
simulation.force(forceName, d3.forceLink().links(links));
|
||||
|
||||
simulation
|
||||
.alphaDecay(1 - Math.pow(0.001, 1 / ITERATIONS))
|
||||
.force(forceName)
|
||||
// The distance function that will be used to calculate distances
|
||||
// between nodes.
|
||||
.distance(function (n) {
|
||||
return distanceFunction(n.source, n.target, props, norm) * MULTIPLIER;
|
||||
})
|
||||
// Set the parameter for the algorithm (optional).
|
||||
.strength(1);
|
||||
// Restart the simulation.
|
||||
simulation.alpha(1).restart();
|
||||
}
|
||||
|
||||
/**
|
||||
* Halt the execution.
|
||||
*/
|
||||
function stopSimulation() {
|
||||
simulation.stop();
|
||||
if (typeof hybridSimulation !== 'undefined') {
|
||||
hybridSimulation.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the average values of the array.
|
||||
* @param {array} array
|
||||
* @return {number} the mean of the array.
|
||||
*/
|
||||
function getAverage(array) {
|
||||
var total = 0;
|
||||
for (var i = 0; i < array.length; i++) {
|
||||
total += array[i];
|
||||
}
|
||||
return total / array.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deselect the nodes to match the selection from other window.
|
||||
* @param {*} data
|
||||
*/
|
||||
function unSelectNodes(data) {
|
||||
|
||||
selectedData = data;
|
||||
|
||||
if (fileName === data.name && nodes) {
|
||||
node
|
||||
.classed("notSelected", function (d) {
|
||||
if (data.indices.indexOf(d.index) < 0) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Highlight the neighbours for neighbour and sampling algorithm
|
||||
* @param {*} indices
|
||||
*/
|
||||
function highlightNeighbours(indices) {
|
||||
node
|
||||
.attr("r", function (d) {
|
||||
if (indices.indexOf(d.index) >= 0) {
|
||||
return NODE_SIZE * 2;
|
||||
}
|
||||
return NODE_SIZE;
|
||||
})
|
||||
.attr("stroke-width", function (d) {
|
||||
if (indices.indexOf(d.index) >= 0) {
|
||||
return NODE_SIZE * 0.2 + "px";
|
||||
}
|
||||
return "0px";
|
||||
})
|
||||
.attr("stroke", "white");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Highlight all the nodes with the same class on hover
|
||||
* @param {*} highlighValue
|
||||
*/
|
||||
function highlightOnHover(highlighValue) {
|
||||
node.attr("opacity", function (d) {
|
||||
return (highlighValue === d[COLOR_ATTRIBUTE]) ? 1 : 0.3;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Color the nodes according to given attribute.
|
||||
*/
|
||||
function colorToAttribute() {
|
||||
node.attr("fill", function (d) {
|
||||
return color(d[COLOR_ATTRIBUTE])
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update the distance range.
|
||||
*/
|
||||
function updateDistanceRange() {
|
||||
if (springForce) {
|
||||
simulation.force(forceName).distanceRange(SELECTED_DISTANCE);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Implemented pause/resume functionality
|
||||
*/
|
||||
function pauseUnPause() {
|
||||
if (simulation) {
|
||||
if (paused) {
|
||||
simulation.force(forceName).distanceRange(SELECTED_DISTANCE);
|
||||
simulation.restart();
|
||||
d3.select("#pauseButton").text("Pause");
|
||||
paused = false;
|
||||
} else {
|
||||
simulation.stop();
|
||||
d3.select("#pauseButton").text("Resume");
|
||||
paused = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Average distances for each node.
|
||||
* @param {*} dataNodes
|
||||
* @param {*} properties
|
||||
* @param {*} normalization
|
||||
*/
|
||||
function calculateAverageDistance(dataNodes, properties, normalization) {
|
||||
var sum = 0,
|
||||
n = nodes.length;
|
||||
|
||||
for (var i = 0; i < n; i++) {
|
||||
var sumNode = 0;
|
||||
for (var j = 0; j < n; j++) {
|
||||
if (i !== j) {
|
||||
sumNode += distanceFunction(nodes[i], nodes[j], properties, normalization);
|
||||
// console.log(sumNode);
|
||||
}
|
||||
}
|
||||
sum += sumNode / (n - 1);
|
||||
}
|
||||
|
||||
return sum / n;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
function findPivots(dataSet, sampleSet, remainderSet) {
|
||||
var distance = calculateDistancePoker;
|
||||
// Initialize
|
||||
|
||||
var numBuckets = Math.floor(Math.sqrt(sampleSet.length)),
|
||||
numPivots = Math.floor(Math.sqrt(sampleSet.length)),
|
||||
parents = [],
|
||||
maxDists = [],
|
||||
bucketWidths = [],
|
||||
pivotsBuckets = [];
|
||||
|
||||
var pivots = createRandomSample(dataSet, sampleSet.length, numPivots);
|
||||
|
||||
for (var i = 0; i < numPivots; i++) {
|
||||
pivotsBuckets[i] = [];
|
||||
for (var j = 0; j < numBuckets; j++) {
|
||||
pivotsBuckets[i][j] = [];
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-processing
|
||||
var fullDists = []
|
||||
for (var i = 0; i < sampleSet.length; i++) {
|
||||
fullDists[i] = [];
|
||||
}
|
||||
|
||||
for (var j = 0, maxDist = -1; j < numPivots; j++) {
|
||||
var c1 = pivots[j];
|
||||
for (var i = 0; i < sampleSet.length; i++) {
|
||||
var c2 = sampleSet[i];
|
||||
if (c1 !== c2) {
|
||||
var dist = distance(c1, c2);
|
||||
// console.log(dist, c1, c2);
|
||||
if (dist > maxDist) {
|
||||
maxDist = dist;
|
||||
}
|
||||
fullDists[i][j] = dist;
|
||||
} else {
|
||||
fullDists[i][j] = 0.0001;
|
||||
}
|
||||
}
|
||||
maxDists.push(maxDist);
|
||||
bucketWidths.push(maxDist / numBuckets);
|
||||
}
|
||||
|
||||
// console.log(fullDists);
|
||||
|
||||
for (var j = 0; j < numPivots; j++) {
|
||||
var bucketWidth = bucketWidths[j];
|
||||
for (var i = 0; i < sampleSet.length; i++) {
|
||||
var tmp = pivotsBuckets[j][Math.floor((fullDists[i][j] - 0.0001) / bucketWidth)];
|
||||
// pivotsBuckets[j][Math.floor((fullDists[i][j] - 0.0001) / bucketWidth)].push(sampleSet[i]);
|
||||
// console.log(tmp, i, j, bucketWidth, Math.floor((fullDists[i][j] - 0.0001) / bucketWidth));
|
||||
tmp.push(sampleSet[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Find parents
|
||||
for (var r = 0, bNum, minIndex; r < remainderSet.length; r++) {
|
||||
var node = remainderSet[r];
|
||||
var clDist = Number.MAX_VALUE;
|
||||
for (var p = 0; p < numPivots; p++) {
|
||||
var comp = pivots[p];
|
||||
var bucketWidth = bucketWidths[p];
|
||||
if (node !== comp) {
|
||||
var dist = distance(node, comp);
|
||||
bNum = Math.floor((dist - 0.0001) / bucketWidth);
|
||||
if (bNum >= numBuckets) {
|
||||
bNum = numBuckets - 1;
|
||||
} else if (bNum < 0) {
|
||||
bNum = 0;
|
||||
}
|
||||
var bucketContents = pivotsBuckets[p][bNum];
|
||||
for (var w = 0; w < bucketContents.length; w++) {
|
||||
var c1 = bucketContents[w];
|
||||
if (c1 != node) {
|
||||
dist = distance(c1, node);
|
||||
if (dist <= clDist) {
|
||||
clDist = dist;
|
||||
minIndex = bucketContents[w];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
parents.push(minIndex);
|
||||
}
|
||||
return parents;
|
||||
}
|
||||
|
||||
function createRandomSample(nodes, max, size) {
|
||||
var randElements = [];
|
||||
|
||||
for (var i = 0; i < size; ++i) {
|
||||
// Stop when no new elements can be found.
|
||||
if (randElements.size >= nodes.length) {
|
||||
break;
|
||||
}
|
||||
var rand = Math.floor((Math.random() * max));
|
||||
// If the rand is already in random list or in exclude list
|
||||
// ignore it and get a new value.
|
||||
while (randElements.includes(rand)) {
|
||||
rand = Math.floor((Math.random() * max));
|
||||
}
|
||||
randElements.push(nodes[rand]);
|
||||
}
|
||||
|
||||
return randElements;
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
h1 {
|
||||
text-align: center;
|
||||
margin: 10px 0 10px 0;
|
||||
}
|
||||
|
||||
.links line {
|
||||
stroke: #999;
|
||||
stroke-opacity: 0.6;
|
||||
}
|
||||
/*.nodes circle {
|
||||
stroke: #fff;
|
||||
stroke-width: 1.5px;
|
||||
}*/
|
||||
|
||||
circle:hover {
|
||||
fill: #8B0000;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.notSelected {
|
||||
fill: #999;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.highlighted {
|
||||
fill: black;
|
||||
}
|
||||
|
||||
#svg {
|
||||
border-style: solid;
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
.left {
|
||||
float: left;
|
||||
width: 32%;
|
||||
}
|
||||
|
||||
.controls {
|
||||
flex-basis: 200px;
|
||||
padding: 0 5px;
|
||||
}
|
||||
|
||||
.controls input[type="range"] {
|
||||
margin: 0 5% 0.5em 5%;
|
||||
width: 90%;
|
||||
}
|
||||
|
||||
.multiplier {
|
||||
margin: 10px 0 10px 0;
|
||||
}
|
||||
|
||||
.parameters {
|
||||
margin: 10px 0 10px 30px;
|
||||
}
|
||||
|
||||
.checkbox {
|
||||
margin: 10px 0 10px 0;
|
||||
}
|
||||
|
||||
.start {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
div.tooltip {
|
||||
position: absolute;
|
||||
border: 0px;
|
||||
border-radius: 8px;
|
||||
pointer-events: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
<body>
|
||||
<h1>Evaluation</h1>
|
||||
<svg id="svg" width="100%" height="600">
|
||||
<div class="left controls">
|
||||
|
||||
<div class="input">
|
||||
<input type="file" id="csv-file" name="files">
|
||||
</div>
|
||||
|
||||
<div class="multiplier">
|
||||
<label title="The size of the nodes">
|
||||
Node size
|
||||
<output id="nodeSizeSliderOutput">10</output>
|
||||
<input type="range" min="5" max="200" value="10" step="5" oninput="d3.select('#nodeSizeSliderOutput').text(value); NODE_SIZE=value; d3.selectAll('circle').attr('r', value);">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="The number that distance is multiplied by in order to improve the visibility of the graph">
|
||||
distanceMultiplier
|
||||
<output id="distanceMultiplierSliderOutput">50</output>
|
||||
<input type="range" min="5" max="1000" value="50" step="5" oninput="d3.select('#distanceMultiplierSliderOutput').text(value); MULTIPLIER=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="Number of iterations before the simulation is stopped">
|
||||
Iterations
|
||||
<output id="iterationsSliderOutput">300</output>
|
||||
<input type="range" min="5" max="5000" value="300" step="5" oninput="d3.select('#iterationsSliderOutput').text(value); ITERATIONS=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="Attribute used for coloring nodes">
|
||||
Color attribute
|
||||
<select id="color_attr" onchange="COLOR_ATTRIBUTE=value; colorToAttribute();">
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="checkbox">
|
||||
<label title="js/">
|
||||
Rendering
|
||||
<input type="checkbox" checked onclick="rendering=!rendering;">
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="start">
|
||||
<button id="startSimulation" form="algorithmForm">Start</button>
|
||||
<button onclick="stopSimulation()">Stop</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="left">
|
||||
<p>Select algorithm:</p>
|
||||
<div id="algorithms">
|
||||
<input id="HLButton" type="radio" name="algorithm" onclick="d3.select('#startSimulation').on('click', startHybridSimulation)">Hybrid
|
||||
layout
|
||||
<br>
|
||||
<div id="HLParameters" class="parameters" style="display:none">
|
||||
<div id="pivots">
|
||||
<input id="BFButton" type="radio" name="pivots" checked="checked" onclick="PIVOTS=false;">Brute-force<br>
|
||||
<input id="PButton" type="radio" name="pivots" onclick="PIVOTS=true;">Pivots<br>
|
||||
<div id="numPivots" class="parameters" style="display:none">
|
||||
<label title="The number of pivots">
|
||||
Number of Pivots
|
||||
<output id="numPivotsSliderOutput">3</output><br/>
|
||||
<input type="range" min="1" max="50" value="3" step="1" oninput="d3.select('#numPivotsSliderOutput').text(value); NUM_PIVOTS=value;">
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<br/>
|
||||
<label title="Number of iterations done at the end">
|
||||
Full iterations
|
||||
<output id="fullIterationsSliderOutput">20</output><br/>
|
||||
<input type="range" min="1" max="100" value="20" step="1" oninput="d3.select('#fullIterationsSliderOutput').text(value); FULL_ITERATIONS=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="NeighbourSize">
|
||||
Neighbour Set
|
||||
<output id="hlneighbourSizeSliderOutput">6</output><br/>
|
||||
<input type="range" min="1" max="100" value="6" step="1" oninput="d3.select('#hlneighbourSizeSliderOutput').text(value); NEIGHBOUR_SIZE=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="SampleSize">
|
||||
Sample Set
|
||||
<output id="hlsampleSizeSliderOutput">3</output><br/>
|
||||
<input type="range" min="1" max="100" value="3" step="1" oninput="d3.select('#hlsampleSizeSliderOutput').text(value); SAMPLE_SIZE=value;">
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<input id="NSButton" type="radio" name="algorithm" onclick="d3.select('#startSimulation').on('click', startNeighbourSamplingSimulation)">Neighbour
|
||||
and Sampling<br>
|
||||
<div id="NSParameters" class="parameters" style="display:none">
|
||||
<label title="NeighbourSize">
|
||||
Neighbour Set
|
||||
<output id="neighbourSizeSliderOutput">6</output><br/>
|
||||
<input type="range" min="1" max="100" value="6" step="1" oninput="d3.select('#neighbourSizeSliderOutput').text(value); NEIGHBOUR_SIZE=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="SampleSize">
|
||||
Sample Set
|
||||
<output id="sampleSizeSliderOutput">3</output><br/>
|
||||
<input type="range" min="1" max="100" value="3" step="1" oninput="d3.select('#sampleSizeSliderOutput').text(value); SAMPLE_SIZE=value;">
|
||||
</label>
|
||||
</div>
|
||||
<input class="noParameters" type="radio" name="algorithm" onclick="d3.select('#startSimulation').on('click', startLinkSimulation)">Link
|
||||
force in D3<br>
|
||||
<input class="noParameters" type="radio" name="algorithm" onclick="d3.select('#startSimulation').on('click', startBarnesHutSimulation)">Barnes-Hut<br>
|
||||
<input id="tSNEButton" type="radio" name="algorithm" onclick="d3.select('#startSimulation').on('click', starttSNE)">t-SNE<br>
|
||||
<div id="tSNEParameters" class="parameters" style="display:none">
|
||||
<label title="Perplexity">
|
||||
Perplexity
|
||||
<output id="perplexitySliderOutput">30</output><br/>
|
||||
<input type="range" min="1" max="500" value="30" step="1" oninput="d3.select('#perplexitySliderOutput').text(value); PERPLEXITY=value;">
|
||||
</label>
|
||||
<br/>
|
||||
<label title="LearningRate">
|
||||
Learning Rate
|
||||
<output id="learningRateSliderOutput">10</output><br/>
|
||||
<input type="range" min="1" max="500" value="10" step="1" oninput="d3.select('#learningRateSliderOutput').text(value); LEARNING_RATE=value;">
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="left">
|
||||
<p>Select distance function:</p>
|
||||
<div id="distance">
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateDistance"> General<br>
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateEuclideanDistance"> Euclidean<br>
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateManhattanDistance"> Manhattan<br>
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateJaccardDissimilarity"> Jaccard<br>
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateDiceDissimilarity"> Dice<br>
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateCosineSimilarity"> Cosine<br>
|
||||
<input type="radio" name="distance" onclick="distanceFunction=calculateDistancePoker"> Poker Hands<br>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</svg>
|
||||
</body>
|
||||
|
||||
<!-- Load the files and libraries used. -->
|
||||
<script src="js/lib/d3.v4.min.js"></script>
|
||||
<script src="js/lib/papaparse.js"></script>
|
||||
<script src="js/lib/jquery-3.1.1.js"></script>
|
||||
<script src="js/lib/intercom.js"></script>
|
||||
<script src="../build/d3-neighbour-sampling.js"></script>
|
||||
<script src="js/src/neighbourSampling-papaparsing-nist-images.js"></script>
|
||||
<script src="js/distances/distancePokerHands.js"></script>
|
||||
<script src="js/distances/distance.js"></script>
|
||||
<script src="js/distances/euclideanDistance.js"></script>
|
||||
<script src="js/distances/euclideanDistanceInTSNE.js"></script>
|
||||
<script src="js/distances/manhattanDistance.js"></script>
|
||||
<script src="js/distances/jaccardDissimilarity.js"></script>
|
||||
<script src="js/distances/diceDissimilarity.js"></script>
|
||||
<script src="js/distances/cosineSimilarity.js"></script>
|
||||
<script src="js/distances/normalization.js"></script>
|
||||
<script src="js/distances/numeric.js"></script>
|
||||
|
||||
|
||||
<script>
|
||||
$(document).ready(function () {
|
||||
$("#csv-file").change(function (d) {
|
||||
parseFile(d);
|
||||
$("#color_attr option").remove();
|
||||
});
|
||||
|
||||
$("#tSNEButton").click(function () {
|
||||
$(".parameters").hide();
|
||||
$("#tSNEParameters").show();
|
||||
});
|
||||
|
||||
$("#NSButton").click(function () {
|
||||
$(".parameters").hide();
|
||||
$("#NSParameters").show();
|
||||
});
|
||||
|
||||
$("#HLButton").click(function () {
|
||||
$(".parameters").hide();
|
||||
$("#HLParameters").show();
|
||||
if ($("#PButton").is(":checked")) {
|
||||
$("#numPivots").show();
|
||||
}
|
||||
});
|
||||
|
||||
$("#BFButton").click(function () {
|
||||
$("#numPivots").hide();
|
||||
});
|
||||
|
||||
$("#PButton").click(function () {
|
||||
$("#numPivots").show();
|
||||
});
|
||||
|
||||
$(".noParameters").click(function () {
|
||||
$(".parameters").hide();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
</html>
|
||||
Reference in new issue
Block a user