Commit c6d60bbc authored by Romain Loth's avatar Romain Loth

Squashed 'tinawebJS/' content from commit 86a6f0c

git-subtree-dir: tinawebJS
git-subtree-split: 86a6f0c88f988976bca0c9dd3b081105bf9fc482
parents
function scanDataFolder(){
$.ajax({
type: 'GET',
url: 'php/DirScan_main.php',
//data: "type="+type+"&query="+jsonparams,
//contentType: "application/json",
//dataType: 'json',
success : function(data){
console.log(data);
dataFolderTree=data;
},
error: function(){
console.log('Page Not found: updateLeftPanel_uni()');
}
});
}
function getGexfPath(v){
gexfpath=(gexfDictReverse[v])?gexfDictReverse[v]:v;
return gexfpath;
}
function getGexfLegend(gexfPath){
legend=(gexfDict[gexfPath])?gexfDict[gexfPath]:gexfPath;
return legend;
}
function jsActionOnGexfSelector(gexfLegend){
window.location=window.location.origin+window.location.pathname+"?file="+encodeURIComponent(getGexfPath(gexfLegend));
}
function listGexfs(){
divlen=$("#gexfs").length;
if(divlen>0) {
param = JSON.stringify(gexfDict);
$.ajax({
type: 'GET',
url: 'php/listFiles.php',
//contentType: "application/json",
//dataType: 'json',
success : function(data){
html="<select style='width:150px;' ";
javs='onchange="'+'jsActionOnGexfSelector(this.value);'+'"';
html+=javs;
html+=">";
html+='<option selected>[More Graphs]</option>';
for(var i in data){
//pr("path: "+data[i]);
//pr("legend: "+getGexfLegend(data[i]));
//pr("");
html+="<option>"+getGexfLegend(data[i])+"</option>";
}
html+="</select>";
$("#gexfs").html(html);
},
error: function(){
console.log("Page Not found.");
}
});
}
}
// Mathieu Jacomy @ Sciences Po Médialab & WebAtlas
var ForceAtlas2 = function(graph) {
var self = this;
this.graph = graph;
this.p = {
linLogMode: false,
outboundAttractionDistribution: false,
adjustSizes: false,
edgeWeightInfluence: 0,
scalingRatio: 1,
strongGravityMode: false,
gravity: 1,
jitterTolerance: 1,
barnesHutOptimize: false,
barnesHutTheta: 1.2,
speed: 20,
outboundAttCompensation: 1,
totalSwinging: 0,
swingVSnode1: 0,
banderita: false,
totalEffectiveTraction: 0,
complexIntervals: 500,
simpleIntervals: 1000
};
// The state tracked from one atomic "go" to another
this.state = {step: 0, index: 0};
this.rootRegion;
// Runtime (the ForceAtlas2 itself)
this.init = function() {
self.state = {step: 0, index: 0};
self.graph.nodes.forEach(function(n) {
n.fa2 = {
mass: 1 + n.degree,
old_dx: 0,
old_dy: 0,
dx: 0,
dy: 0
};
});
return self;
}
this.go = function() {
while (self.onebucle()) {}
}
this.onebucle = function() {
var graph = self.graph;
var nodes = graph.nodes;
var edges = graph.edges;
var cInt = self.p.complexIntervals;
var sInt = self.p.simpleIntervals;
switch (self.state.step) {
case 0: // Pass init
// Initialise layout data
// pr("caso 0")
nodes.forEach(function(n) {
if(n.fa2) {
n.fa2.mass = 1 + n.degree;
n.fa2.old_dx = n.fa2.dx;
n.fa2.old_dy = n.fa2.dx;
n.fa2.dx = 0;
n.fa2.dy = 0;
} else {
n.fa2 = {
mass: 1 + n.degree,
old_dx: 0,
old_dy: 0,
dx: 0,
dy: 0
};
}
});
// If Barnes Hut active, initialize root region
if (self.p.barnesHutOptimize) {
self.rootRegion = new Region(nodes, 0);
self.rootRegion.buildSubRegions();
}
// If outboundAttractionDistribution active, compensate.
if (self.p.outboundAttractionDistribution) {
self.p.outboundAttCompensation = 0;
nodes.forEach(function(n) {
self.p.outboundAttCompensation += n.fa2.mass;
});
self.p.outboundAttCompensation /= nodes.length;
}
self.state.step = 1;
self.state.index = 0;
return true;
break;
case 1: // Repulsion
// pr("caso 1")
var Repulsion = self.ForceFactory.buildRepulsion(
self.p.adjustSizes,
self.p.scalingRatio
);
if (self.p.barnesHutOptimize) {
var rootRegion = self.rootRegion;
// Pass to the scope of forEach
var barnesHutTheta = self.p.barnesHutTheta;
var i = self.state.index;
while (i < nodes.length && i < self.state.index + cInt) {
var n = nodes[i++];
if(n.fa2)
rootRegion.applyForce(n, Repulsion, barnesHutTheta);
}
if (i == nodes.length) {
self.state.step = 2;
self.state.index = 0;
} else {
self.state.index = i;
}
} else {
var i1 = self.state.index;
while (i1 < nodes.length && i1 < self.state.index + cInt) {
var n1 = nodes[i1++];
if(n1.fa2)
nodes.forEach(function(n2, i2) {
if (i2 < i1 && n2.fa2) {
Repulsion.apply_nn(n1, n2);
}
});
}
if (i1 == nodes.length) {
self.state.step = 2;
self.state.index = 0;
} else {
self.state.index = i1;
}
}
return true;
break;
case 2: // Gravity
// pr("caso 2")
var Gravity = (self.p.strongGravityMode) ?
(self.ForceFactory.getStrongGravity(
self.p.scalingRatio
)) :
(self.ForceFactory.buildRepulsion(
self.p.adjustSizes,
self.p.scalingRatio
));
// Pass gravity and scalingRatio to the scope of the function
var gravity = self.p.gravity,
scalingRatio = self.p.scalingRatio;
var i = self.state.index;
while (i < nodes.length && i < self.state.index + sInt) {
var n = nodes[i++];
if (n.fa2)
Gravity.apply_g(n, gravity / scalingRatio);
}
if (i == nodes.length) {
self.state.step = 3;
self.state.index = 0;
} else {
self.state.index = i;
}
return true;
break;
case 3: // Attraction
// pr("caso 3")
var Attraction = self.ForceFactory.buildAttraction(
self.p.linLogMode,
self.p.outboundAttractionDistribution,
self.p.adjustSizes,
1 * ((self.p.outboundAttractionDistribution) ?
(self.p.outboundAttCompensation) :
(1))
);
var i = self.state.index;
if (self.p.edgeWeightInfluence == 0) {
while (i < edges.length && i < self.state.index + cInt) {
var e = edges[i++];
Attraction.apply_nn(e.source, e.target, 1);
}
} else if (self.p.edgeWeightInfluence == 1) {
while (i < edges.length && i < self.state.index + cInt) {
var e = edges[i++];
Attraction.apply_nn(e.source, e.target, e.weight || 1);
}
} else {
while (i < edges.length && i < self.state.index + cInt) {
var e = edges[i++];
Attraction.apply_nn(
e.source, e.target,
Math.pow(e.weight || 1, self.p.edgeWeightInfluence)
);
}
}
if (i == edges.length) {
self.state.step = 4;
self.state.index = 0;
} else {
self.state.index = i;
}
return true;
break;
case 4: // Auto adjust speed
// pr("caso 4")
var totalSwinging = 0; // How much irregular movement
var totalEffectiveTraction = 0; // Hom much useful movement
var swingingSum=0;
var promdxdy=0; /**/
nodes.forEach(function(n) {
var fixed = n.fixed || false;
if (!fixed && n.fa2) {
var swinging = Math.sqrt(Math.pow(n.fa2.old_dx - n.fa2.dx, 2) +
Math.pow(n.fa2.old_dy - n.fa2.dy, 2));
// If the node has a burst change of direction,
// then it's not converging.
totalSwinging += n.fa2.mass * swinging;
swingingSum += swinging;
promdxdy += (Math.abs(n.fa2.dx)+Math.abs(n.fa2.dy))/2; /**/
totalEffectiveTraction += n.fa2.mass *
0.5 *
Math.sqrt(
Math.pow(n.fa2.old_dx + n.fa2.dx, 2) +
Math.pow(n.fa2.old_dy + n.fa2.dy, 2)
);
}
});
self.p.totalSwinging = totalSwinging;
var convg= ((Math.pow(nodes.length,2))/promdxdy); /**/
var swingingVSnodes_length = swingingSum/nodes.length; /**/
// if(convg > swingingVSnodes_length){
// self.p.banderita=true;
// }
self.p.totalEffectiveTraction = totalEffectiveTraction;
// We want that swingingMovement < tolerance * convergenceMovement
var targetSpeed = Math.pow(self.p.jitterTolerance, 2) *
self.p.totalEffectiveTraction /
self.p.totalSwinging;
// But the speed shoudn't rise too much too quickly,
// since it would make the convergence drop dramatically.
var maxRise = 0.5; // Max rise: 50%
self.p.speed = self.p.speed +
Math.min(
targetSpeed - self.p.speed,
maxRise * self.p.speed
);
// Save old coordinates
nodes.forEach(function(n) {
n.old_x = +n.x;
n.old_y = +n.y;
});
self.state.step = 5;
return true;
break;
case 5: // Apply forces
// pr("caso 5")
var i = self.state.index;
if (self.p.adjustSizes) {
var speed = self.p.speed;
// If nodes overlap prevention is active,
// it's not possible to trust the swinging mesure.
while (i < nodes.length && i < self.state.index + sInt) {
var n = nodes[i++];
var fixed = n.fixed || false;
if (!fixed && n.fa2) {
// Adaptive auto-speed: the speed of each node is lowered
// when the node swings.
var swinging = Math.sqrt(
(n.fa2.old_dx - n.fa2.dx) *
(n.fa2.old_dx - n.fa2.dx) +
(n.fa2.old_dy - n.fa2.dy) *
(n.fa2.old_dy - n.fa2.dy)
);
var factor = 0.1 * speed / (1 + speed * Math.sqrt(swinging));
var df = Math.sqrt(Math.pow(n.fa2.dx, 2) +
Math.pow(n.fa2.dy, 2));
factor = Math.min(factor * df, 10) / df;
n.x += n.fa2.dx * factor;
n.y += n.fa2.dy * factor;
}
}
} else {
var speed = self.p.speed;
while (i < nodes.length && i < self.state.index + sInt) {
var n = nodes[i++];
var fixed = n.fixed || false;
if (!fixed && n.fa2) {
// Adaptive auto-speed: the speed of each node is lowered
// when the node swings.
var swinging = Math.sqrt(
(n.fa2.old_dx - n.fa2.dx) *
(n.fa2.old_dx - n.fa2.dx) +
(n.fa2.old_dy - n.fa2.dy) *
(n.fa2.old_dy - n.fa2.dy)
);
var factor = speed / (1 + speed * Math.sqrt(swinging));
n.x += n.fa2.dx * factor;
n.y += n.fa2.dy * factor;
}
}
}
if(self.p.banderita) return "fini";
if (i == nodes.length) {
self.state.step = 0;
self.state.index = 0;
return false;
} else {
self.state.index = i;
return true;
}
break;
default:
throw new Error('ForceAtlas2 - atomic state error');
break;
}
}
this.end = function() {
this.graph.nodes.forEach(function(n) {
n.fa2 = null;
});
}
// Auto Settings
this.setAutoSettings = function() {
var graph = this.graph;
// Tuning
if (graph.nodes.length >= 100) {
this.p.scalingRatio = 2.0;
} else {
this.p.scalingRatio = 10.0;
}
this.p.strongGravityMode = false;
this.p.gravity = 1;
// Behavior
this.p.outboundAttractionDistribution = false;
this.p.linLogMode = false;
this.p.adjustSizes = false;
this.p.edgeWeightInfluence = 1;
// Performance
if (graph.nodes.length >= 50000) {
this.p.jitterTolerance = 10;
} else if (graph.nodes.length >= 5000) {
this.p.jitterTolerance = 1;
} else {
this.p.jitterTolerance = 0.1;
}
if (graph.nodes.length >= 1000) {
this.p.barnesHutOptimize = false;
} else {
this.p.barnesHutOptimize = false;
}
this.p.barnesHutTheta = 1.2;
return this;
}
// All the different forces
this.ForceFactory = {
buildRepulsion: function(adjustBySize, coefficient) {
if (adjustBySize) {
return new this.linRepulsion_antiCollision(coefficient);
} else {
return new this.linRepulsion(coefficient);
}
},
getStrongGravity: function(coefficient) {
return new this.strongGravity(coefficient);
},
buildAttraction: function(logAttr, distributedAttr, adjustBySize, c) {
if (adjustBySize) {
if (logAttr) {
if (distributedAttr) {
return new this.logAttraction_degreeDistributed_antiCollision(c);
} else {
return new this.logAttraction_antiCollision(c);
}
} else {
if (distributedAttr) {
return new this.linAttraction_degreeDistributed_antiCollision(c);
} else {
return new this.linAttraction_antiCollision(c);
}
}
} else {
if (logAttr) {
if (distributedAttr) {
return new this.logAttraction_degreeDistributed(c);
} else {
return new this.logAttraction(c);
}
} else {
if (distributedAttr) {
return new this.linAttraction_massDistributed(c);
} else {
return new this.linAttraction(c);
}
}
}
},
// Repulsion force: Linear
linRepulsion: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient *
n1.fa2.mass *
n2.fa2.mass /
Math.pow(distance, 2);
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
this.apply_nr = function(n, r) {
// Get the distance
var xDist = n.x - r.config('massCenterX');
var yDist = n.y - r.config('massCenterY');
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient *
n.fa2.mass *
r.config('mass') /
Math.pow(distance, 2);
n.fa2.dx += xDist * factor;
n.fa2.dy += yDist * factor;
}
}
this.apply_g = function(n, g) {
// Get the distance
var xDist = n.x;
var yDist = n.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient * n.fa2.mass * g / distance;
n.fa2.dx -= xDist * factor;
n.fa2.dy -= yDist * factor;
}
}
},
linRepulsion_antiCollision: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist) -
n1.size -
n2.size;
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient *
n1.fa2.mass *
n2.fa2.mass /
Math.pow(distance, 2);
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
} else if (distance < 0) {
var factor = 100 * this.coefficient * n1.fa2.mass * n2.fa2.mass;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
this.apply_nr = function(n, r) {
// Get the distance
var xDist = n.fa2.x() - r.getMassCenterX();
var yDist = n.fa2.y() - r.getMassCenterY();
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient *
n.fa2.mass *
r.getMass() /
Math.pow(distance, 2);
n.fa2.dx += xDist * factor;
n.fa2.dy += yDist * factor;
} else if (distance < 0) {
var factor = -this.coefficient * n.fa2.mass * r.getMass() / distance;
n.fa2.dx += xDist * factor;
n.fa2.dy += yDist * factor;
}
}
this.apply_g = function(n, g) {
// Get the distance
var xDist = n.x;
var yDist = n.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient * n.fa2.mass * g / distance;
n.fa2.dx -= xDist * factor;
n.fa2.dy -= yDist * factor;
}
}
},
// Repulsion force: Strong Gravity
// (as a Repulsion Force because it is easier)
strongGravity: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2) {
// Not Relevant
}
this.apply_nr = function(n, r) {
// Not Relevant
}
this.apply_g = function(n, g) {
// Get the distance
var xDist = n.x;
var yDist = n.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient * n.fa2.mass * g;
n.fa2.dx -= xDist * factor;
n.fa2.dy -= yDist * factor;
}
}
},
// Attraction force: Linear
linAttraction: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
// NB: factor = force / distance
var factor = -this.coefficient * e;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
},
// Attraction force: Linear, distributed by mass (typically, degree)
linAttraction_massDistributed: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
// NB: factor = force / distance
var factor = -this.coefficient * e / n1.fa2.mass;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
},
// Attraction force: Logarithmic
logAttraction: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = -this.coefficient *
e *
Math.log(1 + distance) /
distance;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
},
// Attraction force: Linear, distributed by Degree
logAttraction_degreeDistributed: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = -this.coefficient *
e *
Math.log(1 + distance) /
distance /
n1.fa2.mass;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
},
// Attraction force: Linear, with Anti-Collision
linAttraction_antiCollision: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = -this.coefficient * e;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
},
// Attraction force: Linear, distributed by Degree, with Anti-Collision
linAttraction_degreeDistributed_antiCollision: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = -this.coefficient * e / n1.fa2.mass;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
},
// Attraction force: Logarithmic, with Anti-Collision
logAttraction_antiCollision: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = -this.coefficient *
e *
Math.log(1 + distance) /
distance;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
},
// Attraction force: Linear, distributed by Degree, with Anti-Collision
logAttraction_degreeDistributed_antiCollision: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = -this.coefficient *
e *
Math.log(1 + distance) /
distance /
n1.fa2.mass;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
}
};
};
var updateMassAndGeometry = function() {
if (this.nodes.length > 1) {
// Compute Mass
var mass = 0;
var massSumX = 0;
var massSumY = 0;
this.nodes.forEach(function(n) {
mass += n.fa2.mass;
massSumX += n.x * n.fa2.mass;
massSumY += n.y * n.fa2.mass;
});
var massCenterX = massSumX / mass;
massCenterY = massSumY / mass;
// Compute size
var size;
this.nodes.forEach(function(n) {
var distance = Math.sqrt(
(n.x - massCenterX) *
(n.x - massCenterX) +
(n.y - massCenterY) *
(n.y - massCenterY)
);
size = Math.max(size || (2 * distance), 2 * distance);
});
this.p.mass = mass;
this.p.massCenterX = massCenterX;
this.p.massCenterY = massCenterY;
this.size = size;
}
};
// The Region class, as used by the Barnes Hut optimization
var Region = function(nodes, depth) {
this.depthLimit = 20;
this.size = 0;
this.nodes = nodes;
this.subregions = [];
this.depth = depth;
this.p = {
mass: 0,
massCenterX: 0,
massCenterY: 0
};
console.log("updating mass and geometry");
this.updateMassAndGeometry();
}
var buildSubRegions = function() {
if (this.nodes.length > 1) {
var leftNodes = [];
var rightNodes = [];
var subregions = [];
var massCenterX = this.p.massCenterX;
var massCenterY = this.p.massCenterY;
var nextDepth = this.depth + 1;
var self = this;
this.nodes.forEach(function(n) {
var nodesColumn = (n.x < massCenterX) ? (leftNodes) : (rightNodes);
nodesColumn.push(n);
});
var tl = [], bl = [], br = [], tr = [];
leftNodes.forEach(function(n) {
var nodesLine = (n.y < massCenterY) ? (tl) : (bl);
nodesLine.push(n);
});
rightNodes.forEach(function(n) {
var nodesLine = (n.y < massCenterY) ? (tr) : (br);
nodesLine.push(n);
});
[tl, bl, br, tr].filter(function(a) {
return a.length;
}).forEach(function(a) {
if (nextDepth <= self.depthLimit && a.length < self.nodes.length) {
var subregion = new Region(a, nextDepth);
subregions.push(subregion);
} else {
a.forEach(function(n) {
var oneNodeList = [n];
var subregion = new Region(oneNodeList, nextDepth);
subregions.push(subregion);
});
}
});
this.subregions = subregions;
subregions.forEach(function(subregion) {
subregion.buildSubRegions();
});
}
};
var applyForce = function(n, Force, theta) {
if (this.nodes.length < 2) {
var regionNode = this.nodes[0];
Force.apply_nn(n, regionNode);
} else {
var distance = Math.sqrt(
(n.x - this.p.massCenterX) *
(n.x - this.p.massCenterX) +
(n.y - this.p.massCenterY) *
(n.y - this.p.massCenterY)
);
if (distance * theta > this.size) {
Force.apply_nr(n, this);
} else {
this.subregions.forEach(function(subregion) {
subregion.applyForce(n, Force, theta);
});
}
}
};
var startForceAtlas2 = function(graph,limit_it) {
// pr("inside FA2")
//// if(!this.forceatlas2) {
// pr(graph);
// pr(graph.nodes[0].x)
// pr(graph.nodes[0].y)
// pr("--------")
// nodes = graph.nodes;
// for(var n in nodes) {
// if(!nodes[n].hidden)
// nodes[n].degree = 0;
// }
// edges = graph.edges;
// for(var e in edges) {
// if(!edges[e].hidden) {
// }
// }
forceatlas2 = new ForceAtlas2(graph);
forceatlas2.setAutoSettings();
forceatlas2.init();
count=0;
flag=false;
while(true){
for(var jt=0;jt<=5;jt++){
ret=forceatlas2.onebucle();
if(ret=="fini") {
flag=true;
break;
}
}
count++;
if(flag||count>limit_it) break;
}
// pr(forceatlas2.graph.nodes[0].x)
// pr(forceatlas2.graph.nodes[0].y)
// console.log("\titerations: "+count)
result={
"nodes":forceatlas2.graph.nodes,
"it":count
}
return result;
};
self.addEventListener("message", function(e) {
var graph = {
"nodes":e.data.nodes,
"edges":e.data.edges
}
var limit_it=e.data.it;
result=startForceAtlas2(graph,limit_it)
postMessage({
"nodes":result.nodes,
"it":result.it
});
}, false);
\ No newline at end of file
#!/bin/bash
#
find . -name '*~' -delete
//============================ < NEW BUTTONS > =============================//
function changeType() {
pr("***swclickActual:"+swclickActual+" , swMacro:"+swMacro);
if(swclickActual=="social") {
if(swMacro) {
changeToMacro("semantic");
pushSWClick("semantic");
RefreshState("B")
} else {
//From soc* to SocSem
if(is_empty(selections)) {
//soc to SocSem
changeToMacro("semantic");
pushSWClick("semantic");
RefreshState("B")
} else {
//soc* to SocSem
changeToMeso("sociosemantic");
pushSWClick("sociosemantic");
RefreshState("AaBb")
}
}
return;
}
if(swclickActual=="semantic") {
if(swMacro) {
changeToMacro("social");
pushSWClick("social");
RefreshState("A");
} else {
if(is_empty(selections)) {
changeToMacro("social");
pushSWClick("social");
RefreshState("A");
} else {
changeToMeso("sociosemantic");
pushSWClick("sociosemantic");
RefreshState("AaBb");
}
}
return;
}
if(swclickActual=="sociosemantic") {
if(swMacro) {
changeToMacro("sociosemantic");
pushSWClick("sociosemantic");
RefreshState("AaBb")
} else {
if(is_empty(selections)) {
changeToMacro(swclickPrev);
pushSWClick(swclickPrev);
RefreshState(PAST.toUpperCase())
} else {
//there is an active selection
//identify type of the current-selection
var countTypes = {};
for(var i in selections) {
if( isUndef(countTypes[Nodes[i].type]) )
countTypes[Nodes[i].type]=1;
else
countTypes[Nodes[i].type]++;
}
pr("bigraph #selectionsTypes: ")
pr(countTypes)
cpCountTypes = Object.keys(countTypes);
if(cpCountTypes.length==1) {
if(cpCountTypes[0]==catSoc) {
pushSWClick("social");
changeToMeso("social");
RefreshState("a");
} else {
pushSWClick("semantic");
changeToMeso("semantic");
RefreshState("b");
}
} else {
//there is a selection with both kind of nodes
//Manually changing the selection, not using MultipleSelection
var ndsids = [];
for(var i in selections) {
if( Nodes[i].type == catSoc )
ndsids.push(i);
}
cancelSelection(false);
for(var i in ndsids){
nodeid = ndsids[i]
getOpossitesNodes(nodeid,false); //false -> just nodeid
}
pushSWClick("social");
changeToMeso("social");
RefreshState("a");
}
}
}
return;
}
}
function changeLevel() {
bf=swclickActual
pushSWClick(swclickActual);
pr("swMacro: "+swMacro+" - [swclickPrev: "+bf+"] - [swclickActual: "+swclickActual+"]")
if(swMacro){
// Macro Level -- swMacro:true
if(swclickActual=="social") {
changeToMeso("social")
RefreshState("a");
}
if(swclickActual=="semantic") {
changeToMeso("semantic")
RefreshState("b");
}
swMacro=false;
return;
} else {
// Meso Level -- swMacro:false
if(swclickActual=="social") {
changeToMacro("social")
RefreshState("A")
}
if(swclickActual=="semantic") {
changeToMacro("semantic")
RefreshState("B")
}
swMacro=true;
return;
}
}
//============================= </ NEW BUTTONS > =============================//
//=========================== < FILTERS-SLIDERS > ===========================//
function NodeSizeSlider(sliderDivID, myType, myValue, myColor) {
$(sliderDivID).html()
$(sliderDivID).freshslider({
step:1,
min:1,
max:25,
value:myValue,
bgcolor:myColor,
onchange:function(value){
$.doTimeout(100,function (){
partialGraph.iterNodes(function (n) {
if(Nodes[n.id].type==myType) {
n.size = parseFloat(Nodes[n.id].size) + parseFloat((value-1))*0.3;
sizeMult[myType] = parseFloat(value-1)*0.3;
}
});
partialGraph.draw();
});
}
});
}
// Execution modes:
// EdgeWeightFilter("#sliderAEdgeWeight", "label" , "nodes1", "weight");
// EdgeWeightFilter("#sliderBEdgeWeight", "label" , "nodes2", "weight");
function EdgeWeightFilter(sliderDivID , type_attrb , type , criteria) {
if ($(sliderDivID).html()!="") {
pr("\t\t\t\t\t\t[[ algorithm not applied "+sliderDivID+" ]]")
return;
}
// sliderDivID = "#sliderAEdgeWeight"
// type = "nodes1"
// type_attrb = "label"
// criteria = "weight"
// sliderDivID = "#sliderBNodeSize"
// type = "NGram"
// type_attrb = "type"
// criteria = "size"
if(partialGraph._core.graph.edges.length==0) {
$(sliderDivID).freshslider({
range: true,
step:1,
value:[10, 60],
enabled: false,
onchange:function(low, high){
console.log(low, high);
}
});
return;
}
var filterparams = AlgorithmForSliders ( Edges , type_attrb , type , criteria)
var steps = filterparams["steps"]
var finalarray = filterparams["finalarray"]
var lastvalue=("0-"+(steps-1));
pushFilterValue( sliderDivID , lastvalue )
//finished
$(sliderDivID).freshslider({
range: true,
step: 1,
min:0,
bgcolor: (type=="nodes1")?"#27c470":"#FFA500" ,
max:steps-1,
value:[0,steps-1],
onchange:function(low, high) {
var filtervalue = low+"-"+high
if(filtervalue!=lastFilter[sliderDivID]) {
$.doTimeout(sliderDivID+"_"+lastFilter[sliderDivID]);
$.doTimeout( sliderDivID+"_"+filtervalue,300,function () {
pr("\nprevious value "+lastvalue+" | current value "+filtervalue)
// [ Stopping FA2 ]
partialGraph.stopForceAtlas2();
// [ / Stopping FA2 ]
var t0 = lastvalue.split("-")
var mint0=parseInt(t0[0]), maxt0=parseInt(t0[1]), mint1=parseInt(low), maxt1=parseInt(high);
var addflag = false;
var delflag = false;
var iterarr = []
if(mint0!=mint1) {
if(mint0<mint1) {
delflag = true;
pr("cotainferior --||>--------|| a la derecha")
}
if(mint0>mint1) {
addflag = true;
pr("cotainferior --<||--------|| a la izquierda")
}
iterarr = calc_range(mint0,mint1).sort(compareNumbers);
}
if(maxt0!=maxt1) {
if(maxt0<maxt1) {
addflag = true;
pr("cotasuperior ||--------||>-- a la derecha")
}
if(maxt0>maxt1) {
delflag = true;
pr("cotasuperior ||--------<||-- a la izquierda")
}
iterarr = calc_range(maxt0,maxt1).sort(compareNumbers);
}
// do the important stuff
for( var c in iterarr ) {
var i = iterarr[c];
ids = finalarray[i]
if(i>=low && i<=high) {
if(addflag) {
// pr("adding "+ids.join())
for(var id in ids) {
ID = ids[id]
Edges[ID].lock = false;
if(swMacro) {
add1Edge(ID)
} else {
for (var n in partialGraph._core.graph.nodesIndex) {
sid = Edges[ID].sourceID
tid = Edges[ID].targetID
if (sid==n || tid==n) {
if(isUndef(getn(sid))) unHide(sid)
if(isUndef(getn(tid))) unHide(tid)
add1Edge(ID)
// pr("\tADD "+ID)
}
}
}
}
}
} else {
if(delflag) {
// pr("deleting "+ids.join())
for(var id in ids) {
ID = ids[id]
if(!isUndef(gete(ID)))
partialGraph.dropEdge(ID)
Edges[ID].lock = true;
// pr("\tDEL "+ID)
// pr("removeedge")
}
}
}
}
if (!is_empty(selections))
DrawAsSelectedNodes(selections)
partialGraph.refresh()
partialGraph.draw()
// [ Starting FA2 ]
$.doTimeout(30,function(){
fa2enabled=true; partialGraph.startForceAtlas2();
if(filtervalue.charAt(0)=="0") partialGraph.stopForceAtlas2();
});
// [ / Starting FA2 ]
pr("\t\t\tfilter applied!")
lastvalue = filtervalue;
});
pushFilterValue( sliderDivID , filtervalue )
}
}
});
}
// Execution modes:
// NodeWeightFilter ( "#sliderANodeWeight" , "Document" , "type" , "size")
// NodeWeightFilter ( "#sliderBNodeWeight" , "NGram" , "type" , "size")
function NodeWeightFilter(sliderDivID , type_attrb , type , criteria) {
if ($(sliderDivID).html()!="") {
pr("\t\t\t\t\t\t[[ algorithm not applied "+sliderDivID+" ]]")
return;
}
// sliderDivID = "#sliderAEdgeWeight"
// type = "nodes1"
// type_attrb = "label"
// criteria = "weight"
// sliderDivID = "#sliderBNodeSize"
// type = "NGram"
// type_attrb = "type"
// criteria = "size"
if(partialGraph._core.graph.nodes.length==0) {
$(sliderDivID).freshslider({
range: true,
step:1,
value:[10, 60],
enabled: false,
onchange:function(low, high){
console.log(low, high);
}
});
return;
}
var filterparams = AlgorithmForSliders ( Nodes , type_attrb , type , criteria)
var steps = filterparams["steps"]
var finalarray = filterparams["finalarray"]
//finished
$(sliderDivID).freshslider({
range: true,
step: 1,
min:0,
max:steps-1,
bgcolor:(type_attrb=="Document")?"#27c470":"#FFA500" ,
value:[0,steps-1],
onchange:function(low, high){
var filtervalue = low+"-"+high
if(filtervalue!=lastFilter[sliderDivID]) {
if(lastFilter[sliderDivID]=="-") {
pushFilterValue( sliderDivID , filtervalue )
return false
}
// [ Stopping FA2 ]
partialGraph.stopForceAtlas2();
// [ / Stopping FA2 ]
for(var i in finalarray) {
ids = finalarray[i]
if(i>=low && i<=high){
for(var id in ids) {
ID = ids[id]
Nodes[ID].lock = false;
if(partialGraph._core.graph.nodesIndex[ID])
partialGraph._core.graph.nodesIndex[ID].hidden = false;
}
} else {
for(var id in ids) {
ID = ids[id]
Nodes[ID].lock = true;
if(partialGraph._core.graph.nodesIndex[ID])
partialGraph._core.graph.nodesIndex[ID].hidden = true;
}
}
}
pushFilterValue(sliderDivID,filtervalue)
if (!is_empty(selections))
DrawAsSelectedNodes(selections)
partialGraph.refresh()
partialGraph.draw()
// [ Starting FA2 ]
$.doTimeout(30,function(){
fa2enabled=true; partialGraph.startForceAtlas2()
if(filtervalue.charAt(0)=="0") partialGraph.stopForceAtlas2();
});
// [ / Starting FA2 ]
}
}
});
}
// Execution modes:
// AlgorithmForSliders ( partialGraph._core.graph.edges , "label" , "nodes1" , "weight")
// AlgorithmForSliders ( partialGraph._core.graph.edges , "label" , "nodes2" , "weight")
// AlgorithmForSliders ( partialGraph._core.graph.nodes , "type" , "Document" , "size")
// AlgorithmForSliders ( partialGraph._core.graph.nodes , "type" , "NGram" , "size")
function AlgorithmForSliders( elements , type_attrb , type , criteria) {
// // ( 1 )
// // get visible sigma nodes|edges
var elems = [];/*=elements.filter(function(e) {
return e[type_attrb]==type;
});*/
for(var e in elements) {
// pr(elements[e])
// pr("\t"+type_attrb)
if( elements[e][type_attrb]==type )
elems.push(elements[e])
}
// // ( 2 )
// // extract [ "edgeID" : edgeWEIGHT ] | [ "nodeID" : nodeSIZE ]
// // and save this into edges_weight | nodes_size
var elem_attrb=[]
for (var i in elems) {
e = elems[i]
id = e.id
elem_attrb[id]=e[criteria]
// pr(id+"\t:\t"+e[criteria])
}
// pr("{ id : size|weight } ")
// pr(elem_attrb)
// // ( 3 )
// // order dict edges_weight by edge weight | nodes_size by node size
var result = ArraySortByValue(elem_attrb, function(a,b){
return a-b
//ASCENDENT
});
// pr("result: ")
// pr(result)
// pr(result.length)
// // ( 4 )
// // printing ordered ASC by weigth
// for (var i in result) {
// r = result[i]
// idid = r.key
// elemattrb = r.value
// pr(idid+"\t:\t"+elemattrb)
// // e = result[i]
// // pr(e[criteria])
// }
var N = result.length
// var magnitude = (""+N).length //order of magnitude of edges|nodes
// var exponent = magnitude - 1
// var steps = Math.pow(10,exponent) // #(10 ^ magnit-1) steps
// var stepsize = Math.round(N/steps)// ~~(visibledges / #steps)
//var roundsqrtN = Math.round( Math.sqrt( N ) );
var steps = Math.round( Math.sqrt( N ) );
var stepsize = Math.round( N / steps );
// pr("-----------------------------------")
// pr("number of visible nodes|edges: "+N);
// pr("number of steps : "+steps)
// pr("size of one step : "+stepsize)
// pr("-----------------------------------")
var finalarray = []
var counter=0
for(var i = 0; i < steps*2; i++) {
// pr(i)
var IDs = []
for(var j = 0; j < stepsize; j++) {
if(!isUndef(result[counter])) {
k = result[counter].key
// w = result[counter].value
// pr("\t["+counter+"] : "+w)
IDs.push(k)
}
counter++;
}
if(IDs.length==0) break;
finalarray[i] = IDs
}
// pr("finalarray: ")
return {"steps":finalarray.length,"finalarray":finalarray}
}
//=========================== </ FILTERS-SLIDERS > ===========================//
//============================= < SEARCH > =============================//
function updateSearchLabels(id,name,type){
labels.push({
'id' : id,
'label' : name,
'desc': type
});
}
function extractContext(string, context) {
var matched = string.toLowerCase().indexOf(context.toLowerCase());
if (matched == -1)
return string.slice(0, 20) + '...';
var begin_pts = '...', end_pts = '...';
if (matched - 20 > 0) {
var begin = matched - 20;
} else {
var begin = 0;
begin_pts = '';
}
if (matched + context.length + 20 < string.length) {
var end = matched + context.length + 20;
} else {
var end = string.length;
end_pts = '';
}
str = string.slice(begin, end);
if (str.indexOf(" ") != Math.max(str.lastIndexOf(" "), str.lastIndexOf(".")))
str = str.slice(str.indexOf(" "), Math.max(str.lastIndexOf(" "), str.lastIndexOf(".")));
return begin_pts + str + end_pts;
}
function searchLabel(string){
var id_node = '';
var n;
nds = partialGraph._core.graph.nodes.filter(function(x){return !x["hidden"]});
for(var i in nds){
n = nds[i]
if (n.label == string) {
return n;
}
}
}
function search(string) {
var id_node = '';
var results = find(string)
var coincd=[]
for(var i in results) {
coincd.push(results[i].id)
}
$.doTimeout(30,function (){
MultipleSelection(coincd , true);
$("input#searchinput").val("");
$("input#searchinput").autocomplete( "close" );
});
}
//============================ < / SEARCH > ============================//
/*
* Customize as you want ;)
*/
function callGeomap(){
db=JSON.stringify('community.db');
if(is_empty(selections)){
// jsonparams='["all"]';
jsonparams='["unique_id"]&unique_id='+egonode[getUrlParam.nodeidparam];
} else {
N=getNodesByAtt(catSoc).length;
nodesA = []
nodesB = []
socneigh = []
for(var i in selections) {
if(Nodes[i].type==catSoc) nodesA.push(i);
if(Nodes[i].type==catSem) nodesB.push(i);
}
if(nodesA.length==0 && nodesB.length>0) socneigh = getArrSubkeys(opos,"key");
if(nodesA.length>0 && nodesB.length>0) socneigh = getNeighs(nodesB,bipartiteN2D);
kSels = {}
for(var i in nodesA) {
kSels[nodesA[i]] = 1;
}
for(var i in socneigh) {
kSels[socneigh[i]] = 1;
}
k=Object.keys(kSels).length;
// cats=(categoriesIndex.length);
// arr={};
// if(cats==2 && swclickActual=="social") {
// N=Object.keys(partialGraph._core.graph.nodes.filter(function(n){return n.type==catSoc})).length;
// arr=nodes1;
// }
// if(cats==2 && swclickActual=="semantic") {
// N=Object.keys(partialGraph._core.graph.nodes.filter(function(n){return n.type==catSem})).length;
// arr=nodes2;
// }
// if(cats==1)
// N=Object.keys(Nodes).length;
// temp=getNeighs(Object.keys(selections),arr);
// sel_plus_neigh=Object.keys(temp);
// k=sel_plus_neigh.length;
// // if(N==k) jsonparams='["all"]';
pr ("N: "+N+" - k: "+k)
if(N==k) jsonparams='["unique_id"]&unique_id='+getUrlParam.nodeidparam;
else jsonparams=JSON.stringify(Object.keys(kSels));
//jsonparams=JSON.stringify(getSelections());
//jsonparams = jsonparams.split('&').join('__and__');
}
pr('in callGeomap: db='+db+'&query='+jsonparams);
initiateMap(db,jsonparams,"geomap2/");
// $("#ctlzoom").hide();
// $("#CurrentView").hide();
}
function clickInCountry( CC ) {
// pr("in extras.js: you've clicked "+CC)
var results = []
for(var i in Nodes) {
if( !isUndef(Nodes[i].CC) && Nodes[i].CC==CC) results.push(i)
}
$.doTimeout(20,function (){
if(swclickActual=="social") {
MultipleSelection(results , false); //false-> dont apply deselection algorithm
return;
}
if(swclickActual=="semantic") {
var oposresults = getNeighs2( results , bipartiteD2N );
MultipleSelection(oposresults , false);
return;
}
});
}
function callTWJS(){
// db=getCurrentDBforCurrentGexf();
// db=JSON.stringify(db);
// if(is_empty(selections)){
// jsonparams='["all"]';
// } else {
// jsonparams=JSON.stringify(getSelections());
// jsonparams = jsonparams.split('&').join('__and__');
// }
// pr('in callGeomap: db='+db+'&query='+jsonparams);
// initiateMap(db,jsonparams,"geomap/"); //From GEOMAP submod
$("#ctlzoom").show();
$("#CurrentView").show();
}
function selectionToMap(){
db=getCurrentDBforCurrentGexf();
db=JSON.stringify(db);
param='geomap/?db='+db+'';
if(is_empty(selections)){
newPopup('geomap/?db='+db+'&query=["all"]');
} else {
pr("selection to geomap:");
jsonparams=JSON.stringify(getSelections());
jsonparams = jsonparams.split('&').join('__and__');
pr('geomap/?db='+db+'&query='+jsonparams);
newPopup('geomap/?db='+db+'&query='+jsonparams);
}
}
//DataFolderMode
function getCurrentDBforCurrentGexf(){
folderID=dataFolderTree["gexf_idfolder"][decodeURIComponent(getUrlParam.file)];
dbsRaw = dataFolderTree["folders"][folderID];
dbsPaths=[];
for(var i in dbsRaw){
dbs = dbsRaw[i]["dbs"];
for(var j in dbs){
dbsPaths.push(i+"/"+dbs[j]);
}
break;
}
return dbsPaths;
}
//DataFolderMode
function getGlobalDBs(){
graphdb=dataFolderTree["folders"];
for(var i in graphdb){
for(var j in graphdb[i]){
if(j=="data") {
maindbs=graphdb[i][j]["dbs"];
for(var k in maindbs){
return jsonparams+"/"+maindbs[k];
}
}
}
}
}
//DataFolderMode
function getTopPapers(type){
if(getAdditionalInfo){
jsonparams=JSON.stringify(getSelections());
//jsonparams = jsonparams.replaceAll("&","__and__");
jsonparams = jsonparams.split('&').join('__and__');
dbsPaths=getCurrentDBforCurrentGexf();
//dbsPaths.push(getGlobalDBs());
dbsPaths=JSON.stringify(dbsPaths);
thisgexf=JSON.stringify(decodeURIComponent(getUrlParam.file));
image='<img style="display:block; margin: 0px auto;" src="'+twjs+'img/ajax-loader.gif"></img>';
$("#topPapers").html(image);
bi=(Object.keys(categories).length==2)?1:0;
$.ajax({
type: 'GET',
url: twjs+'php/info_div.php',
data: "type="+type+"&bi="+bi+"&query="+jsonparams+"&dbs="+dbsPaths+"&gexf="+thisgexf,
//contentType: "application/json",
//dataType: 'json',
success : function(data){
pr(twjs+'php/info_div.php?'+"type="+type+"&bi="+bi+"&query="+jsonparams+"&dbs="+dbsPaths+"&gexf="+thisgexf);
$("#topPapers").html(data);
},
error: function(){
pr('Page Not found: updateLeftPanel_uni()');
}
});
}
}
//FOR UNI-PARTITE
function selectionUni(currentNode){
pr("in selectionUni");
if(checkBox==false && cursor_size==0) {
highlightSelectedNodes(false);
opossites = [];
selections = [];
partialGraph.refresh();
}
if((typeof selections[currentNode.id])=="undefined"){
selections[currentNode.id] = 1;
currentNode.active=true;
}
else {
delete selections[currentNode.id];
currentNode.active=false;
}
//highlightOpossites(nodes1[currentNode.id].neighbours);
// currentNode.color = currentNode.attr['true_color'];
// currentNode.attr['grey'] = 0;
//
//
partialGraph.zoomTo(partialGraph._core.width / 2, partialGraph._core.height / 2, 0.8);
partialGraph.refresh();
}
//JUST ADEME
function camaraButton(){
$("#PhotoGraph").click(function (){
//canvas=partialGraph._core.domElements.nodes;
var nodesCtx = partialGraph._core.domElements.nodes;
/*
var edgesCtx = document.getElementById("sigma_edges_1").getContext('2d');
var edgesImg = edgesCtx.getImageData(0, 0, document.getElementById("sigma_edges_1").width, document.getElementById("sigma_edges_1").height)
nodesCtx.putImageData(edgesImg,0,0);
//ctx.drawImage(partialGraph._core.domElements.edges,0,0)
//var oCanvas = ctx;
*/
//div = document.getElementById("sigma_nodes_1").getContext('2d');
//ctx = div.getContext("2d");
//oCanvas.drawImage(partialGraph._core.domElements.edges,0,0);
Canvas2Image.saveAsPNG(nodesCtx);
/*
Canvas2Image.saveAsJPEG(oCanvas); // will prompt the user to save the image as JPEG.
// Only supported by Firefox.
Canvas2Image.saveAsBMP(oCanvas); // will prompt the user to save the image as BMP.
// returns an <img> element containing the converted PNG image
var oImgPNG = Canvas2Image.saveAsPNG(oCanvas, true);
// returns an <img> element containing the converted JPEG image (Only supported by Firefox)
var oImgJPEG = Canvas2Image.saveAsJPEG(oCanvas, true);
// returns an <img> element containing the converted BMP image
var oImgBMP = Canvas2Image.saveAsBMP(oCanvas, true);
// all the functions also takes width and height arguments.
// These can be used to scale the resulting image:
// saves a PNG image scaled to 100x100
Canvas2Image.saveAsPNG(oCanvas, false, 100, 100);
*/
});
}
//JUST ADEME
function getChatFrame() {
content = '<div id="showChat" onclick="showhideChat();"><a href="#" id="aShowChat"> </a></div>';
content += '<iframe src="'+ircUrl+'"'
content += 'width="400" height="300"></iframe>';
$("#rightcolumn").html(content);
}
//JUST ADEME
function showhideChat(){
cg = document.getElementById("rightcolumn");
if(cg){
if(cg.style.right=="-400px"){
cg.style.right="0px";
}
else cg.style.right="-400px";
}
}
function getTips(){
text =
"<br>"+
"Basic Interactions:"+
"<ul>"+
"<li>Click on a node to select/unselect and get its information. In case of multiple selection, the button unselect clears all selections.</li>"+
"<li>The switch button switch allows to change the view type.</li>"+
"</ul>"+
"<br>"+
"Graph manipulation:"+
"<ul>"+
"<li>Link and node sizes indicate their strength.</li>"+
"<li>To fold/unfold the graph (keep only strong links or weak links), use the 'edges filter' sliders.</li>"+
"<li>To select a more of less specific area of the graph, use the 'nodes filter' slider.</li>"+
"</ul>"+
"<br>"+
"Micro/Macro view:"+
"<ul>"+
"<li>To explore the neighborhood of a selection, either double click on the selected nodes, either click on the macro/meso level button. Zoom out in meso view return to macro view.</li>"+
"<li>Click on the 'all nodes' tab below to view the full clickable list of nodes.</li>"+
"</ul>";
$("#tab-container").hide();
return text;
}
//both obsolete
function closeDialog () {
$('#windowTitleDialog').modal('hide');
}
function okClicked () {
//document.title = document.getElementById ("xlInput").value;
closeDialog ();
}
function pr(msg) {
console.log(msg);
}
//to general utils
function getClientTime(){
var totalSec = new Date().getTime() / 1000;
var d = new Date();
var hours = d.getHours();
var minutes = parseInt( totalSec / 60 ) % 60;
var seconds = (totalSec % 60).toFixed(4);
var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
return result;
}
function compareNumbers(a, b) {
return a - b;
}
//python range(a,b) | range(a)
function calc_range(begin, end) {
if (typeof end === "undefined") {
end = begin; begin = 0;
}
var result = [], modifier = end > begin ? 1 : -1;
for ( var i = 0; i <= Math.abs(end - begin); i++ ) {
result.push(begin + i * modifier);
}
return result;
}
//to general utils (not used btw)
function cloneObject(source) {
for (i in source) {
if (typeof source[i] == 'source') {
this[i] = new cloneObject(source[i]);
}
else{
this[i] = source[i];
}
}
}
function isUndef(variable){
if(typeof(variable)==="undefined") return true;
else return false;
}
$.fn.toggleClick = function(){
methods = arguments, // store the passed arguments for future reference
count = methods.length; // cache the number of methods
//use return this to maintain jQuery chainability
return this.each(function(i, item){
// for each element you bind to
index = 0; // create a local counter for that element
$(item).click(function(){ // bind a click handler to that element
return methods[index++ % count].apply(this,arguments); // that when called will apply the 'index'th method to that element
// the index % count means that we constrain our iterator between 0 and (count-1)
});
});
};
ourGetUrlParam = (function () {
var get = {
push:function (key,value){
var cur = this[key];
if (cur.isArray){
this[key].push(value);
}else {
this[key] = [];
this[key].push(cur);
this[key].push(value);
}
}
},
decode = function (s, rmSpaceFlag) {
s = decodeURIComponent(s.replace(/\+/g, ' '));
return rmSpaceFlag ? s.replace(/\s+/g,'') : s;
};
document.location.search.replace(
/\??(?:([^=]+)=(?:%22(.*?)%22|"([^"]*)"|([^&]*))&?)/g,
// ^^^^^^^ ^^^^^ | ^^^^^^^ |^^^^^^^
// key valUrlquoted|valQuoted|valRaw
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// wholeMatch
function (wholeMatch,key,valUrlquoted,valQuoted,valRaw) {
// exemple
// -------
// wholeMatch: ?type=%22filter%22&
// key: type
// valUrlquoted: filter
// debug
// -----
// console.log("getUrlParam re vars wholeMatch :", wholeMatch)
// console.log("getUrlParam re vars key :", key)
// console.log("getUrlParam re vars valUrlquoted:", valUrlquoted)
// console.log("getUrlParam re vars valQuoted :", valQuoted)
// console.log("getUrlParam re vars valRaw :", valRaw)
var val = ""
if (typeof valUrlquoted != "undefined") {
val = valUrlquoted
}
else if (typeof valQuoted != "undefined") {
val = valQuoted
}
else {
val = valRaw
}
if (get[decode(key,true)]){
get.push(decode(key,true),decode(val));
}else {
get[decode(key,true)] = decode(val);
}
// debug
// -----
// console.log("getUrlParam output dict:\n ", JSON.stringify(get))
});
return get;
})();
function ArraySortByValue(array, sortFunc){
var tmp = [];
oposMAX=0;
for (var k in array) {
if (array.hasOwnProperty(k)) {
tmp.push({
key: k,
value: array[k]
});
if((array[k]) > oposMAX) oposMAX= array[k];
}
}
tmp.sort(function(o1, o2) {
return sortFunc(o1.value, o2.value);
});
return tmp;
}
function ArraySortByKey(array, sortFunc){
var tmp = [];
for (var k in array) {
if (array.hasOwnProperty(k)) {
tmp.push({
key: k,
value: array[k]
});
}
}
tmp.sort(function(o1, o2) {
return sortFunc(o1.key, o2.key);
});
return tmp;
}
function is_empty(obj) {
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length && obj.length > 0) return false;
if (obj.length && obj.length === 0) return true;
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
function getByID(elem) {
return document.getElementById(elem);
}
function hex2rga(sent_hex) {
result = []
hex = ( sent_hex.charAt(0) === "#" ? sent_hex.substr(1) : sent_hex );
// check if 6 letters are provided
if (hex.length === 6) {
result = calculateFull(hex);
return result;
}
else if (hex.length === 3) {
result = calculatePartial(hex);
return result;
}
}
function calculateFull(hex) {
var r = parseInt(hex.substring(0, 2), 16);
var g = parseInt(hex.substring(2, 4), 16);
var b = parseInt(hex.substring(4, 6), 16);
return [r,g,b];
}
// function for calculating 3 letters hex value
function calculatePartial(hex) {
var r = parseInt(hex.substring(0, 1) + hex.substring(0, 1), 16);
var g = parseInt(hex.substring(1, 2) + hex.substring(1, 2), 16);
var b = parseInt(hex.substring(2, 3) + hex.substring(2, 3), 16);
return [r,g,b];
}
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
// === monitor windows resize === //
var counterrrr=0;
$( window ).resize(function() {
counterrrr++;
$("#log").html("redimension nro: "+counterrrr);
sigmaLimits();
});// === / monitor windows resize === //
mainfile = (isUndef(ourGetUrlParam.file))?false:true;
// === [what to do at start] === //
if (mainfile) {
if(!isUndef(ourGetUrlParam.file)){
$.doTimeout(30,function (){
var filename = ourGetUrlParam.file;
if( filename.indexOf(".json") > -1 ) {
bringTheNoise( filename , "mono");
} else {
listGexfs();
parse(filename);
nb_cats = scanCategories();
pr("nb_cats: "+nb_cats);
graphtype=(nb_cats==1)?"mono":"bi";
bringTheNoise(filename,graphtype);
$.doTimeout(30,function (){
var filename = ourGetUrlParam.file
if(!isUndef(gexfDict[filename])){
$("#currentGraph").html(gexfDict[filename.file]);
} else $("#currentGraph").html(filename);
scanDataFolder();
listGexfs();
});
}
});
} else {
window.location.href=window.location.origin+window.location.pathname+"?file="+mainfile;
}
} //url-mode
else {
var param = ourGetUrlParam.nodeidparam
var qtype = ourGetUrlParam.type
if(isUndef(param) || isUndef(qtype)) {
console.warn("missing nodes filter/id param");
}
else {
console.log("Received query of type:", qtype)
if(qtype == "filter" || qtype == "unique_id"){
bringTheNoise(param,qtype);
}
else {
console.warn ("=> unsupported query type !")
}
}
}// === [ / what to do at start ] === //
//just CSS
function sigmaLimits(){
pr("\t*** sigmaLimits()")
pw=$('#sigma-example').width();
ph=$('#sigma-example').height();
pr("\t\tprevsigma:("+pw+","+ph+")");
sidebar=$('#leftcolumn').width();
anchototal=$('#fixedtop').width();
altototal=$('#leftcolumn').height();
altofixtop=$('#fixedtop').height()
altodeftop=$('#defaultop').height()
$('#sigma-example').width(anchototal-sidebar);
$('#sigma-example').height(altototal-altofixtop-altodeftop-4);
pw=$('#sigma-example').width();
ph=$('#sigma-example').height();
pr("\t\tnowsigma:("+pw+","+ph+")");
}
function bringTheNoise(sourceinfo,type){
$("#semLoader").hide();
// $('.selectpicker').selectpicker();
// === get width and height === //
sigmaLimits();
// === sigma canvas resize with previous values === //
partialGraph = sigma.init(document.getElementById('sigma-example'))
.drawingProperties(sigmaJsDrawingProperties)
.graphProperties(sigmaJsGraphProperties)
.mouseProperties(sigmaJsMouseProperties);
//dummy graph (semantic layouting in background)
otherGraph = sigma.init(document.getElementById('sigma-othergraph'));
// === resize topbar and tweakbar === //
var body=document.getElementsByTagName('body')[0];
body.style.paddingTop="41px";
$('.etabs').click(function(){
$.doTimeout(500,function (){
$("#opossiteNodes").readmore({maxHeight:200});
$("#sameNodes").readmore({maxHeight:200});
});
});
$("#changetype").click(function(){
pr("")
pr(" ############ changeTYPE click");
printStates()
changeType();
$.doTimeout(500,function (){
$('.etabs a[href="#tabs1"]').trigger('click');
});
printStates()
pr(" ############ / changeTYPE click");
pr("")
});
$("#changelevel").click(function(){
pr("")
pr(" ############ changeLEVEL click");
printStates()
changeLevel();
// $("#tabs1").click()
printStates()
pr(" ############ / changeLEVEL click");
pr("")
});
// === un/hide leftpanel === //
$("#aUnfold").click(function(e) {
//SHOW leftcolumn
sidebar = $("#leftcolumn");
fullwidth=$('#fixedtop').width();
e.preventDefault();
// $("#wrapper").toggleClass("active");
if(parseFloat(sidebar.css("right"))<0){
$("#aUnfold").attr("class","rightarrow");
sidebar.animate({
"right" : sidebar.width()+"px"
}, { duration: 400, queue: false });
$("#ctlzoom").animate({
"right": (sidebar.width()+10)+"px"
}, { duration: 400, queue: false });
// $('#sigma-example').width(fullwidth-sidebar.width());
$('#sigma-example').animate({
"width": fullwidth-sidebar.width()+"px"
}, { duration: 400, queue: false });
setTimeout(function() {
partialGraph.resize();
partialGraph.refresh();
}, 400);
}
else {
//HIDE leftcolumn
$("#aUnfold").attr("class","leftarrow");
sidebar.animate({
"right" : "-" + sidebar.width() + "px"
}, { duration: 400, queue: false });
$("#ctlzoom").animate({
"right": "0px"
}, { duration: 400, queue: false });
// $('#sigma-example').width(fullwidth);
$('#sigma-example').animate({
"width": fullwidth+"px"
},{ duration: 400, queue: false });
setTimeout(function() {
partialGraph.resize();
partialGraph.refresh();
}, 400);
}
});
// $("#statsicon").click(function(){
// $('#statsmodal').modal('show');
// });
// === start minimap library... currently off === //
startMiniMap();
console.log("parsing...");
// < === EXTRACTING DATA === >
if(mainfile) {
pr("mainfile: "+mainfile)
var pathfile = sourceinfo
if(gexfDict[pathfile]) $("#network").html(gexfDict[pathfile]);
else $("#network").html(pathfile);
// $('#modalloader').modal('show');
parse(decodeURIComponent(pathfile));
if(type=="mono") {
$("#changetype").hide();
if( pathfile.indexOf(".json") > -1 ) {
JSONFile( pathfile )
} else {
onepartiteExtract();
}
pushSWClick("social");
$("#taboppos").remove();
$.doTimeout(500,function (){
$('.etabs a[href="#tabs2"]').trigger('click');
});
pr(partialGraph._core.graph.nodes.length)
pr(partialGraph._core.graph.edges.length)
}
if(type=="bi") {
semanticConverged=true;
pr("here in fullextract")
fullExtract();
pushSWClick("social");
pr(partialGraph._core.graph.nodes.length)
pr(partialGraph._core.graph.edges.length)
}
partialGraph.zoomTo(partialGraph._core.width / 2, partialGraph._core.height / 2, 0.8).draw(2,2,2);
theListeners();
$("#closeloader").click();
} else {
var theurl,thedata,thename;
$('#modalloader').modal('show');
// console.warn("===> PASSING ON QUERY (type "+type+") TO BRIDGE <===")
if(type=="uid") {
// pr("bring the noise, case: unique_id");
// pr(getClientTime()+" : DataExt Ini");
// < === DATA EXTRACTION === >
theurl = bridge["forNormalQuery"]
thedata = "qtype=uid&unique_id="+sourceinfo+"&it="+iterationsFA2;
thename = "unique scholar";
}
if (type=="filter") {
// pr("bring the noise, case: multipleQuery");
// pr(getClientTime()+" : DataExt Ini");
theurl = bridge["forFilteredQuery"];
// json is twice URI encoded by whoswho to avoid both '"' and '%22'
var json_constraints = decodeURIComponent(sourceinfo)
console.log("multipleQuery RECEIVED", json_constraints)
// safe parsing of the URL's untrusted JSON
var filteringKeyArrayPairs = JSON.parse( json_constraints)
// INPUT json: <= { keywords: ['complex systems', 'something'],
// countries: ['France', 'USA'], laboratories: []}
// we build 2 OUTPUT strings:
// => thedata (for comexAPI):
// keywords[]="complex systems"&keywords[]="something"&countries="France"&countries[]="USA"
// => thename (for user display):
// ("complex systems" or "something") and ("France" or "USA")
// console.log("decoded filtering query", filteringKeyArrayPairs)
var restParams = []
var nameElts = []
// build REST parameters from filtering arrays
// and name from each filter value
for (var fieldName in filteringKeyArrayPairs) {
var nameSubElts = []
for (var value of filteringKeyArrayPairs[fieldName]) {
// exemple: "countries[]=France"
restParams.push(fieldName+"[]="+value)
nameSubElts.push ('"'+value+'"')
}
nameElts.push("("+nameSubElts.join(" or ")+")")
}
if (restParams.length) {
thedata = "qtype=filters&" + restParams.join("&")
thename = nameElts.join(" and ")
}
else {
thedata = "qtype=filters&query=*"
thename = "(ENTIRE NETWORK)"
}
}
// Assigning name for the network
if (! thename) {
elements = []
queryarray = JSON.parse(ourGetUrlParam.nodeidparam)
for(var i in queryarray) {
item = queryarray[i]
if(Array.isArray(item) && item.length>0) {
for(var j in item) elements.push(item[j])
}
}
thename = '"'+elements.join('" , "')+'"';
}
SigmaLayouting( theurl , thedata , thename );
}
}
function theListeners(){
pr("in THELISTENERS");
// leftPanel("close");
$("#closeloader").click();//modal.hide doesnt work :c
cancelSelection(false);
$("#tips").html(getTips());
//$('#sigma-example').css('background-color','white');
$("#category-B").hide();
$("#labelchange").hide();
$("#availableView").hide();
showMeSomeLabels(6);
initializeMap();
updateMap();
updateDownNodeEvent(false);
partialGraph.zoomTo(partialGraph._core.width / 2, partialGraph._core.height / 2, 0.8).draw(2,2,2);
$("#saveAs").click(function() {
$('#savemodal').modal('show');
});
/******************* /SEARCH ***********************/
$.ui.autocomplete.prototype._renderItem = function(ul, item) {
var searchVal = $("#searchinput").val();
var desc = extractContext(item.desc, searchVal);
// pr("desc:")
// pr(desc)
return $('<li onclick=\'var s = "'+item.label+'"; search(s);$("#searchinput").val(strSearchBar);\'></li>')
.data('item.autocomplete', item)
.append("<a><span class=\"labelresult\">" + item.label + "</span></a>" )
.appendTo(ul);
};
$('input#searchinput').autocomplete({
source: function(request, response) {
matches = [];
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
var results = $.grep(labels, function(e) {
return matcher.test(e.label); //|| matcher.test(e.desc);
});
if (!results.length) {
$("#noresults").text("Pas de résultats");
} else {
$("#noresults").empty();
}
matches = results.slice(0, maxSearchResults);
response(matches);
},
minLength: minLengthAutoComplete
});
$('#searchinput').bind('autocompleteopen', function(event, ui) {
$(this).data('is_open',true);
});
$('#searchinput').bind('autocompleteclose', function(event, ui) {
$(this).data('is_open',false);
});
$("#searchinput").focus(function () {
if ($(this).val() == strSearchBar) {
$(this).val('');
}
});
$("#searchinput").blur(function () {
if ($(this).val() == '') {
$(this).val(strSearchBar);
}
});
// i've a list of coincidences and i press enter like a boss
$("#searchinput").keydown(function (e) {
if (e.keyCode == 13 && $("input#searchinput").data('is_open') === true) {
// Search has several results and you pressed ENTER
if(!is_empty(matches)) {
var coincidences = []
for(j=0;j<matches.length;j++){
coincidences.push(matches[j].id)
}
$.doTimeout(30,function (){
MultipleSelection(coincidences , true);//true-> apply deselection algorithm
$("input#searchinput").val("");
$("input#searchinput").autocomplete( "close" );
});
//$("input#searchinput").trigger('autocompleteclose');
}
}
});
$("#searchinput").keyup(function (e) {
if (e.keyCode == 13 && $("input#searchinput").data('is_open') !== true) {
pr("search KEY UP");
var exfnd = exactfind( $("#searchinput").val() )
$.doTimeout(30,function (){
MultipleSelection(exfnd.id , true);//true-> apply deselection algorithm
$("input#searchinput").val("");
$("input#searchinput").autocomplete( "close" );
});
}
});
$("#searchsubmit").click(function () {
pr("searchsubmit CLICK");
var s = $("#searchinput").val();
search(s);
$("#searchinput").val("");
});
/******************* /SEARCH ***********************/
// button CENTER
$("#lensButton").click(function () {
partialGraph.position(0,0,1);
partialGraph.zoomTo(partialGraph._core.width / 2, partialGraph._core.height / 2, 0.8);
partialGraph.refresh();
// partialGraph.startForceAtlas2();
});
$('#sigma-example').dblclick(function(event) {
pr("in the double click event");
var targeted = [];
if(cursor_size>0) {
//Multiple selection
x1 = partialGraph._core.mousecaptor.mouseX;
y1 = partialGraph._core.mousecaptor.mouseY;
var counter=0;
var actualSel=[];
partialGraph.iterNodes(function(n){
if(!n.hidden){
distance = Math.sqrt(
Math.pow((x1-parseInt(n.displayX)),2) +
Math.pow((y1-parseInt(n.displayY)),2)
);
if(parseInt(distance)<=cursor_size) {
counter++;
actualSel.push(n.id);
}
}
});
targeted = actualSel;
} else {
targeted = partialGraph._core.graph.nodes.filter(function(n) {
return !!n['hover'];
}).map(function(n) {
return n.id;
});
}
if(!is_empty(targeted)) {
graphTagCloudElem(targeted);
} else {
if(!is_empty(selections)){
cancelSelection(false);
}
}
});
// minimap stuff
// $("#overview")
// .mousemove(onOverviewMove)
// .mousedown(startMove)
// .mouseup(endMove)
// .mouseout(endMove)
// .mousewheel(onGraphScroll);
$("#sigma-example")
.mousemove(function(){
if(!isUndef(partialGraph)) {
if(cursor_size>0) trackMouse();
}
})
.contextmenu(function(){
return false;
})
.mousewheel(onGraphScroll)
.mousedown(function(e){
//left click!<- normal click
if(e.which==1){
var targeted = partialGraph._core.graph.nodes.filter(function(n) {
return !!n['hover'];
}).map(function(n) {
return n.id;
});
partialGraph.dispatch(
e['type'] == 'mousedown' ?
'downgraph' :
'upgraph'
);
if(cursor_size>0) {
//Multiple selection
x1 = partialGraph._core.mousecaptor.mouseX;
y1 = partialGraph._core.mousecaptor.mouseY;
var counter=0;
var actualSel=[];
partialGraph.iterNodes(function(n){
if(!n.hidden){
distance = Math.sqrt(
Math.pow((x1-parseInt(n.displayX)),2) +
Math.pow((y1-parseInt(n.displayY)),2)
);
if(parseInt(distance)<=cursor_size) {
counter++;
actualSel.push(n.id);
}
}
});
if(checkBox) {
var dummyarray = {};
for(var i in actualSel) dummyarray[ actualSel[i] ]=1;
for(var i in selections) dummyarray[ i ]=1;
var countTypes = {};
for(var i in dummyarray) {
if( isUndef(countTypes[Nodes[i].type]) )
countTypes[Nodes[i].type]=1;
else
countTypes[Nodes[i].type]++;
}
cancelSelection(false);
cpCountTypes = Object.keys(countTypes);
if(cpCountTypes.length==1)
MultipleSelection(Object.keys(dummyarray) , true);//true-> apply deselection algorithm
else
MultipleSelection(actualSel , true);//true-> apply deselection algorithm
} else MultipleSelection(actualSel , true);//true-> apply deselection algorithm
// //The most brilliant way of knowing if an array is empty in the world of JavaScript
i=0; for(var s in actualSel) { i++; break;}
if(is_empty(actualSel) || i==0){
pr("cursor radius ON, mouseDown -> selecciones vacias");
cancelSelection(false);
//$("#names").html("");
//$("#opossiteNodes").html("");
//$("#information").html("");
//$("#topPapers").html("");
//$("#tips").html(getTips());
//changeButton("unselectNodes");
//if(counter>0) graphResetColor();
}
} else {
//Unique Selection
partialGraph.dispatch(
e['type'] == 'mousedown' ? 'downnodes' : 'upnodes',
targeted
);
}
partialGraph.draw();
trackMouse();
}
});
$("#zoomSlider").slider({
orientation: "vertical",
value: partialGraph.position().ratio,
min: sigmaJsMouseProperties.minRatio,
max: sigmaJsMouseProperties.maxRatio,
range: "min",
step: 0.1,
slide: function( event, ui ) {
// pr("*******lalala***********")
// pr(partialGraph.position().ratio)
// pr(sigmaJsMouseProperties.minRatio)
// pr(sigmaJsMouseProperties.maxRatio)
partialGraph.zoomTo(
partialGraph._core.width / 2,
partialGraph._core.height / 2,
ui.value);
}
});
$("#zoomPlusButton").click(function () {
partialGraph.zoomTo(partialGraph._core.width / 2, partialGraph._core.height / 2, partialGraph._core.mousecaptor.ratio * 1.5);
$("#zoomSlider").slider("value",partialGraph.position().ratio);
return false;
});
$("#zoomMinusButton").click(function () {
partialGraph.zoomTo(partialGraph._core.width / 2, partialGraph._core.height / 2, partialGraph._core.mousecaptor.ratio * 0.5);
$("#zoomSlider").slider("value",partialGraph.position().ratio);
return false;
});
$("#edgesButton").click(function () {
fa2enabled=true;
if(!isUndef(partialGraph.forceatlas2)) {
if(partialGraph.forceatlas2.active) {
partialGraph.stopForceAtlas2();
partialGraph.draw();
return;
} else {
partialGraph.startForceAtlas2();
return;
}
} else {
partialGraph.startForceAtlas2();
return;
}
});
// finished but not used
// NodeWeightFilter ( "#sliderANodeWeight" , "Document" , "type" , "size")
$("#sliderANodeWeight").freshslider({
range: true,
step:1,
value:[10, 60],
enabled: false,
onchange:function(low, high){
console.log(low, high);
}
});
// finished
//this should be available at start!!
// pr("applying edge weith filter")
EdgeWeightFilter("#sliderAEdgeWeight", "label" , "nodes1", "weight");
//finished
NodeSizeSlider("#sliderANodeSize","Document", 10, "#27c470")
//finished TODO check if doing it is useful at init
NodeSizeSlider("#sliderBNodeSize","NGram", 1, "#FFA500")
// NodeWeightFilter ( "#sliderBNodeWeight" , "NGram" , "type" , "size")
// EdgeWeightFilter("#sliderBEdgeWeight", "label" , "nodes2", "weight");
//finished
$("#unranged-value").freshslider({
step: 1,
min:cursor_size_min,
max:cursor_size_max,
value:cursor_size,
onchange:function(value){
// console.log("en cursorsize: "+value);
cursor_size=value;
if(cursor_size==0) partialGraph.draw();
}
});
$.doTimeout(5,function (){
fa2enabled=true; partialGraph.startForceAtlas2();
$.doTimeout(5,function (){
partialGraph.stopForceAtlas2();
});
});
}
// extractFromJson()
// Social Spatialization
// Semantic Spatialization
function SigmaLayouting( URL, DATA, NAME) {
console.log("_ /"+URL+"?"+DATA)
return $.ajax({
type: 'GET',
url: "/"+URL,
data: DATA,
contentType: "application/json",
dataType: 'json',
async: true,
success : function(data) {
pr(data)
if(!isUndef(ourGetUrlParam.seed))seed=ourGetUrlParam.seed;
extractFromJson(data,seed);
// changeToMacro("social");
pr(getClientTime()+" : DataExt Fin");
// < === DATA EXTRACTED!! === >
if(fa2enabled==="off") $("#edgesButton").hide();
pushSWClick("social");
pr(partialGraph._core.graph.nodes.length)
pr(partialGraph._core.graph.edges.length)
nbnodes = partialGraph._core.graph.nodes.length
if(nbnodes>=400 && nbnodes<1000) {
snbnodes = nbnodes+"";
cut1 = snbnodes[0];
cut2 = snbnodes.length;
pr("cut1: "+cut1)
pr("cut2: "+cut2)
iterationsFA2 = Math.round(iterationsFA2/(cut1/cut2))
}
if(nbnodes>=1000) iterationsFA2 = 150;
pr("iterationsFA2: "+iterationsFA2)
$("#network").html(NAME);
// < === ASYNCHRONOUS FA2.JS === >
pr(getClientTime()+" : Ini FA2");
var ForceAtlas2 = new Worker("tinawebJS/asyncFA2.js");
ForceAtlas2.postMessage({
"nodes": partialGraph._core.graph.nodes,
"edges": partialGraph._core.graph.edges,
"it":iterationsFA2
});
ForceAtlas2.addEventListener('message', function(e) {
iterations=e.data.it;
nds=e.data.nodes;
for(var n in nds){
id=nds[n].id;
x=nds[n].x
y=nds[n].y
partialGraph._core.graph.nodes[n].x=x;
partialGraph._core.graph.nodes[n].y=y;
partialGraph._core.graph.nodesIndex[id].x=x
partialGraph._core.graph.nodesIndex[id].y=y
Nodes[id].x=x;
Nodes[id].y=y;
}
pr("\ttotalIterations: "+iterations)
pr(getClientTime()+" : Fin FA2");
console.log("Parsing and FA2 complete.");
pr("\n=================\n")
// < === ASYNCHRONOUS FA2.JS DONE!! === >
// [ calculate iterations for semanticgraph ]
pr(getClientTime()+" : Ini FA2 for SemanticGraph");
var cut1_,cut2_,iterationsFA2_=iterationsFA2;
pr(otherGraph._core.graph.nodes.length)
pr(otherGraph._core.graph.edges.length)
nbnodes = otherGraph._core.graph.nodes.length
if(nbnodes>=400 && nbnodes<1000) {
snbnodes = nbnodes+"";
cut1_ = snbnodes[0];
cut2_ = snbnodes.length;
pr("cut1 sem: "+cut1_)
pr("cut2 sem: "+cut2_)
iterationsFA2_ = Math.round(iterationsFA2/(cut1_/cut2_))
}
if(nbnodes>=1000) iterationsFA2_ = 150;
pr("iterationsFA2 sem: "+iterationsFA2_)
// [ / calculate iterations for semanticgraph ]
// [ semantic layouting ]
var ForceAtlas2_ = new Worker("tinawebJS/asyncFA2.js");
ForceAtlas2_.postMessage({
"nodes": otherGraph._core.graph.nodes,
"edges": otherGraph._core.graph.edges,
"it":iterationsFA2_
});
ForceAtlas2_.addEventListener('message', function(e) {
iterations=e.data.it;
nds=e.data.nodes;
for(var n in nds){
id=nds[n].id;
x=nds[n].x
y=nds[n].y
Nodes[id].x=x;
Nodes[id].y=y;
}
pr("\ttotalIterations: "+iterations)
pr(getClientTime()+" : Fin FA2 for SemanticGraph");
otherGraph.emptyGraph();
otherGraph = null;
$("#sigma-othergraph").html("");
semanticConverged = true;
$("#semLoader").hide();
if( NOW=="B" ) {
changeToMacro("semantic");
partialGraph.draw();
// $("#sliderBEdgeWeight").html("");
// $("#sliderBNodeWeight").html("");
$("#category-B").show();
EdgeWeightFilter("#sliderBEdgeWeight", "label" , "nodes2", "weight");
NodeWeightFilter ( "#sliderBNodeWeight" , "type" , "NGram" , "size");
$("#colorGraph").hide();
}
console.log("Parsing and FA2 complete for SemanticGraph.");
});
// [ / semantic layouting ]
theListeners();
});
},
error: function(){
console.log("in the main.js")
console.log(URL)
pr("Page Not found. parseCustom, inside the IF");
}
});
}
function cancelSelection (fromTagCloud) {
pr("\t***in cancelSelection");
highlightSelectedNodes(false); //Unselect the selected ones :D
opossites = [];
selections = [];
//selections.length = 0;
selections.splice(0, selections.length);
partialGraph.refresh();
//Nodes colors go back to normal
overNodes=false;
e = partialGraph._core.graph.edges;
for(i=0;i<e.length;i++){
e[i].color = e[i].attr['grey'] ? e[i].attr['true_color'] : e[i].color;
e[i].attr['grey'] = 0;
}
partialGraph.draw(2,1,2);
partialGraph.iterNodes(function(n){
n.active=false;
n.color = n.attr['grey'] ? n.attr['true_color'] : n.color;
n.attr['grey'] = 0;
}).draw(2,1,2);
//Nodes colors go back to normal
if(fromTagCloud==false){
$("#names").html("");
$("#topPapers").html(""); $("#topPapers").hide();
$("#opossiteNodes").html(""); $("#tab-container").hide();
$("#information").html("");
$("#searchinput").val("");
$("#switchbutton").hide();
$("#tips").html(getTips());
}
for(var i in deselections){
if( !isUndef(partialGraph._core.graph.nodesIndex[i]) ) {
partialGraph._core.graph.nodesIndex[i].forceLabel=false;
partialGraph._core.graph.nodesIndex[i].neighbour=false;
}
}
deselections={};
// leftPanel("close");
if(swMacro) LevelButtonDisable(true);
partialGraph.draw();
}
function highlightSelectedNodes(flag){
pr("\t***methods.js:highlightSelectedNodes(flag)"+flag+" selEmpty:"+is_empty(selections))
if(!is_empty(selections)){
for(var i in selections) {
if(Nodes[i].type==catSoc && swclickActual=="social"){
node = partialGraph._core.graph.nodesIndex[i];
node.active = flag;
}
else if(Nodes[i].type==catSem && swclickActual=="semantic") {
node = partialGraph._core.graph.nodesIndex[i];
node.active = flag;
}
else if(swclickActual=="sociosemantic") {
node = partialGraph._core.graph.nodesIndex[i];
node.active = flag;
}
else break;
}
}
}
function alertCheckBox(eventCheck){
if(!isUndef(eventCheck.checked)) checkBox=eventCheck.checked;
}
// States:
// A : Macro-Social
// B : Macro-Semantic
// A*: Macro-Social w/selections
// B*: Macro-Semantic w/selections
// a : Meso-Social
// b : Meso-Semantic
// AaBb: Socio-Semantic
function RefreshState(newNOW){
pr("\t\t\tin RefreshState newNOW:_"+newNOW+"_.")
if (newNOW!="") {
PAST = NOW;
NOW = newNOW;
// if(NOW=="a" || NOW=="A" || NOW=="AaBb") {
// $("#category-A").show();
// }
// if(NOW=="b" || NOW=="B" || NOW=="AaBb") {
// $("#category-B").show();
// }
}
$("#category-A").hide();
$("#category-B").hide();
// i=0; for(var s in selections) { i++; break;}
// if(is_empty(selections) || i==0) LevelButtonDisable(true);
// else LevelButtonDisable(false);
//complete graphs case
// sels=getNodeIDs(selections).length
if(NOW=="A" || NOW=="a") {
// N : number of nodes
// k : number of ( selected nodes + their neighbors )
// s : number of selections
var N=( Object.keys(Nodes).filter(function(n){return Nodes[n].type==catSoc}) ).length
var k=Object.keys(getNeighs(Object.keys(selections),nodes1)).length
var s=Object.keys(selections).length
pr("in social N: "+N+" - k: "+k+" - s: "+s)
if(NOW=="A"){
if( (s==0 || k>=(N-1)) ) {
LevelButtonDisable(true);
} else LevelButtonDisable(false);
if(s==N) LevelButtonDisable(false);
}
if(NOW=="a") {
LevelButtonDisable(false);
}
$("#semLoader").hide();
$("#category-A").show();
$("#colorGraph").show();
}
if(NOW=="B" || NOW=="b") {
var N=( Object.keys(Nodes).filter(function(n){return Nodes[n].type==catSem}) ).length
var k=Object.keys(getNeighs(Object.keys(selections),nodes2)).length
var s=Object.keys(selections).length
pr("in semantic N: "+N+" - k: "+k+" - s: "+s)
if(NOW=="B") {
if( (s==0 || k>=(N-1)) ) {
LevelButtonDisable(true);
} else LevelButtonDisable(false);
if(s==N) LevelButtonDisable(false);
}
if(NOW=="b") {
LevelButtonDisable(false);
}
if ( semanticConverged ) {
$("#semLoader").hide();
$("#category-B").show();
$.doTimeout(30,function (){
EdgeWeightFilter("#sliderBEdgeWeight", "label" , "nodes2", "weight");
NodeWeightFilter ( "#sliderBNodeWeight" , "type" , "NGram" , "size");
NodeSizeSlider("#sliderBNodeSize","NGram", 25, "#FFA500")
});
} else {
$("#semLoader").css('visibility', 'visible');
$("#semLoader").show();
}
}
if(NOW=="AaBb"){
LevelButtonDisable(true);
$("#category-A").show();
$("#category-B").show();
}
partialGraph.draw();
}
function pushSWClick(arg){
swclickPrev = swclickActual;
swclickActual = arg;
}
// it receives entire node
function selection(currentNode){
if(checkBox==false && cursor_size==0) {
highlightSelectedNodes(false);
opossites = [];
selections = [];
partialGraph.refresh();
}
if(socsemFlag==false){
if(isUndef(selections[currentNode.id])){
selections[currentNode.id] = 1;
if(Nodes[currentNode.id].type==catSoc && !isUndef(bipartiteD2N[currentNode.id])){
for(i=0;i<bipartiteD2N[currentNode.id].neighbours.length;i++) {
if(isUndef(opossites[bipartiteD2N[currentNode.id].neighbours[i]])){
opossites[bipartiteD2N[currentNode.id].neighbours[i]]=1;
}
else {
opossites[bipartiteD2N[currentNode.id].neighbours[i]]++;
}
}
}
if(Nodes[currentNode.id].type==catSem){
if(!isUndef(bipartiteN2D[currentNode.id])){
for(i=0;i<bipartiteN2D[currentNode.id].neighbours.length;i++) {
if(isUndef(opossites[bipartiteN2D[currentNode.id].neighbours[i]])){
opossites[bipartiteN2D[currentNode.id].neighbours[i]]=1;
}
else opossites[bipartiteN2D[currentNode.id].neighbours[i]]++;
}
}
}
currentNode.active=true;
}
else {
delete selections[currentNode.id];
markAsSelected(currentNode.id,false);
if(Nodes[currentNode.id].type==catSoc){
for(i=0;i<bipartiteD2N[currentNode.id].neighbours.length;i++) {
if(isUndef(opossites[bipartiteD2N[currentNode.id].neighbours[i]])) {
console.log("lala");
}
if(opossites[bipartiteD2N[currentNode.id].neighbours[i]]==1){
delete opossites[bipartiteD2N[currentNode.id].neighbours[i]];
}
if(opossites[bipartiteD2N[currentNode.id].neighbours[i]]>1){
opossites[bipartiteD2N[currentNode.id].neighbours[i]]--;
}
}
}
if(Nodes[currentNode.id].type==catSem){
for(i=0;i<bipartiteN2D[currentNode.id].neighbours.length;i++) {
if(isUndef(opossites[bipartiteN2D[currentNode.id].neighbours[i]])) {
console.log("lala");
}
if(opossites[bipartiteN2D[currentNode.id].neighbours[i]]==1){
delete opossites[bipartiteN2D[currentNode.id].neighbours[i]];
}
if(opossites[bipartiteN2D[currentNode.id].neighbours[i]]>1){
opossites[bipartiteN2D[currentNode.id].neighbours[i]]--;
}
}
}
currentNode.active=false;
}
}
/* ============================================================================================== */
else {
if(isUndef(selections[currentNode.id])){
selections[currentNode.id] = 1;
if(Nodes[currentNode.id].type==catSoc){
for(i=0;i<bipartiteD2N[currentNode.id].neighbours.length;i++) {
//opossitesbipartiteD2N[currentNode.id].neighbours[i]];
if(isUndef(opossites[bipartiteD2N[currentNode.id].neighbours[i].toString()])){
opossites[bipartiteD2N[currentNode.id].neighbours[i]]=1;
}
else {
opossites[bipartiteD2N[currentNode.id].neighbours[i]]++;
}
}
}
if(Nodes[currentNode.id].type==catSem){
for(i=0;i<nodes2[currentNode.id].neighbours.length;i++) {
if(isUndef(opossites[nodes2[currentNode.id].neighbours[i]])){
opossites[nodes2[currentNode.id].neighbours[i]]=1;
}
else opossites[nodes2[currentNode.id].neighbours[i]]++;
}
}
currentNode.active=true;
}
else {
delete selections[currentNode.id];
markAsSelected(currentNode.id,false);
if(Nodes[currentNode.id].type==catSoc){
for(i=0;i<bipartiteD2N[currentNode.id].neighbours.length;i++) {
if(isUndef(opossites[bipartiteD2N[currentNode.id].neighbours[i]])) {
console.log("lala");
}
if(opossites[bipartiteD2N[currentNode.id].neighbours[i]]==1){
delete opossites[bipartiteD2N[currentNode.id].neighbours[i]];
}
if(opossites[bipartiteD2N[currentNode.id].neighbours[i]]>1){
opossites[bipartiteD2N[currentNode.id].neighbours[i]]--;
}
}
}
if(Nodes[currentNode.id].type==catSem){
for(i=0;i<nodes2[currentNode.id].neighbours.length;i++) {
if(isUndef(opossites[nodes2[currentNode.id].neighbours[i]])) {
console.log("lala");
}
if(opossites[nodes2[currentNode.id].neighbours[i]]==1){
delete opossites[nodes2[currentNode.id].neighbours[i]];
}
if(opossites[nodes2[currentNode.id].neighbours[i]]>1){
opossites[nodes2[currentNode.id].neighbours[i]]--;
}
}
}
currentNode.active=false;
}
}
// partialGraph.zoomTo(partialGraph._core.width / 2, partialGraph._core.height / 2, 0.8);
partialGraph.refresh();
}
function getOpossitesNodes(node_id, entireNode) {
node="";
if(entireNode==true) node=node_id;
else node = partialGraph._core.graph.nodesIndex[node_id];
if(socsemFlag==true) {
pr("wtf is this -> if(socsemFlag==true) {");
cancelSelection(false);
socsemFlag=false;
}
if (!node) return null;
//selection(node);
if(categoriesIndex.length==1) selectionUni(node);
if(categoriesIndex.length==2) selection(node);
opos = ArraySortByValue(opossites, function(a,b){
return b-a
});
}
// tag cloud div
//missing: the graphNGrams javascript
function htmlfied_alternodes(elems) {
var oppositesNodes=[]
js1='onclick="graphTagCloudElem(\'';
js2="');\""
frecMAX=elems[0].value
for(var i in elems){
id=elems[i].key
frec=elems[i].value
if(frecMAX==1) fontSize=desirableTagCloudFont_MIN;
else {
fontSize=
desirableTagCloudFont_MIN+
(frec-1)*
((desirableTagCloudFont_MAX-desirableTagCloudFont_MIN)/(frecMAX-1));
}
if(!isUndef(Nodes[id])){
// js1 js2
// onclick="graphNGrams(' ');
htmlfied_alternode = '<span class="tagcloud-item" style="font-size:'+fontSize+'px;" '+js1+id+js2+'>'+ Nodes[id].label+ '</span>';
oppositesNodes.push(htmlfied_alternode)
}
}
return oppositesNodes
}
function manualForceLabel(nodeid,active) {
// pr("manual|"+nodeid+"|"+active)
partialGraph._core.graph.nodesIndex[nodeid].active=active;
partialGraph.draw();
}
function htmlfied_samenodes(elems) {
var sameNodes=[]
js1=' onmouseover="manualForceLabel(this.id,true);" ';
js2=' onmouseout="manualForceLabel(this.id,true);" ';
if(elems.length>0) {
var A = getVisibleNodes()
for (var a in A){
n = A[a]
if(!n.active && n.color.charAt(0)=="#" ) {
sameNodes.push('<li onmouseover="manualForceLabel(\''+n.id+'\',true)" onmouseout="manualForceLabel(\''+n.id+'\',false)" >'+ n.label+ '</li>')
}
}
}
return sameNodes
}
// nodes information div
function htmlfied_nodesatts(elems){
var socnodes=[]
var semnodes=[]
for(var i in elems) {
information=[]
var id=elems[i]
var node = Nodes[id]
if (mainfile) {
information += '<li><b>' + node.label + '</b></li>';
for (var i in node.attributes) {
information += '<li>&nbsp;&nbsp;'+i +" : " + node.attributes[i] + '</li>';
}
socnodes.push(information);
} else {
if(node.type==catSoc){
information += '<li><b>' + node.label + '</b></li>';
if(node.htmlCont==""){
if (!isUndef(node.level)) {
information += '<li>' + node.level + '</li>';
}
} else {
information += '<li>' + $("<div/>").html(node.htmlCont).text() + '</li>';
}
socnodes.push(information)
}
if(node.type==catSem){
information += '<li><b>' + node.label + '</b></li>';
google='<a href=http://www.google.com/#hl=en&source=hp&q=%20'+node.label.replace(" ","+")+'%20><img src="'+'img/google.png"></img></a>';
wiki = '<a href=http://en.wikipedia.org/wiki/'+node.label.replace(" ","_")+'><img src="'+'img/wikipedia.png"></img></a>';
flickr= '<a href=http://www.flickr.com/search/?w=all&q='+node.label.replace(" ","+")+'><img src="'+'img/flickr.png"></img></a>';
information += '<li>'+google+"&nbsp;"+wiki+"&nbsp;"+flickr+'</li><br>';
semnodes.push(information)
}
}
}
return socnodes.concat(semnodes)
}
//missing: getTopPapers for both node types
//considering complete graphs case! <= maybe i should mv it
function updateLeftPanel_fix() {
pr("\t ** in updateLeftPanel() corrected version** ")
var namesDIV=''
var alterNodesDIV=''
var informationDIV=''
// var alternodesname=getNodeLabels(opos)
namesDIV+='<div id="selectionsBox"><h4>';
namesDIV+= getNodeLabels( selections ).join(', ')//aqui limitar
namesDIV += '</h4></div>';
if(opos.length>0) {
alterNodesDIV+='<div id="opossitesBox">';//tagcloud
alterNodesDIV+= htmlfied_alternodes( opos ).join("\n")
alterNodesDIV+= '</div>';
}
sameNodesDIV = "";
sameNodesDIV+='<div id="sameNodes"><ul style="list-style: none;">';//tagcloud
sameNodesDIV += htmlfied_samenodes( getNodeIDs(selections) ).join("\n") ;
sameNodesDIV+= '</ul></div>';
// getTopPapers("semantic");
informationDIV += '<br><h4>Information:</h4><ul>';
informationDIV += htmlfied_nodesatts( getNodeIDs(selections) ).join("<br>\n")
informationDIV += '</ul><br>';
//using the readmore.js
// ive put a limit for nodes-name div
// and opposite-nodes div aka tagcloud div
// and im commenting now because github is not
// pushing my commit
// because i need more lines, idk
$("#names").html(namesDIV).readmore({maxHeight:100});
$("#tab-container").show();
$("#opossiteNodes").html(alterNodesDIV).readmore({maxHeight:200});
$("#sameNodes").html(sameNodesDIV).readmore({maxHeight:200});
$("#information").html(informationDIV);
$("#tips").html("");
if(categoriesIndex.length==1) getTopPapers("semantic");
else getTopPapers(swclickActual);
}
function printStates() {
pr("\t\t\t\t---------"+getClientTime()+"---------")
pr("\t\t\t\tswMacro: "+swMacro)
pr("\t\t\t\tswActual: "+swclickActual+" | swPrev: "+swclickPrev)
pr("\t\t\t\tNOW: "+NOW+" | PAST: "+PAST)
pr("\t\t\t\tselections: ")
pr(Object.keys(selections))
pr("\t\t\t\topposites: ")
pr(Object.keys(opossites))
pr("\t\t\t\t------------------------------------")
}
// just css
//true: button disabled
//false: button enabled
function LevelButtonDisable( TF ){
$('#changelevel').prop('disabled', TF);
}
//tofix!
function graphTagCloudElem(nodes) {
pr("in graphTagCloudElem, nodae_id: "+nodes);
cancelSelection();
partialGraph.emptyGraph();
var ndsids=[]
if(! $.isArray(nodes)) ndsids.push(nodes);
else ndsids=nodes;
var voisinage = []
var vars = []
node_id = ndsids[0]
if(Nodes[node_id].type==catSoc) {
voisinage = nodes1;
vars = ["social","a"]
$("#colorGraph").show();
} else {
voisinage = nodes2;
vars = ["semantic","b"]
$("#colorGraph").hide();
}
var finalnodes={}
for (var i in ndsids) {
node_id = ndsids[i]
finalnodes[node_id]=1
if(voisinage[node_id]) {
for(var j in voisinage[node_id].neighbours) {
id=voisinage[node_id].neighbours[j];
s = node_id;
t = id;
edg1 = Edges[s+";"+t];
if(edg1){
if(!edg1.lock) finalnodes[t] = 1;
}
edg2 = Edges[t+";"+s];
if(edg2){
if(!edg2.lock) finalnodes[t] = 1;
}
}
}
}
for (var Nk in finalnodes) unHide(Nk);
createEdgesForExistingNodes(vars[0]);
pushSWClick(vars[0]);
RefreshState(vars[1]);
swMacro=false;
MultipleSelection(ndsids , false);//false-> dont apply deselection algorithm
$.doTimeout(10,function (){
fa2enabled=true; partialGraph.startForceAtlas2();
});
$('.gradient').css({"background-size":"90px 90px"});
}
function updateDownNodeEvent(selectionRadius){
pr("actualizando eventos downode");
partialGraph.unbind("downnodes");
partialGraph.unbind("overnodes");
partialGraph.unbind("outnodes");
hoverNodeEffectWhileFA2(selectionRadius);
}
function greyEverything(){
nds = partialGraph._core.graph.nodes.filter(function(n) {
return !n['hidden'];
});
for(var i in nds){
if(!nds[i].attr['grey']){
nds[i].attr['true_color'] = nds[i].color;
alphacol = "rgba("+hex2rga(nds[i].color)+",0.5)";
nds[i].color = alphacol;
}
nds[i].attr['grey'] = 1;
}
eds = partialGraph._core.graph.edges.filter(function(e) {
return !e['hidden'];
});
for(var i in eds){
if(!eds[i].attr['grey']){
eds[i].attr['true_color'] = eds[i].color;
eds[i].color = greyColor;
}
eds[i].attr['grey'] = 1;
}
// deselect neighbours of previous selection i think
// for(var i in selections){
// if(!isUndef(nodes1[i])){
// if(!isUndef(nodes1[i]["neighbours"])){
// nb=nodes1[i]["neighbours"];
// for(var j in nb){
// deselections[nb[j]]=1;
// partialGraph._core.graph.nodesIndex[nb[j]].forceLabel=true;
// partialGraph._core.graph.nodesIndex[nb[j]].neighbour=true;
// }
// }
// }
// }
}
//it is a mess but it works.
// TODO: refactor this
function markAsSelected(n_id,sel) {
if(!isUndef(n_id.id)) nodeSel=n_id;
else nodeSel = partialGraph._core.graph.nodesIndex[n_id];
if(sel) {
nodeSel.color = nodeSel.attr['true_color'];
nodeSel.attr['grey'] = 0;
if(categoriesIndex.length==1) {
pr("jeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeere")
if( !isUndef(nodes1[nodeSel.id]) &&
!isUndef(nodes1[nodeSel.id].neighbours)
){
neigh=nodes1[nodeSel.id].neighbours;/**/
for(var i in neigh){
vec = partialGraph._core.graph.nodesIndex[neigh[i]];
if(vec) {
vec.color = vec.attr['true_color'];
vec.attr['grey'] = 0;
an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
}
}
}
} // two categories network:
else {
if(swclickActual=="social") {
if(nodeSel.type==catSoc){
if( !isUndef(nodes1[nodeSel.id]) &&
!isUndef(nodes1[nodeSel.id].neighbours)
){
neigh=nodes1[nodeSel.id].neighbours;/**/
for(var i in neigh) {
if( !isUndef(partialGraph._core.graph.nodesIndex[neigh[i]]) ) {
nodeVec = partialGraph._core.graph.nodesIndex[neigh[i]];
// vec.color = vec.attr['true_color'];
// vec.attr['grey'] = 0;
// pr("nodeselected: "+nodeSel.id+"\t"+nodeSel.label+"\t\t||\t\tvecino: "+vec.id+"\t"+vec.label)
possibledge1 = partialGraph._core.graph.edgesIndex[nodeVec.id+";"+nodeSel.id]
possibledge2 = partialGraph._core.graph.edgesIndex[nodeSel.id+";"+nodeVec.id]
an_edge = (!isUndef(possibledge1))?possibledge1:possibledge2;
if(!isUndef(an_edge) && !an_edge.hidden) {
//highlight node
// nodeVec.hidden = false;
nodeVec.color = nodeVec.attr['true_color'];
nodeVec.attr['grey'] = 0;
//highlight edge
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
// if ( (NOW=="a" || NOW=="b") && nodeVec.color==grey)
// pr(nodeVec)
// nodeVec.hidden = true
// an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
// if(!isUndef(an_edge) && !an_edge.hidden){
// an_edge.color = an_edge.attr['true_color'];
// an_edge.attr['grey'] = 0;
// }
// an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
// if(!isUndef(an_edge) && !an_edge.hidden){
// an_edge.color = an_edge.attr['true_color'];
// an_edge.attr['grey'] = 0;
// }
}
}
}
} else {
if( !isUndef(bipartiteN2D[nodeSel.id]) &&
!isUndef(bipartiteN2D[nodeSel.id].neighbours)
){
neigh=bipartiteN2D[nodeSel.id].neighbours;/**/
for(var i in neigh){
if( !isUndef(partialGraph._core.graph.nodesIndex[neigh[i]]) ){
vec = partialGraph._core.graph.nodesIndex[neigh[i]];
vec.color = vec.attr['true_color'];
vec.attr['grey'] = 0;
an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
}
}
}
}
}
if(swclickActual=="semantic") {
if(nodeSel.type==catSoc){
if( !isUndef(bipartiteD2N[nodeSel.id]) &&
!isUndef(bipartiteD2N[nodeSel.id].neighbours)
){
neigh=bipartiteD2N[nodeSel.id].neighbours;/**/
for(var i in neigh) {
if( !isUndef(partialGraph._core.graph.nodesIndex[neigh[i]]) ) {
vec = partialGraph._core.graph.nodesIndex[neigh[i]];
vec.color = vec.attr['true_color'];
vec.attr['grey'] = 0;
an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
}
}
}
}
else {
if( !isUndef(nodes2[nodeSel.id]) &&
!isUndef(nodes2[nodeSel.id].neighbours)
){
neigh=nodes2[nodeSel.id].neighbours;/**/
for(var i in neigh){
if( !isUndef(partialGraph._core.graph.nodesIndex[neigh[i]]) ) {
nodeVec = partialGraph._core.graph.nodesIndex[neigh[i]];
// vec.color = vec.attr['true_color'];
// vec.attr['grey'] = 0;
// pr("nodeselected: "+nodeSel.id+"\t"+nodeSel.label+"\t\t||\t\tvecino: "+vec.id+"\t"+vec.label)
possibledge1 = partialGraph._core.graph.edgesIndex[nodeVec.id+";"+nodeSel.id]
possibledge2 = partialGraph._core.graph.edgesIndex[nodeSel.id+";"+nodeVec.id]
an_edge = (!isUndef(possibledge1))?possibledge1:possibledge2;
if(!isUndef(an_edge) && !an_edge.hidden) {
//highlight node
// nodeVec.hidden = false;
nodeVec.color = nodeVec.attr['true_color'];
nodeVec.attr['grey'] = 0;
//highlight edge
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
// if ( (NOW=="a" || NOW=="b") && nodeVec.color==grey)
// pr(nodeVec)
// nodeVec.hidden = true
// vec = partialGraph._core.graph.nodesIndex[neigh[i]];
// vec.color = vec.attr['true_color'];
// vec.attr['grey'] = 0;
// an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
// if(!isUndef(an_edge) && !an_edge.hidden){
// an_edge.color = an_edge.attr['true_color'];
// an_edge.attr['grey'] = 0;
// }
// an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
// if(!isUndef(an_edge) && !an_edge.hidden){
// an_edge.color = an_edge.attr['true_color'];
// an_edge.attr['grey'] = 0;
// }
}
}
}
}
}
if(swclickActual=="sociosemantic") {
if(nodeSel.type==catSoc){
if( !isUndef(nodes1[nodeSel.id]) &&
!isUndef(nodes1[nodeSel.id].neighbours)
){
neigh=nodes1[nodeSel.id].neighbours;/**/
for(var i in neigh){
if( !isUndef(partialGraph._core.graph.nodesIndex[neigh[i]]) ) {
vec = partialGraph._core.graph.nodesIndex[neigh[i]];
vec.color = vec.attr['true_color'];
vec.attr['grey'] = 0;
an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
}
}
}
if( !isUndef(bipartiteD2N[nodeSel.id]) &&
!isUndef(bipartiteD2N[nodeSel.id].neighbours)
){
neigh=bipartiteD2N[nodeSel.id].neighbours;/**/
for(var i in neigh) {
if( !isUndef(partialGraph._core.graph.nodesIndex[neigh[i]]) ) {
vec = partialGraph._core.graph.nodesIndex[neigh[i]];
vec.color = vec.attr['true_color'];
vec.attr['grey'] = 0;
an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
}
}
}
}
else {
if( !isUndef(nodes2[nodeSel.id]) &&
!isUndef(nodes2[nodeSel.id].neighbours)
){
neigh=nodes2[nodeSel.id].neighbours;/**/
for(var i in neigh) {
if( !isUndef(partialGraph._core.graph.nodesIndex[neigh[i]]) ) {
vec = partialGraph._core.graph.nodesIndex[neigh[i]];
vec.color = vec.attr['true_color'];
vec.attr['grey'] = 0;
an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
}
}
}
if( !isUndef(bipartiteN2D[nodeSel.id]) &&
!isUndef(bipartiteN2D[nodeSel.id].neighbours)
){
neigh=bipartiteN2D[nodeSel.id].neighbours;/**/
for(var i in neigh){
if( !isUndef(partialGraph._core.graph.nodesIndex[neigh[i]]) ) {
vec = partialGraph._core.graph.nodesIndex[neigh[i]];
vec.color = vec.attr['true_color'];
vec.attr['grey'] = 0;
an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
if(!isUndef(an_edge) && !an_edge.hidden){
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
if(!isUndef(an_edge) && !an_edge.hidden) {
an_edge.color = an_edge.attr['true_color'];
an_edge.attr['grey'] = 0;
}
}
}
}
}
}
}
}
// /* Just in case of unselection */
// /* Finally I decide not using this unselection. */
// /* We just greyEverything and color the selections[] */
// else { // sel=false <-> unselect(nodeSel)
//
// nodeSel.color = greyColor;
// nodeSel.attr['grey'] = 1;
//
// if(swclickActual=="social") {
// if(nodeSel.type==catSoc){
// neigh=nodes1[nodeSel.id].neighbours;/**/
// for(var i in neigh){
// vec = partialGraph._core.graph.nodesIndex[neigh[i]];
// vec.color = greyColor;
// vec.attr['grey'] = 1;
// an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// }
// }
// else {
// neigh=bipartiteN2D[nodeSel.id].neighbours;/**/
// for(var i in neigh){
// vec = partialGraph._core.graph.nodesIndex[neigh[i]];
// vec.color = greyColor;
// vec.attr['grey'] = 1;
// an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// }
// }
// }
// if(swclickActual=="semantic") {
// if(nodeSel.type==catSoc){
// neigh=bipartiteD2N[nodeSel.id].neighbours;/**/
// for(var i in neigh){
// vec = partialGraph._core.graph.nodesIndex[neigh[i]];
// vec.color = greyColor;
// vec.attr['grey'] = 1;
// an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// }
// }
// else {
// neigh=nodes2[nodeSel.id].neighbours;/**/
// for(var i in neigh){
// vec = partialGraph._core.graph.nodesIndex[neigh[i]];
// vec.color = greyColor;
// vec.attr['grey'] = 1;
// an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// }
// }
// }
// if(swclickActual=="sociosemantic") {
// if(nodeSel.type==catSoc){
// neigh=nodes1[nodeSel.id].neighbours;/**/
// for(var i in neigh){
// vec = partialGraph._core.graph.nodesIndex[neigh[i]];
// vec.color = greyColor;
// vec.attr['grey'] = 1;
// an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// }
// neigh=bipartiteD2N[nodeSel.id].neighbours;/**/
// for(var i in neigh){
// vec = partialGraph._core.graph.nodesIndex[neigh[i]];
// vec.color = greyColor;
// vec.attr['grey'] = 1;
// an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// }
// }
// else {
// neigh=nodes2[nodeSel.id].neighbours;/**/
// for(var i in neigh){
// vec = partialGraph._core.graph.nodesIndex[neigh[i]];
// vec.color = greyColor;
// vec.attr['grey'] = 1;
// an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// }
// neigh=bipartiteN2D[nodeSel.id].neighbours;/**/
// for(var i in neigh){
// vec = partialGraph._core.graph.nodesIndex[neigh[i]];
// vec.color = greyColor;
// vec.attr['grey'] = 1;
// an_edge=partialGraph._core.graph.edgesIndex[vec.id+";"+nodeSel.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// an_edge=partialGraph._core.graph.edgesIndex[nodeSel.id+";"+vec.id];
// if(typeof(an_edge)!="undefined" && an_edge.hidden==false){
// an_edge.color = greyColor;
// an_edge.attr['grey'] = 1;
// }
// }
// }
// }
// }
}
//obsolete au non
function DrawAsSelectedNodes( nodeskeys ) {
greyEverything();
var ndsids=[]
if( $.isArray(nodeskeys) ) {
if(nodeskeys.length==0 && !is_empty(nodeskeys))
ndsids = Object.keys(nodeskeys)
else
ndsids=nodeskeys;
} else ndsids.push(nodeskeys);
if(!checkBox) {
checkBox=true;
for(var i in ndsids){
nodeid = ndsids[i]
markAsSelected(nodeid,true);
}
checkBox=false;
}
overNodes=true;
}
function MultipleSelection(nodes , desalg){
pr("IN MULTIPLE SELECTION: checkbox="+checkBox)
var prevsels = selections;
if(!checkBox) cancelSelection(false);
greyEverything();
var ndsids=[]
if(! $.isArray(nodes)) ndsids.push(nodes);
else ndsids=nodes;
if(!checkBox) {
checkBox=true;
printStates();
pr("prevsels:")
pr(Object.keys(prevsels))
pr("ndsids:")
pr(ndsids)
if (desalg && !is_empty(prevsels) ) {
pr("DOING THE WEIRD ALGORITHM")
var blacklist = {};
for(var i in ndsids) {
ID = ndsids[i];
if ( prevsels[ID] ) {
delete prevsels[ID];
blacklist[ID] = true;
}
}
if(Object.keys(blacklist).length>0) {
tmparr = Object.keys(prevsels);
for (var i in ndsids) {
ID = ndsids[i];
if(isUndef(blacklist[ID])) {
tmparr.push(ID)
}
}
ndsids = tmparr;
}
} else pr("CASE NOT COVERED")
if (ndsids.length>0) {
for(var i in ndsids) {
nodeid = ndsids[i]
getOpossitesNodes(nodeid,false); //false -> just nodeid
markAsSelected(nodeid,true);
}
} else {
cancelSelection(false);
partialGraph.draw();
RefreshState("")
checkBox=false;
return;
}
checkBox=false;
} else {
//checkbox = true
cancelSelection(false);
greyEverything();
for(var i in ndsids){
nodeid = ndsids[i]
getOpossitesNodes(nodeid,false); //false -> just nodeid
markAsSelected(nodeid,true);
}
}
overNodes=true;
partialGraph.draw();
updateLeftPanel_fix();
RefreshState("")
}
//test-function
function genericHighlightSelection( nodes ) {
for( var n in nodes ) {
pr(n)
}
// nodeSel.color = nodeSel.attr['true_color'];
// nodeSel.attr['grey'] = 0;
// if(swclickActual=="social") {
// if(nodeSel.type==catSoc){
// if( !isUndef(nodes1[nodeSel.id]) &&
// !isUndef(nodes1[nodeSel.id].neighbours)
// ) {
// neigh=nodes1[nodeSel.id].neighbours;/**/
// for(var i in neigh) {
// if( !isUndef(partialGraph._core.graph.nodesIndex[neigh[i]]) ) {
// nodeVec = partialGraph._core.graph.nodesIndex[neigh[i]];
// possibledge1 = partialGraph._core.graph.edgesIndex[nodeVec.id+";"+nodeSel.id]
// possibledge2 = partialGraph._core.graph.edgesIndex[nodeSel.id+";"+nodeVec.id]
// }
// }
// }
// }
// }
}
function hoverNodeEffectWhileFA2(selectionRadius) {
partialGraph.bind('downnodes', function (event) {
var nodeID = event.content;
if(nodeID.length>0) {
pr("\t\t\t\t"+nodeID+" -> "+Nodes[nodeID].label);
pr(getn(nodeID))
if(cursor_size==0 && !checkBox){
//Normal click on a node
$.doTimeout(30,function (){
MultipleSelection(nodeID , true);//true-> apply deselection algorithm
});
}
if(cursor_size==0 && checkBox){
//Normal click on a node, but we won't clean the previous selections
selections[nodeID] = 1;
$.doTimeout(30,function (){
MultipleSelection( Object.keys(selections) , true );//true-> apply deselection algorithm
});
}
}
});
}
function graphResetColor(){
nds = partialGraph._core.graph.nodes.filter(function(x) {
return !x['hidden'];
});
eds = partialGraph._core.graph.edges.filter(function(x) {
return !x['hidden'];
});
for(var x in nds){
n=nds[x];
n.attr["grey"] = 0;
n.color = n.attr["true_color"];
}
for(var x in eds){
e=eds[x];
e.attr["grey"] = 0;
e.color = e.attr["true_color"];
}
}
function createEdgesForExistingNodes (typeOfNodes) {
if(typeOfNodes=="social") typeOfNodes="Scholars"
if(typeOfNodes=="semantic") typeOfNodes="Keywords"
if(typeOfNodes=="sociosemantic") typeOfNodes="Bipartite"
existingNodes = partialGraph._core.graph.nodes;
if( categoriesIndex.length==1 ) {
var pairdict = {}
for(var n in existingNodes) {
ID = existingNodes[n].id;
vois = nodes1[ID].neighbours;
for(var v in vois) {
pair = [ parseInt(ID) , parseInt(vois[v]) ].sort(compareNumbers)
pairdict [ pair[0]+";"+pair[1] ] = 1
}
}
for (var e in pairdict) {
edge = "";
if(isUndef(Edges[e])) {
E = e.split(";")
edge = E[1]+";"+E[0];
} else edge=e;
E = edge.split(";")
if( getn(E[0]) && getn(E[1]) )
unHide(edge)
// pr("antes:"+e+"\t|\tdespues:"+edge)
// pr("\t\t\t\t\t----- decision final "+edge)
// unHide(edge)
}
return;
}
if(typeOfNodes=="Bipartite"){
for(i=0; i < existingNodes.length ; i++){
for(j=0; j < existingNodes.length ; j++){
i1=existingNodes[i].id+";"+existingNodes[j].id;
i2=existingNodes[j].id+";"+existingNodes[i].id;
indexS1 = existingNodes[i].id;
indexT1 = existingNodes[j].id;
indexS2 = existingNodes[j].id;
indexT2 = existingNodes[i].id;
if(!isUndef(Edges[i1]) && !isUndef(Edges[i2])){
if(Edges[i1].weight > Edges[i2].weight ){
unHide(indexS1+";"+indexT1);
}
if(Edges[i1].weight < Edges[i2].weight){
unHide(indexS2+";"+indexT2);
}
if(Edges[i1].weight == Edges[i2].weight){
if(Edges[i1].label!="bipartite") { /*danger*/
if( isUndef(partialGraph._core.graph.edgesIndex[indexS1+";"+indexT1]) &&
isUndef(partialGraph._core.graph.edgesIndex[indexT1+";"+indexS1]) ){
unHide(indexS1+";"+indexT1);
}
}
}
}
else {
if(!isUndef(Edges[i1])){// && Edges[i1].label=="bipartite"){
//I've found a source Node
unHide(indexS1+";"+indexT1);
}
if(!isUndef(Edges[i2])){// && Edges[i2].label=="bipartite"){
//I've found a target Node
unHide(indexS2+";"+indexT2);
}
}
}
}
}
else {
for(i=0; i < existingNodes.length ; i++){
for(j=(i+1); j < existingNodes.length ; j++){
i1=existingNodes[i].id+";"+existingNodes[j].id;
i2=existingNodes[j].id+";"+existingNodes[i].id;
// pr("Edges[i1]:")
// pr(Edges[i1])
// pr("Edges[i2]:")
// pr(Edges[i2])
// pr(".")
// pr(".")
// if(!isUndef(Edges[i1]) && !isUndef(Edges[i2]) && i1!=i2){
// if(typeOfNodes=="Scholars") {
// if(Edges[i1].label=="nodes1" && Edges[i2].label=="nodes1"){
// pr(Edges[i1])
// if(Edges[i1].weight > Edges[i2].weight){
// unHide(i1);
// }
// if(Edges[i1].weight < Edges[i2].weight){
// unHide(i2);
// }
// if(Edges[i1].weight == Edges[i2].weight){
// unHide(i1);
// }
// }
// }
// if(typeOfNodes=="Keywords") {
// if(Edges[i1].label=="nodes2" && Edges[i2].label=="nodes2"){
// pr(Edges[i1]);
// if(Edges[i1].weight > Edges[i2].weight){
// unHide(i1);
// }
// if(Edges[i1].weight < Edges[i2].weight){
// unHide(i2);
// }
// if(Edges[i1].weight == Edges[i2].weight){
// unHide(i1);
// }
// }
// }
// }
// else {
e=(!isUndef(Edges[i1]))?Edges[i1]:Edges[i2]
if(!isUndef(e)){
if(typeOfNodes=="Scholars" && e.label=="nodes1") unHide(e.id)
if(typeOfNodes=="Keywords" && e.label=="nodes2") unHide(e.id)
}
// }
}
}
}
}
function hideEverything(){
pr("\thiding all");
nodeslength=0;
for(var n in partialGraph._core.graph.nodesIndex){
partialGraph._core.graph.nodesIndex[n].hidden=true;
}
for(var e in partialGraph._core.graph.edgesIndex){
partialGraph._core.graph.edgesIndex[e].hidden=true;
}
overNodes=false;//magic line!
pr("\tall hidded");
//Remember that this function is the analogy of EmptyGraph
//"Saving node positions" should be applied in this function, too.
}
function unHide(id){
// pr("unhide "+id)
id = ""+id;
if(id.split(";").length==1) {
// i've received a NODE
if(!isUndef(getn(id))) return;
if(Nodes[id]) {
var tt = Nodes[id].type
var anode = ({
id:id,
label: Nodes[id].label,
size: (parseFloat(Nodes[id].size)+sizeMult[tt])+"",
x: Nodes[id].x,
y: Nodes[id].y,
hidden: (Nodes[id].lock)?true:false,
type: Nodes[id].type,
color: Nodes[id].color,
shape: Nodes[id].shape
}); // The graph node
if(!Nodes[id].lock) {
updateSearchLabels(id,Nodes[id].label,Nodes[id].type);
nodeslength++;
}
partialGraph.addNode(id,anode);
return;
}
}
else {// It's an edge!
//visibleEdges.push(id);
if(!isUndef(gete(id))) return;
if(Edges[id] && !Edges[id].lock){
var anedge = {
id: id,
sourceID: Edges[id].sourceID,
targetID: Edges[id].targetID,
lock : false,
label: Edges[id].label,
weight: (swMacro && (iwantograph=="sociosemantic"))?Edges[id].bweight:Edges[id].weight
};
partialGraph.addEdge(id , anedge.sourceID , anedge.targetID , anedge);
return;
}
}
}
function pushFilterValue(filtername,arg){
lastFilter[filtername] = arg;
}
function add1Edge(ID) {
if(gete(ID)) return;
var s = Edges[ID].sourceID
var t = Edges[ID].targetID
var edge = {
id: ID,
sourceID: s,
targetID: t,
label: Edges[ID].label,
weight: Edges[ID].weight,
hidden : false
};
if(getn(s) && getn(t)) {
partialGraph.addEdge(ID,s,t,edge);
if(!isUndef(getn(s))) {
partialGraph._core.graph.nodesIndex[s].x = Nodes[s].x
partialGraph._core.graph.nodesIndex[s].y = Nodes[s].y
}
if(!isUndef(getn(t))) {
partialGraph._core.graph.nodesIndex[t].x = Nodes[t].x
partialGraph._core.graph.nodesIndex[t].y = Nodes[t].y
}
}
}
//obsolete au non
function hideElem(id){
if(id.split(";").length==1){
//updateSearchLabels(id,Nodes[id].label,Nodes[id].type);
partialGraph._core.graph.nodesIndex[id].hidden=true;
}
else {// It's an edge!
partialGraph._core.graph.edgesIndex[id].hidden=true;
// partialGraph._core.graph.edgesIndex[id].dead=true;
}
}
//obsolete au non
function unHideElem(id){
if(id.split(";").length==1){
//updateSearchLabels(id,Nodes[id].label,Nodes[id].type);
partialGraph._core.graph.nodesIndex[id].hidden=false;
}
else {// It's an edge!
partialGraph._core.graph.edgesIndex[id].hidden=false;
// partialGraph._core.graph.edgesIndex[id].dead=false;
}
}
function changeToMeso(iwannagraph) {
labels=[]
iwantograph=iwannagraph;//just a mess
partialGraph.emptyGraph();
pr("changing to Meso-"+iwannagraph);
if(iwannagraph=="social") {
if(!is_empty(selections)) {
if(swclickPrev=="social") {
var finalnodes={}
for(var i in selections) {
finalnodes[i]=1
if(nodes1[i]) {
for(var j in nodes1[i].neighbours) {
id=nodes1[i].neighbours[j];
s = i;
t = id;
edg1 = Edges[s+";"+t];
if(edg1){
// pr("\tunhide "+edg1.id)
if(!edg1.lock){
finalnodes[t] = 1;
}
}
edg2 = Edges[t+";"+s];
if(edg2){
// pr("\tunhide "+edg2.id)
if(!edg2.lock){
finalnodes[t] = 1;
}
}
}
}
}
for (var Nk in finalnodes) unHide(Nk);
createEdgesForExistingNodes(iwannagraph);/**/
}
if(swclickPrev=="semantic") {
var finalnodes={}
for(var i in selections) {
if(Nodes[i].type==catSem){
for(var j in opossites) {
// unHide(j);
finalnodes[j] = 1;
}
}
else {
// unHide(i);
finalnodes[i]=1;
if(nodes1[i]) {
neigh=nodes1[i].neighbours;
for(var j in neigh) {
// unHide(neigh[j]);
finalnodes[neigh[j]] = 1;
}
}
}
}
for (var Nk in finalnodes) unHide(Nk);
createEdgesForExistingNodes(iwannagraph);/**/
}
if(swclickPrev=="sociosemantic") {
var finalnodes={}
for(var i in selections) {
if(Nodes[i].type==catSoc){
// unHide(i);
finalnodes[i] = 1;
if(nodes1[i]) {
for(var j in nodes1[i].neighbours) {
id=nodes1[i].neighbours[j];
// unHide(id);
finalnodes[id] = 1;
}
}
// createEdgesForExistingNodes(iwannagraph);
}
if(Nodes[i].type==catSem){
for(var j in opossites) {
// unHide(j);
finalnodes[j] = 1;
}
}
}
for (var Nk in finalnodes) unHide(Nk);
createEdgesForExistingNodes(iwannagraph);
}
}
// EdgeWeightFilter("#sliderAEdgeWeight", "label" , "nodes1", "weight");
$("#colorGraph").show();
}
if(iwannagraph=="sociosemantic") {
if(!is_empty(selections) && !is_empty(opossites)){
for(var i in selections) {
unHide(i);
}
for(var i in opossites) {
unHide(i);
}
createEdgesForExistingNodes(iwannagraph);
socsemFlag=true;
}
$("#category-B").show();
EdgeWeightFilter("#sliderBEdgeWeight", "label" , "nodes2", "weight");
NodeWeightFilter ( "#sliderBNodeWeight" , "type" , "NGram" , "size");
NodeSizeSlider("#sliderBNodeSize","NGram", 25, "#FFA500")
$("#colorGraph").hide();
}
if(iwannagraph=="semantic") {
if(!is_empty(opossites)){
// hideEverything()
//pr("2. swclickPrev: "+swclickPrev+" - swclickActual: "+swclickActual);
var finalnodes = {}
if(swclickPrev=="semantic") {
var finalnodes={}
for(var i in selections) {
finalnodes[i]=1
if(nodes2[i]) {
for(var j in nodes2[i].neighbours) {
id=nodes2[i].neighbours[j];
s = i;
t = id;
edg1 = Edges[s+";"+t];
if(edg1){
// pr("\tunhide "+edg1.id)
if(!edg1.lock){
finalnodes[t] = 1;
}
}
edg2 = Edges[t+";"+s];
if(edg2){
// pr("\tunhide "+edg2.id)
if(!edg2.lock){
finalnodes[t] = 1;
}
}
}
}
}
for (var Nk in finalnodes) unHide(Nk);
createEdgesForExistingNodes(iwannagraph);/**/
// for(var i in selections) {
// // unHide(i);
// finalnodes[i] = 1;
// if(nodes2[i]) {
// neigh=nodes2[i].neighbours;
// for(var j in neigh) {
// // unHide(neigh[j]);
// finalnodes[neigh[j]] = 1;
// }
// }
// }
// for (var Nk in finalnodes) unHide(Nk);
// createEdgesForExistingNodes(iwannagraph);
}
if(swclickPrev=="social") {
var finalnodes = {}
for(var i in selections) {
if(Nodes[i].type==catSoc){
for(var j in opossites) {
// unHide(j);
finalnodes[j] = 1;
}
} else {
// unHide(i);
finalnodes[i] = 1;
if(nodes2[i]) {
neigh=nodes2[i].neighbours;
for(var j in neigh) {
// unHide(neigh[j]);
finalnodes[neigh[j]] = 1;
}
}
}
}
for (var Nk in finalnodes) unHide(Nk);
createEdgesForExistingNodes(iwannagraph);
}
if(swclickPrev=="sociosemantic") {
var finalnodes = {}
for(var i in selections) {
if(Nodes[i].type==catSoc){
for(var j in opossites) {
// unHide(j);
finalnodes[i] = 1;
}
}
if(Nodes[i].type==catSem){
// unHide(i);//sneaky bug!
finalnodes[i] = 1;
if(nodes2[i]) {
for(var j in nodes2[i].neighbours) {
id=nodes2[i].neighbours[j];
// unHide(id);
finalnodes[id] = 1;
}
}
}
}
for (var Nk in finalnodes) unHide(Nk);
createEdgesForExistingNodes(iwannagraph);
}
}
$("#category-B").show();
EdgeWeightFilter("#sliderBEdgeWeight", "label" , "nodes2", "weight");
NodeWeightFilter ( "#sliderBNodeWeight" , "type" , "NGram" , "size");
NodeSizeSlider("#sliderBNodeSize","NGram", 25, "#FFA500")
$("#colorGraph").hide();
}
fa2enabled=true; partialGraph.startForceAtlas2();
MultipleSelection(Object.keys(selections) , false);//false-> dont apply deselection algorithm
$('.gradient').css({"background-size":"90px 90px"});
}
function changeToMacro(iwannagraph) {
labels=[]
pr("CHANGING TO Macro-"+iwannagraph);
iwantograph=iwannagraph;//just a mess
partialGraph.emptyGraph();
if ( iwannagraph=="semantic" && !semanticConverged ) {
partialGraph.draw();
partialGraph.refresh();
$("#semLoader").css('visibility', 'visible');
$("#semLoader").show();
return;
}
//iwantograph Social OR Semantic
if(iwannagraph!="sociosemantic") {
socsemFlag=false;
category = (iwannagraph=="social")?catSoc:catSem;
pr("CHANGING TO Macro-"+iwannagraph+" __ [category: "+category+"] __ [actualsw: "+swclickActual+"] __ [prevsw: "+swclickPrev+"]")
//show semantic nodes
for(var n in Nodes) {
if(Nodes[n].type==category){
unHide(n);
}
} // and semantic edges
createEdgesForExistingNodes(iwannagraph);
if(iwannagraph=="social") showMeSomeLabels(6);
else {
$("#category-B").show();
EdgeWeightFilter("#sliderBEdgeWeight", "label" , "nodes2", "weight");
NodeWeightFilter ( "#sliderBNodeWeight" , "type" , "NGram" , "size");
NodeSizeSlider("#sliderBNodeSize","NGram", 25, "#FFA500")
}
swMacro=true;
if (!is_empty(selections))
$.doTimeout(10,function (){
chosenones=(PAST=="a"||PAST=="b")?selections:opossites;
MultipleSelection(Object.keys(chosenones) , false)//false-> dont apply deselection algorithm
});
} else {
//iwantograph socio-semantic
for(var n in Nodes) unHide(n);
for(var e in Edges) {
if(Edges[e].label=="nodes1" || Edges[e].label=="nodes2"){
st=e.split(";");
if(Edges[st[0]+";"+st[1]] && Edges[st[1]+";"+st[0]] &&
Edges[st[0]+";"+st[1]].hidden==true &&
Edges[st[1]+";"+st[0]].hidden==true
){
if(Edges[st[0]+";"+st[1]].weight == Edges[st[1]+";"+st[0]].weight){
unHide(st[0]+";"+st[1]);
}
else {
if(Edges[st[0]+";"+st[1]].weight > Edges[st[1]+";"+st[0]].weight){
unHide(st[0]+";"+st[1]);
}
else {
unHide(st[1]+";"+st[0]);
}
}
}
}
if(Edges[e].label=="bipartite"){
unHide(e);
}
}
if (!is_empty(selections))
MultipleSelection(Object.keys(selections) , false);//false-> dont apply deselection algorithm
}
$.doTimeout(30,function (){
if(iwannagraph=="social") {
// EdgeWeightFilter("#sliderAEdgeWeight", "label" , "nodes1", "weight");
$("#colorGraph").show();
}
if(iwannagraph=="semantic") {
// EdgeWeightFilter("#sliderBEdgeWeight", "label" , "nodes2", "weight");
// NodeWeightFilter ( "#sliderBNodeWeight" , "type" , "NGram" , "size")
$("#colorGraph").hide();
}
if(iwannagraph=="sociosemantic") {
// EdgeWeightFilter("#sliderBEdgeWeight", "label" , "nodes2", "weight");
// NodeWeightFilter ( "#sliderBNodeWeight" , "type" , "NGram" , "size")
// EdgeWeightFilter("#sliderAEdgeWeight", "label" , "nodes1", "weight");
$("#colorGraph").hide();
}
});
// fa2enabled=true; partialGraph.startForceAtlas2();
$('.gradient').css({"background-size":"40px 40px"});
var activefilterscount=0;
for(var i in lastFilter) {
if(iwannagraph=="social" && i.indexOf("sliderA")!=-1 )
if(lastFilter[i].charAt(0)!="0")
activefilterscount++;
if(iwannagraph=="semantic" && i.indexOf("sliderb")!=-1)
if(lastFilter[i].charAt(0)!="0")
activefilterscount++;
if(iwannagraph=="sociosemantic")
if(lastFilter[i].charAt(0)!="0")
activefilterscount++;
}
// for 1 second, activate FA2 if there is any filter applied
if(activefilterscount>0) {
partialGraph.startForceAtlas2();
$.doTimeout(2000,function (){
partialGraph.stopForceAtlas2()
});
}
}
function highlightOpossites (list){/*here*/
for(var n in list){
if(!isUndef(partialGraph._core.graph.nodesIndex[n])){
partialGraph._core.graph.nodesIndex[n].active=true;
}
}
}
function saveGraph() {
size = getByID("check_size").checked
color = getByID("check_color").checked
atts = {"size":size,"color":color}
if(getByID("fullgraph").checked) {
saveGEXF ( getnodes() , getedges() , atts);
}
if(getByID("visgraph").checked) {
saveGEXF ( getVisibleNodes() , getVisibleEdges(), atts )
}
$("#closesavemodal").click();
}
function saveGEXF(nodes,edges,atts){
gexf = '<?xml version="1.0" encoding="UTF-8"?>\n';
gexf += '<gexf xmlns="http://www.gexf.net/1.1draft" xmlns:viz="http://www.gephi.org/gexf/viz" version="1.1">\n';
gexf += '<graph defaultedgetype="undirected" type="static">\n';
gexf += '<attributes class="node" type="static">\n';
gexf += ' <attribute id="0" title="category" type="string"> </attribute>\n';
gexf += ' <attribute id="1" title="country" type="float"> </attribute>\n';
//gexf += ' <attribute id="2" title="content" type="string"> </attribute>\n';
//gexf += ' <attribute id="3" title="keywords" type="string"> </attribute>\n';
//gexf += ' <attribute id="4" title="weight" type="float"> </attribute>\n';
gexf += '</attributes>\n';
gexf += '<attributes class="edge" type="float">\n';
gexf += ' <attribute id="6" title="type" type="string"> </attribute>\n';
gexf += '</attributes>\n';
gexf += "<nodes>\n";
for(var n in nodes){
gexf += '<node id="'+nodes[n].id+'" label="'+nodes[n].label+'">\n';
gexf += ' <viz:position x="'+nodes[n].x+'" y="'+nodes[n].y+'" z="0" />\n';
if(atts["color"]) gexf += ' <viz:size value="'+nodes[n].size+'" />\n';
if(atts["color"]) {
col = hex2rga(nodes[n].color);
gexf += ' <viz:color r="'+col[0]+'" g="'+col[1]+'" b="'+col[2]+'" a="1"/>\n';
}
gexf += ' <attvalues>\n';
gexf += ' <attvalue for="0" value="'+nodes[n].type+'"/>\n';
gexf += ' <attvalue for="1" value="'+Nodes[nodes[n].id].CC+'"/>\n';
gexf += ' </attvalues>\n';
gexf += '</node>\n';
}
gexf += "\n</nodes>\n";
gexf += "<edges>\n";
cont = 1;
for(var e in edges){
gexf += '<edge id="'+cont+'" source="'+edges[e].source.id+'" target="'+edges[e].target.id+'" weight="'+edges[e].weight+'">\n';
gexf += '<attvalues> <attvalue for="6" value="'+edges[e].label+'"/></attvalues>';
gexf += '</edge>\n';
cont++;
}
gexf += "\n</edges>\n</graph>\n</gexf>";
uriContent = "data:application/octet-stream," + encodeURIComponent(gexf);
newWindow=window.open(uriContent, 'neuesDokument');
}
function saveGraphIMG(){
var strDownloadMime = "image/octet-stream"
var nodesDiv = partialGraph._core.domElements.nodes;
var nodesCtx = nodesDiv.getContext("2d");
var edgesDiv = partialGraph._core.domElements.edges;
var edgesCtx = edgesDiv.getContext("2d");
var hoverDiv = partialGraph._core.domElements.hover;
var hoverCtx = hoverDiv.getContext("2d");
var labelsDiv = partialGraph._core.domElements.labels;
var labelsCtx = labelsDiv.getContext("2d");
nodesCtx.drawImage(hoverDiv,0,0);
nodesCtx.drawImage(labelsDiv,0,0);
edgesCtx.drawImage(nodesDiv,0,0);
var strData = edgesDiv.toDataURL("image/png");
document.location.href = strData.replace("image/png", strDownloadMime)
}
function draw1Circle(ctx , x , y , color) {
ctx.strokeStyle = '#000';
ctx.lineWidth = 1;
ctx.fillStyle = color;
ctx.globalAlpha = 0.5;
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
function trackMouse() {
if(!shift_key) {
// $.doTimeout(300,function (){
var ctx = partialGraph._core.domElements.mouse.getContext('2d');
ctx.globalCompositeOperation = "source-over";
ctx.clearRect(0, 0, partialGraph._core.domElements.nodes.width, partialGraph._core.domElements.nodes.height);
x = partialGraph._core.mousecaptor.mouseX;
y = partialGraph._core.mousecaptor.mouseY;
ctx.strokeStyle = '#000';
ctx.lineWidth = 1;
ctx.fillStyle = "#71C3FF";
ctx.globalAlpha = 0.5;
ctx.beginPath();
// if(partialGraph._core.mousecaptor.ratio>showLabelsIfZoom){
// for(var i in partialGraph._core.graph.nodesIndex){
// n=partialGraph._core.graph.nodesIndex[i];
// if(n.hidden==false){
// distance = Math.sqrt(
// Math.pow((x-parseInt(n.displayX)),2) +
// Math.pow((y-parseInt(n.displayY)),2)
// );
// if(parseInt(distance)<=cursor_size) {
// partialGraph._core.graph.nodesIndex[i].forceLabel=true;
// } else {
// if(typeof(n.neighbour)!=="undefined") {
// if(!n.neighbour) partialGraph._core.graph.nodesIndex[i].forceLabel=false;
// } else partialGraph._core.graph.nodesIndex[i].forceLabel=false;
// }
// }
// }
// partialGraph.draw(2,2,2);
// } else {
// for(var i in partialGraph._core.graph.nodesIndex){
// n=partialGraph._core.graph.nodesIndex[i];
// if(!n.hidden){
// partialGraph._core.graph.nodesIndex[i].forceLabel=false;
// if(typeof(n.neighbour)!=="undefined") {
// if(!n.neighbour) partialGraph._core.graph.nodesIndex[i].forceLabel=false;
// else partialGraph._core.graph.nodesIndex[i].forceLabel=true;
// } else partialGraph._core.graph.nodesIndex[i].forceLabel=false;
// }
// }
// partialGraph.draw(2,2,2);
// }
ctx.arc(x, y, cursor_size, 0, Math.PI * 2, true);
//ctx.arc(partialGraph._core.width/2, partialGraph._core.height/2, 4, 0, 2 * Math.PI, true);/*todel*/
ctx.closePath();
ctx.fill();
ctx.stroke();
// });
}
};
function changeGraphPosition(evt, echelle) {
document.body.style.cursor = "move";
var _coord = {
x : evt.pageX,
y : evt.pageY
};
console.log("changeGraphPosition... cordx: "+_coord.x+" - cordy: "+_coord.y);
partialGraph.centreX += ( partialGraph.lastMouse.x - _coord.x ) / echelle;
partialGraph.centreY += ( partialGraph.lastMouse.y - _coord.y ) / echelle;
partialGraph.lastMouse = _coord;
}
function onOverviewMove(evt) {
console.log("onOverViewMove");
/*
pageX: 1247 pageY: 216
screenX: 1188 screenY: 307
pageX: 1444 pageY: 216
screenX: 1365 screenY: 307
*/
if (partialGraph.dragOn) {
changeGraphPosition(evt,-overviewScale);
}
}
function startMove(evt){
console.log("startMove");
evt.preventDefault();
partialGraph.dragOn = true;
partialGraph.lastMouse = {
x : evt.pageX,
y : evt.pageY
}
partialGraph.mouseHasMoved = false;
}
function endMove(evt){
console.log("endMove");
document.body.style.cursor = "default";
partialGraph.dragOn = false;
partialGraph.mouseHasMoved = false;
}
function onGraphScroll(evt, delta) {
$("#zoomSlider").slider("value",partialGraph.position().ratio);
// partialGraph.totalScroll += delta;
// if (Math.abs(partialGraph.totalScroll) >= 1) {
// if (partialGraph.totalScroll < 0) {
// //ZoomOUT
// if (partialGraph.position().ratio > sigmaJsMouseProperties.minRatio) {
// //partialGraph.zoomTo(partialGraph._core.width / 2, partialGraph._core.height / 2, partialGraph._core.mousecaptor.ratio * 0.5);
// //var _el = $(this),
// //_off = $(this).offset(),
// //_deltaX = evt.pageX - _el.width() / 2 - _off.left,
// //_deltaY = evt.pageY - _el.height() / 2 - _off.top;
// var
// mx=evt.offsetX,
// my=evt.offsetY;
// partialGraph.centreX=mx*((partialGraph._core.width-1)/(overviewWidth)),
// partialGraph.centreY=my*((partialGraph._core.height-1)/(overviewHeight));
// // console.log("mx: "+mx+" - my: "+ my);
// // console.log("cx: "+cx+" - cy: "+ cy);
// // partialGraph.centreX =cx;
// // partialGraph.centreY =cy;
// partialGraph.zoomTo(partialGraph.centreX, partialGraph.centreY, partialGraph._core.mousecaptor.ratio * 0.5);
// // partialGraph.centreX -= ( Math.SQRT2 - 1 ) * _deltaX / partialGraph.echelleGenerale;
// // partialGraph.centreY -= ( Math.SQRT2 - 1 ) * _deltaY / partialGraph.echelleGenerale;
// // partialGraph.zoomTo(partialGraph._core.width / 2, partialGraph._core.height / 2, partialGraph._core.mousecaptor.ratio * 0.5);
// $("#zoomSlider").slider("value",partialGraph.position().ratio);
// }
// } else {
// //ZoomIN
// if (partialGraph.position().ratio < sigmaJsMouseProperties.maxRatio) {
// // partialGraph.zoomTo(partialGraph._core.width / 2, partialGraph._core.height / 2, partialGraph._core.mousecaptor.ratio * 1.5);
// // partialGraph.echelleGenerale = Math.pow( Math.SQRT2, partialGraph.position().ratio );
// //var _el = $(this),
// //_off = $(this).offset(),
// //_deltaX = evt.pageX - _el.width() / 2 - _off.left,
// //_deltaY = evt.pageY - _el.height() / 2 - _off.top;
// var
// mx=evt.offsetX,
// my=evt.offsetY;
// partialGraph.centreX=mx*((partialGraph._core.width-1)/(overviewWidth)),
// partialGraph.centreY=my*((partialGraph._core.height-1)/(overviewHeight));
// // console.log("mx: "+mx+" - my: "+ my);
// // console.log("cx: "+cx+" - cy: "+ cy);
// // partialGraph.centreX =cx;
// // partialGraph.centreY =cy;
// partialGraph.zoomTo(partialGraph.centreX, partialGraph.centreY, partialGraph._core.mousecaptor.ratio * 1.5);
// $("#zoomSlider").slider("value",partialGraph.position().ratio);
// }
// }
// partialGraph.totalScroll = 0;
// }
}
function initializeMap() {
clearInterval(partialGraph.timeRefresh);
partialGraph.oldParams = {};
if(minimap){
$("#overviewzone").css({
width : overviewWidth + "px",
height : overviewHeight + "px"
});
$("#overview").attr({
width : overviewWidth,
height : overviewHeight
});
partialGraph.timeRefresh = setInterval(traceMap,60);
}
}
function updateMap(){
if(minimap){
partialGraph.imageMini="";
partialGraph.ctxMini="";
partialGraph.ctxMini = document.getElementById('overview').getContext('2d');
partialGraph.ctxMini.clearRect(0, 0, overviewWidth, overviewHeight);
partialGraph.iterNodes(function(n){
if(n.hidden==false){
partialGraph.ctxMini.fillStyle = n.color;
partialGraph.ctxMini.beginPath();
numPosibilidades = 2.5 - 0.9;
aleat = Math.random() * numPosibilidades;
partialGraph.ctxMini.arc(((n.displayX/1.2)-200)*0.25 , ((n.displayY/1.2)+110)*0.25 , (0.9 + aleat)*0.25+1 , 0 , Math.PI*2 , true);
// //console.log(n.x*1000 +" * 0.25"+" _ "+ n.y*1000 +" * 0.25"+" _ "+ (0.9 + aleat) +" * 0.25 + 1");
//
partialGraph.ctxMini.closePath();
partialGraph.ctxMini.fill();
}
//
});
partialGraph.imageMini = partialGraph.ctxMini.getImageData(0, 0, overviewWidth, overviewHeight);
}
}
function traceMap() {
//pr("\ttracingmap");
partialGraph.echelleGenerale = Math.pow( Math.SQRT2, partialGraph.position().ratio );
partialGraph.ctxMini.putImageData(partialGraph.imageMini, 0, 0);
var _r = 0.25 / partialGraph.echelleGenerale,
cx = partialGraph.centreX,
cy = partialGraph.centreY,
_w = _r * partialGraph._core.width,
_h = _r * partialGraph._core.height;
partialGraph.ctxMini.strokeStyle = "rgb(220,0,0)";
partialGraph.ctxMini.lineWidth = 3;
partialGraph.ctxMini.fillStyle = "rgba(120,120,120,0.2)";
partialGraph.ctxMini.beginPath();
partialGraph.ctxMini.fillRect( cx-_w/2, cy-_h/2, _w, _h );
partialGraph.ctxMini.strokeRect( cx-_w/2, cy-_h/2, _w, _h );
partialGraph.ctxMini.closePath();
}
function startMiniMap(){
if(minimap){
partialGraph.ctxMini = document.getElementById('overview').getContext('2d');
partialGraph.ctxMini.clearRect(0, 0, overviewWidth, overviewHeight);
partialGraph.totalScroll=0;
partialGraph.centreX = partialGraph._core.width/2;
partialGraph.centreY = partialGraph._core.heigth/2;
}
}
\ No newline at end of file
/*
* Customize as you want ;)
*/
// ============ < DEVELOPER OPTIONS > ============
var geomap=false;
var minimap=false;
var getAdditionalInfo=false;//for topPapers div
var mainfile=false;
// ourGetUrlParam.file = "data/testgraph.json";
var dataFolderTree = {};
var gexfDict={};
var egonode = {}
var iwantograph = "";
var bridge={};
external="";
//external="http://tina.iscpif.fr/explorerjs/";//Just if you want to use the server-apps from tina.server
bridge["forFilteredQuery"] = "comexAPI" //external+"php/bridgeClientServer_filter.php";
bridge["forNormalQuery"] = "comexAPI" //external+"php/bridgeClientServer.php";
ircNick="";
ircCHN="";
var catSoc = "Document";
var catSem = "NGram";
var sizeMult = [];
sizeMult[catSoc] = 0.0;
sizeMult[catSem] = 0.0;
var inactiveColor = '#666';
var startingNodeId = "1";
var minLengthAutoComplete = 1;
var maxSearchResults = 10;
var strSearchBar = "Search";
var cursor_size_min= 0;
var cursor_size= 0;
var cursor_size_max= 100;
var desirableTagCloudFont_MIN=12;
var desirableTagCloudFont_MAX=20;
var desirableNodeSizeMIN=1;
var desirableNodeSizeMAX=12;
var desirableScholarSize=6; //Remember that all scholars have the same size!
/*
*Three states:
* - true: fa2 running at start
* - false: fa2 stopped at start, button exists
* - "off": button doesn't exist, fa2 stopped forever
**/ var fa2enabled=false;//"off";
var stopcriteria = false;
var iterationsFA2=1000;
var seed=999999999;//defaultseed
var semanticConverged=false;
var showLabelsIfZoom=2.0;
var greyColor = "#9b9e9e";
// ============ < SIGMA.JS PROPERTIES > ============
var sigmaJsDrawingProperties = {
defaultLabelColor: 'black',
defaultLabelSize: 10,//in fact I'm using it as minLabelSize'
defaultLabelBGColor: '#fff',
defaultLabelHoverColor: '#000',
labelThreshold: 6,
defaultEdgeType: 'curve',
borderSize: 2.5,//Something other than 0
nodeBorderColor: "default",//exactly like this
defaultNodeBorderColor: "black"//,//Any color of your choice
//defaultBorderView: "always"
};
var sigmaJsGraphProperties = {
minEdgeSize: 2,
maxEdgeSize: 2
};
var sigmaJsMouseProperties = {
minRatio:0.1,
maxRatio: 15
};
// ============ < / SIGMA.JS PROPERTIES > ============
// ============ < / DEVELOPER OPTIONS > ============
// ============ < VARIABLES.JS > ============
//"http://webchat.freenode.net/?nick=Ademe&channels=#anoe"
var ircUrl="http://webchat.freenode.net/?nick="+ircNick+"&channels="+ircCHN;
var twjs="tinawebJS/";
var categories = {};
var categoriesIndex = [];
var gexf;
//var zoom=0;
var checkBox=false;
var overNodes=false;
var shift_key=false;
var NOW="A";
var PAST="--";
var swclickActual="";
var swclickPrev="";
var swMacro=true;
var socsemFlag=false;
var constantNGramFilter;
// var nodeFilterA_past = ""
// var nodeFilterA_now = ""
// var nodeFilterB_past = ""
// var nodeFilterB_now = ""
var lastFilter = []
lastFilter["#sliderBNodeWeight"] = "-"
lastFilter["#sliderAEdgeWeight"] = "-"
lastFilter["#sliderBEdgeWeight"] = "-"
// var edgeFilterB_past = ""
// var edgeFilterB_now = ""
var overviewWidth = 200;
var overviewHeight = 175;
var overviewScale = 0.25;
var overviewHover=false;
var moveDelay = 80, zoomDelay = 2;
//var Vecindad;
var partialGraph;
var otherGraph;
var Nodes = [];
var Edges = [];
var nodeslength=0;
var labels = [];
var numberOfDocs=0;
var numberOfNGrams=0;
var selections = [];
var deselections={};
var opossites = {};
var opos=[];
var oposMAX;
var matches = [];
var nodes1 = [];
var nodes2 = [];
var bipartiteD2N = [];
var bipartiteN2D = [];
var flag=0;
var firstime=0;
var leftright=true;
var edgesTF=false;
//This variables will be updated in sigma.parseCustom.js
var minNodeSize=1.00;
var maxNodeSize=5.00;
var minEdgeWeight=5.0;
var maxEdgeWeight=0.0;
//---------------------------------------------------
var bipartite=false;
var gexfDictReverse={}
for (var i in gexfDict){
gexfDictReverse[gexfDict[i]]=i;
}
var colorList = ["#000000", "#FFFF00", "#1CE6FF", "#FF34FF", "#FF4A46", "#008941", "#006FA6", "#A30059", "#FFDBE5", "#7A4900", "#0000A6", "#63FFAC", "#B79762", "#004D43", "#8FB0FF", "#997D87", "#5A0007", "#809693", "#FEFFE6", "#1B4400", "#4FC601", "#3B5DFF", "#4A3B53", "#FF2F80", "#61615A", "#BA0900", "#6B7900", "#00C2A0", "#FFAA92", "#FF90C9", "#B903AA", "#D16100", "#DDEFFF", "#000035", "#7B4F4B", "#A1C299", "#300018", "#0AA6D8", "#013349", "#00846F", "#372101", "#FFB500", "#C2FFED", "#A079BF", "#CC0744", "#C0B9B2", "#C2FF99", "#001E09", "#00489C", "#6F0062", "#0CBD66", "#EEC3FF", "#456D75", "#B77B68", "#7A87A1", "#788D66", "#885578", "#FAD09F", "#FF8A9A", "#D157A0", "#BEC459", "#456648", "#0086ED", "#886F4C","#34362D", "#B4A8BD", "#00A6AA", "#452C2C", "#636375", "#A3C8C9", "#FF913F", "#938A81", "#575329", "#00FECF", "#B05B6F", "#8CD0FF", "#3B9700", "#04F757", "#C8A1A1", "#1E6E00", "#7900D7", "#A77500", "#6367A9", "#A05837", "#6B002C", "#772600", "#D790FF", "#9B9700", "#549E79", "#FFF69F", "#201625", "#72418F", "#BC23FF", "#99ADC0", "#3A2465", "#922329", "#5B4534", "#FDE8DC", "#404E55", "#0089A3", "#CB7E98", "#A4E804", "#324E72", "#6A3A4C", "#83AB58", "#001C1E", "#D1F7CE", "#004B28", "#C8D0F6", "#A3A489", "#806C66", "#222800", "#BF5650", "#E83000", "#66796D", "#DA007C", "#FF1A59", "#8ADBB4", "#1E0200", "#5B4E51", "#C895C5", "#320033", "#FF6832", "#66E1D3", "#CFCDAC", "#D0AC94", "#7ED379", "#012C58"];
var RVUniformC = function(seed){
this.a=16807;
this.b=0;
this.m=2147483647;
this.u;
this.seed=seed;
this.x = this.seed;
// this.generar = function(n){
// uniforme = [];
// x = 0.0;
// x = this.seed;
// for(i = 1; i < n ; i++){
// x = ((x*this.a)+this.b)%this.m;
// uniforme[i] = x/this.m;
// }
// return uniforme;
// };
this.getRandom = function(){
x = ((this.x*this.a)+this.b)%this.m;
this.x = x;
this.u = this.x/this.m;
return this.u;
};
}
//unifCont = new RVUniformC(100000000)
// Mathieu Jacomy @ Sciences Po Médialab & WebAtlas
// (requires sigma.js to be loaded)
var minx=1000.0, maxx=0.0, miny=1000.0, maxy=0.0;
sigma.forceatlas2 = sigma.forceatlas2 || {};
sigma.forceatlas2.ForceAtlas2 = function(graph , V , E) {
sigma.classes.Cascade.call(this);
var self = this;
this.graph = graph;
this.count=0;
this.active = false;
this.isolated=0;
this.stepDeg = 0;
this.minx=1000.0;
this.maxx=0.0;
this.miny=1000.0;
this.maxy=0.0;
this.Ox = 0.0;//(this.minx+self.maxx)/2;
this.Oy = 0.0;//(self.miny+self.maxy)/2;
this.Px = 0.0;
this.Py = 0.0;
this.firstit = true;
this.R = 100;
this.p = {
linLogMode: false,
outboundAttractionDistribution: false,
adjustSizes: false,
edgeWeightInfluence: 0,
scalingRatio: 1,
strongGravityMode: false,
gravity: 1,
jitterTolerance: 1,
barnesHutOptimize: false,
barnesHutTheta: 1.2,
speed: 20,
outboundAttCompensation: 1,
totalSwinging: 0,
swingVSnode1: 0,
banderita: false,
totalEffectiveTraction: 0,
complexIntervals: 500,
simpleIntervals: 1000
};
// The state tracked from one atomic "go" to another
this.state = {step: 0, index: 0};
this.rootRegion;
// Runtime (the ForceAtlas2 itself)
this.init = function() {
self.firstit = true;
self.isolated=0;
// console.log("#Nodes: "+V)
// console.log("#Edges: "+E)
self.state = {step: 0, index: 0};
// calc dimensions of connected subgraphs
self.minx=1000.0;
self.maxx=0.0;
self.miny=1000.0;
self.maxy=0.0;
self.graph.nodes.forEach(function(n) {
if(n.degree>0) {
if(n.x < self.minx) self.minx = n.x
if(n.x > self.maxx) self.maxx = n.x
if(n.y < self.miny) self.miny = n.y
if(n.y > self.maxy) self.maxy = n.y
n.fa2 = {
mass: 1 + n.degree,
old_dx: 0,
old_dy: 0,
dx: 0,
dy: 0
};
} else self.isolated++;
});
self.stepDeg = 2/parseFloat(self.isolated);
return self;
}
this.go = function() {
while (self.atomicGo()) {}
}
this.atomicGo = function() {
var graph = self.graph;
var nodes = graph.nodes;
var edges = graph.edges;
var cInt = self.p.complexIntervals;
var sInt = self.p.simpleIntervals;
switch (self.state.step) {
case 0: // Pass init
// pr("case0 - "+"the self.count: "+self.count)
// Initialise layout data
self.count++;
if( self.firstit ) {
self.Ox = (self.minx+self.maxx)/2;
self.Oy = (self.miny+self.maxy)/2;
self.Px = self.minx;
self.Py = self.miny;
self.R = Math.sqrt( Math.pow((self.Ox-self.Px), 2) + Math.pow((self.Oy-self.Py), 2) );
self.R = self.R * 1.2;
}
var mult = 1;
nodes.forEach(function(n) {
if(n.degree>0) {
if(n.fa2) {
n.fa2.mass = 1 + n.degree;
n.fa2.old_dx = n.fa2.dx;
n.fa2.old_dy = n.fa2.dx;
n.fa2.dx = 0;
n.fa2.dy = 0;
} else {
n.fa2 = {
mass: 1 + n.degree,
old_dx: 0,
old_dy: 0,
dx: 0,
dy: 0
};
}
} else {
if( self.firstit ) {
n.x = self.Ox + self.R*Math.cos(Math.PI*self.stepDeg*mult);
n.y = self.Oy + self.R*Math.sin(Math.PI*self.stepDeg*mult);
mult++;
}
}
});
self.firstit = false ;
// If Barnes Hut active, initialize root region
if (self.p.barnesHutOptimize) {
self.rootRegion = new sigma.forceatlas2.Region(nodes, 0);
self.rootRegion.buildSubRegions();
}
// If outboundAttractionDistribution active, compensate.
if (self.p.outboundAttractionDistribution) {
self.p.outboundAttCompensation = 0;
nodes.forEach(function(n) {
if(!n.hidden && n.degree>0) {
self.p.outboundAttCompensation += n.fa2.mass;
}
});
self.p.outboundAttCompensation /= nodes.length;
}
self.state.step = 1;
self.state.index = 0;
return true;
break;
case 1: // Repulsion
// pr("case1 - "+"the self.count: "+self.count)
var Repulsion = self.ForceFactory.buildRepulsion(
self.p.adjustSizes,
self.p.scalingRatio
);
if (self.p.barnesHutOptimize) {
var rootRegion = self.rootRegion;
// Pass to the scope of forEach
var barnesHutTheta = self.p.barnesHutTheta;
var i = self.state.index;
while (i < nodes.length && i < self.state.index + cInt) {
var n = nodes[i++];
if(!n.hidden && n.degree>0 && n.fa2)
rootRegion.applyForce(n, Repulsion, barnesHutTheta);
}
if (i == nodes.length) {
self.state.step = 2;
self.state.index = 0;
} else {
self.state.index = i;
}
} else {
var i1 = self.state.index;
while (i1 < nodes.length && i1 < self.state.index + cInt) {
var n1 = nodes[i1++];
if(!n1.hidden && n1.degree>0 && n1.fa2)
nodes.forEach(function(n2, i2) {
if (i2 < i1 && (!n2.hidden && n2.degree>0 && n2.fa2)) {
Repulsion.apply_nn(n1, n2);
}
});
}
if (i1 == nodes.length) {
self.state.step = 2;
self.state.index = 0;
} else {
self.state.index = i1;
}
}
return true;
break;
case 2: // Gravity
// pr("case2 - "+"the self.count: "+self.count)
var Gravity = (self.p.strongGravityMode) ?
(self.ForceFactory.getStrongGravity(
self.p.scalingRatio
)) :
(self.ForceFactory.buildRepulsion(
self.p.adjustSizes,
self.p.scalingRatio
));
// Pass gravity and scalingRatio to the scope of the function
var gravity = self.p.gravity,
scalingRatio = self.p.scalingRatio;
var i = self.state.index;
while (i < nodes.length && i < self.state.index + sInt) {
var n = nodes[i++];
if (!n.hidden && n.degree>0 && n.fa2)
Gravity.apply_g(n, gravity / scalingRatio);
}
if (i == nodes.length) {
self.state.step = 3;
self.state.index = 0;
} else {
self.state.index = i;
}
return true;
break;
case 3: // Attraction
// pr("case3 - "+"the self.count: "+self.count)
var Attraction = self.ForceFactory.buildAttraction(
self.p.linLogMode,
self.p.outboundAttractionDistribution,
self.p.adjustSizes,
1 * ((self.p.outboundAttractionDistribution) ?
(self.p.outboundAttCompensation) :
(1))
);
var i = self.state.index;
if (self.p.edgeWeightInfluence == 0) {
while (i < edges.length && i < self.state.index + cInt) {
var e = edges[i++];
if(!e.hidden) {
Attraction.apply_nn(e.source, e.target, 1);
}
}
} else if (self.p.edgeWeightInfluence == 1) {
while (i < edges.length && i < self.state.index + cInt) {
var e = edges[i++];
if(!e.hidden) {
Attraction.apply_nn(e.source, e.target, e.weight || 1);
}
}
} else {
while (i < edges.length && i < self.state.index + cInt) {
var e = edges[i++];
if(!e.hidden) {
Attraction.apply_nn(
e.source, e.target,
Math.pow(e.weight || 1, self.p.edgeWeightInfluence)
);
}
}
}
if (i == edges.length) {
self.state.step = 4;
self.state.index = 0;
} else {
self.state.index = i;
}
return true;
break;
case 4: // Auto adjust speed
// pr("case4 - "+"the self.count: "+self.count)
var totalSwinging = 0; // How much irregular movement
var totalEffectiveTraction = 0; // Hom much useful movement
var swingingSum=0;
var promdxdy=0; /**/
nodes.forEach(function(n) {
var fixed = n.fixed || false;
if (!fixed && !n.hidden && n.degree>0 && n.fa2) {
var swinging = Math.sqrt(Math.pow(n.fa2.old_dx - n.fa2.dx, 2) +
Math.pow(n.fa2.old_dy - n.fa2.dy, 2));
// If the node has a burst change of direction,
// then it's not converging.
totalSwinging += n.fa2.mass * swinging;
swingingSum += swinging;
promdxdy += (Math.abs(n.fa2.dx)+Math.abs(n.fa2.dy))/2; /**/
totalEffectiveTraction += n.fa2.mass *
0.5 *
Math.sqrt(
Math.pow(n.fa2.old_dx + n.fa2.dx, 2) +
Math.pow(n.fa2.old_dy + n.fa2.dy, 2)
);
}
});
self.p.totalSwinging = totalSwinging;
var convg= ((Math.pow(nodes.length,2))/promdxdy); /**/
var swingingVSnodes_length = swingingSum/nodes.length; /**/
if(stopcriteria && (convg > swingingVSnodes_length)){
pr("i've applied the stopcriteria: "+self.count)
partialGraph.stopForceAtlas2();
}
self.p.totalEffectiveTraction = totalEffectiveTraction;
// We want that swingingMovement < tolerance * convergenceMovement
var targetSpeed = Math.pow(self.p.jitterTolerance, 2) *
self.p.totalEffectiveTraction /
self.p.totalSwinging;
// But the speed shoudn't rise too much too quickly,
// since it would make the convergence drop dramatically.
var maxRise = 0.5; // Max rise: 50%
self.p.speed = self.p.speed +
Math.min(
targetSpeed - self.p.speed,
maxRise * self.p.speed
);
// Save old coordinates
nodes.forEach(function(n) {
if(!n.hidden && n.degree>0) {
n.old_x = +n.x;
n.old_y = +n.y;
}
});
self.state.step = 5;
return true;
break;
case 5: // Apply forces
// pr("case5 - "+"the self.count: "+self.count)
var i = self.state.index;
if (self.p.adjustSizes) {
var speed = self.p.speed;
// If nodes overlap prevention is active,
// it's not possible to trust the swinging mesure.
while (i < nodes.length && i < self.state.index + sInt) {
var n = nodes[i++];
var fixed = n.fixed || false;
if (!fixed && !n.hidden && n.degree>0 && n.fa2) {
// Adaptive auto-speed: the speed of each node is lowered
// when the node swings.
var swinging = Math.sqrt(
(n.fa2.old_dx - n.fa2.dx) *
(n.fa2.old_dx - n.fa2.dx) +
(n.fa2.old_dy - n.fa2.dy) *
(n.fa2.old_dy - n.fa2.dy)
);
var factor = 0.1 * speed / (1 + speed * Math.sqrt(swinging));
var df = Math.sqrt(Math.pow(n.fa2.dx, 2) +
Math.pow(n.fa2.dy, 2));
factor = Math.min(factor * df, 10) / df;
n.x += n.fa2.dx * factor;
n.y += n.fa2.dy * factor;
}
}
if(self.isolated>0 && self.count%50 == 0) {
nodes.forEach(function(n) {
if(n.degree>0) {
if(n.x < self.minx) self.minx = n.x
if(n.x > self.maxx) self.maxx = n.x
if(n.y < self.miny) self.miny = n.y
if(n.y > self.maxy) self.maxy = n.y
}
});
self.Ox = (self.minx+self.maxx)/2;
self.Oy = (self.miny+self.maxy)/2;
self.Px = self.minx;
self.Py = self.miny;
self.R = Math.sqrt( Math.pow((self.Ox-self.Px), 2) + Math.pow((self.Oy-self.Py), 2) );
self.R = self.R * 1.2;
var mult = 1;
nodes.forEach(function(n) {
if(n.degree==0) {
n.x = self.Ox + self.R*Math.cos(Math.PI*self.stepDeg*mult);
n.y = self.Oy + self.R*Math.sin(Math.PI*self.stepDeg*mult);
mult++;
}
});
}
} else {
var speed = self.p.speed;
while (i < nodes.length && i < self.state.index + sInt) {
var n = nodes[i++];
var fixed = n.fixed || false;
if (!fixed && !n.hidden && n.degree>0 && n.fa2) {
// Adaptive auto-speed: the speed of each node is lowered
// when the node swings.
var swinging = Math.sqrt(
(n.fa2.old_dx - n.fa2.dx) *
(n.fa2.old_dx - n.fa2.dx) +
(n.fa2.old_dy - n.fa2.dy) *
(n.fa2.old_dy - n.fa2.dy)
);
var factor = speed / (1 + speed * Math.sqrt(swinging));
n.x += n.fa2.dx * factor;
n.y += n.fa2.dy * factor;
}
}
if(self.isolated>0 && self.count%50 == 0) {
nodes.forEach(function(n) {
if(n.degree>0) {
if(n.x < self.minx) self.minx = n.x
if(n.x > self.maxx) self.maxx = n.x
if(n.y < self.miny) self.miny = n.y
if(n.y > self.maxy) self.maxy = n.y
}
});
self.Ox = (self.minx+self.maxx)/2;
self.Oy = (self.miny+self.maxy)/2;
self.Px = self.minx;
self.Py = self.miny;
self.R = Math.sqrt( Math.pow((self.Ox-self.Px), 2) + Math.pow((self.Oy-self.Py), 2) );
self.R = self.R * 1.2;
var mult = 1;
nodes.forEach(function(n) {
if(n.degree==0) {
n.x = self.Ox + self.R*Math.cos(Math.PI*self.stepDeg*mult);
n.y = self.Oy + self.R*Math.sin(Math.PI*self.stepDeg*mult);
mult++;
}
});
}
}
if (i == nodes.length) {
self.state.step = 0;
self.state.index = 0;
return false;
} else {
self.state.index = i;
return true;
}
break;
default:
throw new Error('ForceAtlas2 - atomic state error');
break;
}
}
this.end = function() {
this.graph.nodes.forEach(function(n) {
n.fa2 = null;
});
}
// Auto Settings
this.setAutoSettings = function() {
var graph = this.graph;
// Tuning
if (graph.nodes.length >= 100) {
this.p.scalingRatio = 2.0;
} else {
this.p.scalingRatio = 10.0;
}
this.p.strongGravityMode = false;
this.p.gravity = 1;
// Behavior
this.p.outboundAttractionDistribution = false;
this.p.linLogMode = false;
this.p.adjustSizes = false;
this.p.edgeWeightInfluence = 1;
// Performance
if (graph.nodes.length >= 50000) {
this.p.jitterTolerance = 10;
} else if (graph.nodes.length >= 5000) {
this.p.jitterTolerance = 1;
} else {
this.p.jitterTolerance = 0.1;
}
if (graph.nodes.length >= 1000) {
this.p.barnesHutOptimize = true;
} else {
this.p.barnesHutOptimize = false;
}
this.p.barnesHutTheta = 1.2;
return this;
}
// All the different forces
this.ForceFactory = {
buildRepulsion: function(adjustBySize, coefficient) {
if (adjustBySize) {
return new this.linRepulsion_antiCollision(coefficient);
} else {
return new this.linRepulsion(coefficient);
}
},
getStrongGravity: function(coefficient) {
return new this.strongGravity(coefficient);
},
buildAttraction: function(logAttr, distributedAttr, adjustBySize, c) {
if (adjustBySize) {
if (logAttr) {
if (distributedAttr) {
return new this.logAttraction_degreeDistributed_antiCollision(c);
} else {
return new this.logAttraction_antiCollision(c);
}
} else {
if (distributedAttr) {
return new this.linAttraction_degreeDistributed_antiCollision(c);
} else {
return new this.linAttraction_antiCollision(c);
}
}
} else {
if (logAttr) {
if (distributedAttr) {
return new this.logAttraction_degreeDistributed(c);
} else {
return new this.logAttraction(c);
}
} else {
if (distributedAttr) {
return new this.linAttraction_massDistributed(c);
} else {
return new this.linAttraction(c);
}
}
}
},
// Repulsion force: Linear
linRepulsion: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient *
n1.fa2.mass *
n2.fa2.mass /
Math.pow(distance, 2);
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
this.apply_nr = function(n, r) {
// Get the distance
var xDist = n.x - r.config('massCenterX');
var yDist = n.y - r.config('massCenterY');
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient *
n.fa2.mass *
r.config('mass') /
Math.pow(distance, 2);
n.fa2.dx += xDist * factor;
n.fa2.dy += yDist * factor;
}
}
this.apply_g = function(n, g) {
// Get the distance
var xDist = n.x;
var yDist = n.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient * n.fa2.mass * g / distance;
n.fa2.dx -= xDist * factor;
n.fa2.dy -= yDist * factor;
}
}
},
linRepulsion_antiCollision: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist) -
n1.size -
n2.size;
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient *
n1.fa2.mass *
n2.fa2.mass /
Math.pow(distance, 2);
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
} else if (distance < 0) {
var factor = 100 * this.coefficient * n1.fa2.mass * n2.fa2.mass;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
this.apply_nr = function(n, r) {
// Get the distance
var xDist = n.fa2.x() - r.getMassCenterX();
var yDist = n.fa2.y() - r.getMassCenterY();
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient *
n.fa2.mass *
r.getMass() /
Math.pow(distance, 2);
n.fa2.dx += xDist * factor;
n.fa2.dy += yDist * factor;
} else if (distance < 0) {
var factor = -this.coefficient * n.fa2.mass * r.getMass() / distance;
n.fa2.dx += xDist * factor;
n.fa2.dy += yDist * factor;
}
}
this.apply_g = function(n, g) {
// Get the distance
var xDist = n.x;
var yDist = n.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient * n.fa2.mass * g / distance;
n.fa2.dx -= xDist * factor;
n.fa2.dy -= yDist * factor;
}
}
},
// Repulsion force: Strong Gravity
// (as a Repulsion Force because it is easier)
strongGravity: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2) {
// Not Relevant
}
this.apply_nr = function(n, r) {
// Not Relevant
}
this.apply_g = function(n, g) {
// Get the distance
var xDist = n.x;
var yDist = n.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = this.coefficient * n.fa2.mass * g;
n.fa2.dx -= xDist * factor;
n.fa2.dy -= yDist * factor;
}
}
},
// Attraction force: Linear
linAttraction: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
// NB: factor = force / distance
var factor = -this.coefficient * e;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
},
// Attraction force: Linear, distributed by mass (typically, degree)
linAttraction_massDistributed: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
// NB: factor = force / distance
var factor = -this.coefficient * e / n1.fa2.mass;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
},
// Attraction force: Logarithmic
logAttraction: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = -this.coefficient *
e *
Math.log(1 + distance) /
distance;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
},
// Attraction force: Linear, distributed by Degree
logAttraction_degreeDistributed: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = -this.coefficient *
e *
Math.log(1 + distance) /
distance /
n1.fa2.mass;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
},
// Attraction force: Linear, with Anti-Collision
linAttraction_antiCollision: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = -this.coefficient * e;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
},
// Attraction force: Linear, distributed by Degree, with Anti-Collision
linAttraction_degreeDistributed_antiCollision: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = -this.coefficient * e / n1.fa2.mass;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
},
// Attraction force: Logarithmic, with Anti-Collision
logAttraction_antiCollision: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = -this.coefficient *
e *
Math.log(1 + distance) /
distance;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
},
// Attraction force: Linear, distributed by Degree, with Anti-Collision
logAttraction_degreeDistributed_antiCollision: function(c) {
this.coefficient = c;
this.apply_nn = function(n1, n2, e) {
if(n1.fa2 && n2.fa2)
{
// Get the distance
var xDist = n1.x - n2.x;
var yDist = n1.y - n2.y;
var distance = Math.sqrt(xDist * xDist + yDist * yDist);
if (distance > 0) {
// NB: factor = force / distance
var factor = -this.coefficient *
e *
Math.log(1 + distance) /
distance /
n1.fa2.mass;
n1.fa2.dx += xDist * factor;
n1.fa2.dy += yDist * factor;
n2.fa2.dx -= xDist * factor;
n2.fa2.dy -= yDist * factor;
}
}
}
}
};
};
// The Region class, as used by the Barnes Hut optimization
sigma.forceatlas2.Region = function(nodes, depth) {
sigma.classes.Cascade.call(this);
this.depthLimit = 20;
this.size = 0;
this.nodes = nodes;
this.subregions = [];
this.depth = depth;
this.p = {
mass: 0,
massCenterX: 0,
massCenterY: 0
};
this.updateMassAndGeometry();
}
sigma.forceatlas2.Region.prototype.updateMassAndGeometry = function() {
if (this.nodes.length > 1) {
// Compute Mass
var mass = 0;
var massSumX = 0;
var massSumY = 0;
this.nodes.forEach(function(n) {
if(n.fa2) {
mass += n.fa2.mass;
massSumX += n.x * n.fa2.mass;
massSumY += n.y * n.fa2.mass;
}
});
var massCenterX = massSumX / mass;
massCenterY = massSumY / mass;
// Compute size
var size;
this.nodes.forEach(function(n) {
var distance = Math.sqrt(
(n.x - massCenterX) *
(n.x - massCenterX) +
(n.y - massCenterY) *
(n.y - massCenterY)
);
size = Math.max(size || (2 * distance), 2 * distance);
});
this.p.mass = mass;
this.p.massCenterX = massCenterX;
this.p.massCenterY = massCenterY;
this.size = size;
}
};
sigma.forceatlas2.Region.prototype.buildSubRegions = function() {
if (this.nodes.length > 1) {
var leftNodes = [];
var rightNodes = [];
var subregions = [];
var massCenterX = this.p.massCenterX;
var massCenterY = this.p.massCenterY;
var nextDepth = this.depth + 1;
var self = this;
this.nodes.forEach(function(n) {
var nodesColumn = (n.x < massCenterX) ? (leftNodes) : (rightNodes);
nodesColumn.push(n);
});
var tl = [], bl = [], br = [], tr = [];
leftNodes.forEach(function(n) {
var nodesLine = (n.y < massCenterY) ? (tl) : (bl);
nodesLine.push(n);
});
rightNodes.forEach(function(n) {
var nodesLine = (n.y < massCenterY) ? (tr) : (br);
nodesLine.push(n);
});
[tl, bl, br, tr].filter(function(a) {
return a.length;
}).forEach(function(a) {
if (nextDepth <= self.depthLimit && a.length < self.nodes.length) {
var subregion = new sigma.forceatlas2.Region(a, nextDepth);
subregions.push(subregion);
} else {
a.forEach(function(n) {
var oneNodeList = [n];
var subregion = new sigma.forceatlas2.Region(oneNodeList, nextDepth);
subregions.push(subregion);
});
}
});
this.subregions = subregions;
subregions.forEach(function(subregion) {
subregion.buildSubRegions();
});
}
};
sigma.forceatlas2.Region.prototype.applyForce = function(n, Force, theta) {
if (this.nodes.length < 2) {
var regionNode = this.nodes[0];
Force.apply_nn(n, regionNode);
} else {
var distance = Math.sqrt(
(n.x - this.p.massCenterX) *
(n.x - this.p.massCenterX) +
(n.y - this.p.massCenterY) *
(n.y - this.p.massCenterY)
);
if (distance * theta > this.size) {
Force.apply_nr(n, this);
} else {
this.subregions.forEach(function(subregion) {
subregion.applyForce(n, Force, theta);
});
}
}
};
sigma.publicPrototype.startForceAtlas2 = function() {
//if(!this.forceatlas2) {
if(fa2enabled) {
var V = 10;
var E = 100;
this.forceatlas2 = new sigma.forceatlas2.ForceAtlas2(this._core.graph , V, E);
this.forceatlas2.setAutoSettings();
this.forceatlas2.init();
this.forceatlas2.active=true;
// pr("\t\t\t\t\tFA2 Started")
var ene = this._core.graph.nodes.length;
var isolatedBCauseFilter = 0;
for (var i in this._core.graph.nodesIndex) {
if(this._core.graph.nodesIndex[i].degree==0) isolatedBCauseFilter++;
}
if(isolatedBCauseFilter==ene) {
partialGraph.stopForceAtlas2();
return;
}
$("#overviewzone").hide();
this.addGenerator('forceatlas2', this.forceatlas2.atomicGo, function(){
return true;
});
// fixing anomaly in forceatlas2
$.doTimeout(250,function (){
if( !swMacro && partialGraph.forceatlas2.active && partialGraph.forceatlas2.count==0) {
pr("SUPER JUTSU!!")
partialGraph.startForceAtlas2();
return;
}
});
}
};
sigma.publicPrototype.stopForceAtlas2 = function() {
// pr("\t\t\t\t\tFA2 Stopped")
this.removeGenerator('forceatlas2');
this.forceatlas2.active=false;
this.forceatlas2.count=0;
updateMap();
partialGraph.refresh();
if(minimap) $("#overviewzone").show();
};
This source diff could not be displayed because it is too large. You can view the blob instead.
/*
*Categories example (bigraph):
* ISItermsAlexandrePartCountry
* Authors
**/
function parse(gexfPath) {
var gexfhttp;
gexfhttp = window.XMLHttpRequest ?
new XMLHttpRequest() :
new ActiveXObject('Microsoft.XMLHTTP');
gexfhttp.open('GET', gexfPath, false);
gexfhttp.send();
gexf = gexfhttp.responseXML;
}
function scanCategories() {
nodesNodes = gexf.getElementsByTagName('nodes');
for(i=0; i<nodesNodes.length; i++){
var nodesNode = nodesNodes[i]; // Each xml node 'nodes' (plural)
node = nodesNode.getElementsByTagName('node');
for(j=0; j<node.length; j++){
attvalueNodes = node[j].getElementsByTagName('attvalue');
for(k=0; k<attvalueNodes.length; k++){
attvalueNode = attvalueNodes[k];
attr = attvalueNode.getAttribute('for');
val = attvalueNode.getAttribute('value');
// pr(val)
if (attr=="category") categories[val]=val;
}
}
}
pr("The categories");
pr(categories);
pr("");
i=0;
for (var cat in categories) {
categoriesIndex[i] = cat;
i++;
}
pr("The categoriesIndex");
pr(categoriesIndex);
pr("");
return Object.keys(categories).length;
}
function onepartiteExtract(){
var i, j, k;
// partialGraph.emptyGraph();
// Parse Attributes
// This is confusing, so I'll comment heavily
var nodesAttributes = []; // The list of attributes of the nodes of the graph that we build in json
var edgesAttributes = []; // The list of attributes of the edges of the graph that we build in json
var attributesNodes = gexf.getElementsByTagName('attributes'); // In the gexf (that is an xml), the list of xml nodes 'attributes' (note the plural 's')
for(i = 0; i<attributesNodes.length; i++){
var attributesNode = attributesNodes[i]; // attributesNode is each xml node 'attributes' (plural)
if(attributesNode.getAttribute('class') == 'node'){
var attributeNodes = attributesNode.getElementsByTagName('attribute'); // The list of xml nodes 'attribute' (no 's')
for(j = 0; j<attributeNodes.length; j++){
var attributeNode = attributeNodes[j]; // Each xml node 'attribute'
var id = attributeNode.getAttribute('id'),
title = attributeNode.getAttribute('title'),
type = attributeNode.getAttribute('type');
var attribute = {
id:id,
title:title,
type:type
};
nodesAttributes.push(attribute);
}
} else if(attributesNode.getAttribute('class') == 'edge'){
var attributeNodes = attributesNode.getElementsByTagName('attribute'); // The list of xml nodes 'attribute' (no 's')
for(j = 0; j<attributeNodes.length; j++){
var attributeNode = attributeNodes[j]; // Each xml node 'attribute'
var id = attributeNode.getAttribute('id'),
title = attributeNode.getAttribute('title'),
type = attributeNode.getAttribute('type');
var attribute = {
id:id,
title:title,
type:type
};
edgesAttributes.push(attribute);
}
}
}
var nodesNodes = gexf.getElementsByTagName('nodes') // The list of xml nodes 'nodes' (plural)
labels = [];
minNodeSize=5.00;
maxNodeSize=5.00;
numberOfDocs=0;
numberOfNGrams=0;
for(i=0; i<nodesNodes.length; i++){
var nodesNode = nodesNodes[i]; // Each xml node 'nodes' (plural)
var nodeNodes = nodesNode.getElementsByTagName('node'); // The list of xml nodes 'node' (no 's')
for(j=0; j<nodeNodes.length; j++){
var nodeNode = nodeNodes[j]; // Each xml node 'node' (no 's')
window.NODE = nodeNode;
var id = ""+nodeNode.getAttribute('id');
var label = nodeNode.getAttribute('label') || id;
//viz
var size=1;
sizeNodes = nodeNode.getElementsByTagName('size');
sizeNodes = sizeNodes.length ?
sizeNodes :
nodeNode.getElementsByTagName('viz:size');
if(sizeNodes.length>0){
sizeNode = sizeNodes[0];
size = parseFloat(sizeNode.getAttribute('value'));
}
var x = 100 - 200*Math.random();
var y = 100 - 200*Math.random();
var color;
var positionNodes = nodeNode.getElementsByTagName('position');
positionNodes = positionNodes.length ?
positionNodes :
nodeNode.getElementsByTagNameNS('*','position');
if(positionNodes.length>0){
var positionNode = positionNodes[0];
x = parseFloat(positionNode.getAttribute('x'));
y = parseFloat(positionNode.getAttribute('y'));
}
var colorNodes = nodeNode.getElementsByTagName('color');
colorNodes = colorNodes.length ?
colorNodes :
nodeNode.getElementsByTagNameNS('*','color');
if(colorNodes.length>0){
colorNode = colorNodes[0];
color = '#'+sigma.tools.rgbToHex(parseFloat(colorNode.getAttribute('r')),
parseFloat(colorNode.getAttribute('g')),
parseFloat(colorNode.getAttribute('b')));
}
var node = ({
id:id,
label:label,
size:size,
x:x,
y:y,
type:"",
attributes:[],
color:color
}); // The graph node
// Attribute values
var attvalueNodes = nodeNode.getElementsByTagName('attvalue');
var atts={};
for(k=0; k<attvalueNodes.length; k++){
var attvalueNode = attvalueNodes[k];
var attr = attvalueNode.getAttribute('for');
var val = attvalueNode.getAttribute('value');
// node.attributes.push({
// attr:attr,
// val:val
// });
atts[attr]=val;
node.attributes = atts;
}
node.id=id;
node.type = catSoc;
//if(node.attributes[0].attr=="weight"){
if(typeof(node.size)==="undefined") node.size=parseInt(node.attributes["weight"]);
//}
// if(node.attributes[1].attr=="weight"){
// node.size=node.attributes[1].val;
// }
partialGraph.addNode(id,node);
labels.push({
'label' : label,
'desc' : node.type
});
if(parseInt(node.size) < parseInt(minNodeSize)) minNodeSize= node.size;
if(parseInt(node.size) > parseInt(maxNodeSize)) maxNodeSize= node.size;
// Create Node
Nodes[id] = node // The graph node
//pr(node);
}
}
//New scale for node size: now, between 2 and 5 instead [1,70]
for(var it in Nodes){
Nodes[it].size =
desirableNodeSizeMIN+
(parseInt(Nodes[it].size)-1)*
((desirableNodeSizeMAX-desirableNodeSizeMIN)/
(maxNodeSize-minNodeSize));
partialGraph._core.graph.nodesIndex[it].size=Nodes[it].size;
}
var edgeId = 0;
var edgesNodes = gexf.getElementsByTagName('edges');
minEdgeWeight=5.0;
maxEdgeWeight=0.0;
for(i=0; i<edgesNodes.length; i++){
var edgesNode = edgesNodes[i];
var edgeNodes = edgesNode.getElementsByTagName('edge');
for(j=0; j<edgeNodes.length; j++){
var edgeNode = edgeNodes[j];
var source = edgeNode.getAttribute('source');
var target = edgeNode.getAttribute('target');
var indice=source+";"+target;
var edge = {
id: j,
sourceID: source,
targetID: target,
label: "",
weight: 1,
lock: false,
attributes: []
};
var weight = edgeNode.getAttribute('weight');
if(weight!=undefined){
edge['weight'] = weight;
}
var kind;
var attvalueNodes = edgeNode.getElementsByTagName('attvalue');
for(k=0; k<attvalueNodes.length; k++){
var attvalueNode = attvalueNodes[k];
var attr = attvalueNode.getAttribute('for');
var val = attvalueNode.getAttribute('value');
if(k==1) {
kind=val;
edge.label=val;
}
if(k==3) {
edge.weight = val;
if(edge.weight < minEdgeWeight) minEdgeWeight= edge.weight;
if(edge.weight > maxEdgeWeight) maxEdgeWeight= edge.weight;
}
edge.attributes.push({
attr:attr,
val:val
});
}
edge.label="nodes1";
if(isUndef(nodes1[source])){
nodes1[source] = {
label: Nodes[source].label,
neighbours: [],
neighboursIndex: {}
};
nodes1[source].neighboursIndex[target] = 1;
} else nodes1[source].neighboursIndex[target] = 1;
if( isUndef(nodes1[target]) ){
nodes1[target] = {
label: Nodes[target].label,
neighbours: [],
neighboursIndex: {}
};
nodes1[target].neighboursIndex[source] = 1;
} else nodes1[target].neighboursIndex[source] = 1;
Edges[indice] = edge;
if( isUndef(gete([target+";"+source])) ) partialGraph.addEdge(indice,source,target,edge);
}
}
for(var n in nodes1) {
nodes1[n].neighbours = Object.keys(nodes1[n].neighboursIndex)
nodes1[n].neighboursIndex = null;
delete nodes1[n].neighboursIndex
}
}
function fullExtract(){
var i, j, k;
// Parse Attributes
// This is confusing, so I'll comment heavily
var nodesAttributes = []; // The list of attributes of the nodes of the graph that we build in json
var edgesAttributes = []; // The list of attributes of the edges of the graph that we build in json
var attributesNodes = gexf.getElementsByTagName('attributes'); // In the gexf (that is an xml), the list of xml nodes 'attributes' (note the plural 's')
for(i = 0; i<attributesNodes.length; i++){
var attributesNode = attributesNodes[i]; // attributesNode is each xml node 'attributes' (plural)
if(attributesNode.getAttribute('class') == 'node'){
var attributeNodes = attributesNode.getElementsByTagName('attribute'); // The list of xml nodes 'attribute' (no 's')
for(j = 0; j<attributeNodes.length; j++){
var attributeNode = attributeNodes[j]; // Each xml node 'attribute'
var id = attributeNode.getAttribute('id'),
title = attributeNode.getAttribute('title'),
type = attributeNode.getAttribute('type');
var attribute = {
id:id,
title:title,
type:type
};
nodesAttributes.push(attribute);
}
} else if(attributesNode.getAttribute('class') == 'edge'){
var attributeNodes = attributesNode.getElementsByTagName('attribute'); // The list of xml nodes 'attribute' (no 's')
for(j = 0; j<attributeNodes.length; j++){
var attributeNode = attributeNodes[j]; // Each xml node 'attribute'
var id = attributeNode.getAttribute('id'),
title = attributeNode.getAttribute('title'),
type = attributeNode.getAttribute('type');
var attribute = {
id:id,
title:title,
type:type
};
edgesAttributes.push(attribute);
}
}
}
var nodesNodes = gexf.getElementsByTagName('nodes') // The list of xml nodes 'nodes' (plural)
labels = [];
numberOfDocs=0;
numberOfNGrams=0;
for(i=0; i<nodesNodes.length; i++){
var nodesNode = nodesNodes[i]; // Each xml node 'nodes' (plural)
var nodeNodes = nodesNode.getElementsByTagName('node'); // The list of xml nodes 'node' (no 's')
for(j=0; j<nodeNodes.length; j++){
var nodeNode = nodeNodes[j]; // Each xml node 'node' (no 's')
window.NODE = nodeNode;
var id = nodeNode.getAttribute('id');
var label = nodeNode.getAttribute('label') || id;
var size=1;
sizeNodes = nodeNode.getElementsByTagName('size');
sizeNodes = sizeNodes.length ?
sizeNodes :
nodeNode.getElementsByTagName('viz:size');
if(sizeNodes.length>0){
sizeNode = sizeNodes[0];
size = parseFloat(sizeNode.getAttribute('value'));
}
var x = 100 - 200*Math.random();
var y = 100 - 200*Math.random();
var color;
var positionNodes = nodeNode.getElementsByTagName('position');
positionNodes = positionNodes.length ? positionNodes : nodeNode.getElementsByTagNameNS('*','position');
if(positionNodes.length>0){
var positionNode = positionNodes[0];
x = parseFloat(positionNode.getAttribute('x'));
y = parseFloat(positionNode.getAttribute('y'));
}
var colorNodes = nodeNode.getElementsByTagName('color');
colorNodes = colorNodes.length ? colorNodes : nodeNode.getElementsByTagNameNS('*','color');
if(colorNodes.length>0){
colorNode = colorNodes[0];
color = '#'+sigma.tools.rgbToHex(parseFloat(colorNode.getAttribute('r')),
parseFloat(colorNode.getAttribute('g')),
parseFloat(colorNode.getAttribute('b')));
}
var node = ({
id:id,
label:label,
size:size,
x:x,
y:y,
type:"",
attributes:[],
color:color
}); // The graph node
// Attribute values
var attvalueNodes = nodeNode.getElementsByTagName('attvalue');
var atts={};
for(k=0; k<attvalueNodes.length; k++){
var attvalueNode = attvalueNodes[k];
var attr = attvalueNode.getAttribute('for');
var val = attvalueNode.getAttribute('value');
atts[attr]=val;
node.attributes = atts;
/* Para asignar tamaño a los NGrams */
if(atts["category"]===categoriesIndex[1]) {
if(typeof(node.size)==="undefined") node.size=parseInt(val).toFixed(2);
}
/* Para asignar tamaño a los NGrams */
}
//console.log(node.attributes);
nodecat=node.attributes["category"];
nodew=parseInt(node.attributes["weight"]);
if( nodecat===categoriesIndex[1]){
node.type=catSoc;
node.id = "D::"+node.id;
node.shape="square";
numberOfDocs++;
//node.size=desirableScholarSize;
if(typeof(node.size)==="undefined") node.size=nodew;
} else {
node.type=catSem;
node.id = "N::"+node.id;
numberOfNGrams++;
if(isUndef(node.size)) node.size=nodew;
}
if(parseInt(node.size) < parseInt(minNodeSize)) minNodeSize= node.size;
if(parseInt(node.size) > parseInt(maxNodeSize)) maxNodeSize= node.size;
// Create Node
Nodes[node.id] = node // The graph node
}
}
//New scale for node size: now, between 2 and 5 instead [1,70]
for(var i in Nodes){
normalizedSize=desirableNodeSizeMIN+(Nodes[i].size-1)*((desirableNodeSizeMAX-desirableNodeSizeMIN)/(parseInt(maxNodeSize)-parseInt(minNodeSize)));
Nodes[i].size = ""+normalizedSize;
nodeK = Nodes[i];
if(Nodes[i].type==catSoc) {
nodeK.shape="square";
partialGraph.addNode(i,nodeK);
}
// pr(nodeK)
}
//Edges
var edgeId = 0;
var edgesNodes = gexf.getElementsByTagName('edges');
for(i=0; i<edgesNodes.length; i++){
var edgesNode = edgesNodes[i];
var edgeNodes = edgesNode.getElementsByTagName('edge');
for(j=0; j<edgeNodes.length; j++){
var edgeNode = edgeNodes[j];
var source = edgeNode.getAttribute('source');
var target = edgeNode.getAttribute('target');
source = (Nodes["D::"+source])? ("D::"+source):("N::"+source)
target = (Nodes["D::"+target])? ("D::"+target):("N::"+target)
var indice=source+";"+target;
var edge = {
id: indice,
sourceID: source,
targetID: target,
label: "",
weight: 1,
attributes: []
};
var weight = edgeNode.getAttribute('weight');
if(weight!=undefined){
edge['weight'] = weight;
}
var kind;
var attvalueNodes = edgeNode.getElementsByTagName('attvalue');
for(k=0; k<attvalueNodes.length; k++){
var attvalueNode = attvalueNodes[k];
var attr = attvalueNode.getAttribute('for');
var val = attvalueNode.getAttribute('value');
if(k=="category") {
kind=val;
edge.label=val;
}
if(k==3) {
edge.weight = val;
if(edge.weight < minEdgeWeight) minEdgeWeight= edge.weight;
if(edge.weight > maxEdgeWeight) maxEdgeWeight= edge.weight;
}
edge.attributes.push({
attr:attr,
val:val
});
}
// pr(edge)
idS=Nodes[edge.sourceID].type;
idT=Nodes[edge.targetID].type;
Edges[indice] = edge;
// if(idS==idT)
// pr(edge.sourceID+"|"+idS+" <-> "+idT+"|"+edge.targetID)
if(idS==catSoc && idT==catSoc){
// pr("anything here?")
edge.label = "nodes1";
if(isUndef(nodes1[source])) {
nodes1[source] = {
label: Nodes[source].label,
neighbours: []
};
}
if(isUndef(nodes1[target])) {
nodes1[target] = {
label: Nodes[target].label,
neighbours: []
};
}
nodes1[source].neighbours.push(target);
nodes1[target].neighbours.push(source);
// partialGraph.addEdge(indice,source,target,edge);
}
if(idS==catSem && idT==catSem){
edge.label = "nodes2";
if(isUndef(nodes2[source])) {
nodes2[source] = {
label: Nodes[source].label,
neighbours: []
};
}
if(isUndef(nodes2[target])) {
nodes2[target] = {
label: Nodes[target].label,
neighbours: []
};
}
nodes2[source].neighbours.push(target);
nodes2[target].neighbours.push(source);
// otherGraph.addEdge(indice,source,target,edge);
}
if((idS==catSoc && idT==catSem)||(idS==catSem && idT==catSoc)) {
edge.label = "bipartite";
s = edge.sourceID
// // Source is Document
if(Nodes[s].type == catSoc) {
if(isUndef(bipartiteD2N[source])) {
bipartiteD2N[source] = {
label: Nodes[source].label,
neighbours: []
};
}
if(isUndef(bipartiteN2D[target])) {
bipartiteN2D[target] = {
label: Nodes[target].label,
neighbours: []
};
}
bipartiteD2N[source].neighbours.push(target);
bipartiteN2D[target].neighbours.push(source);
// // Source is NGram
} else {
if(isUndef(bipartiteN2D[source])) {
bipartiteN2D[source] = {
label: Nodes[source].label,
neighbours: []
};
}
if(isUndef(bipartiteD2N[target])) {
bipartiteD2N[target] = {
label: Nodes[target].label,
neighbours: []
};
}
bipartiteN2D[source].neighbours.push(target);
bipartiteD2N[target].neighbours.push(source);
}
}
}
}
}
function JSONFile( URL ) {
console.warn('URL:', url) ;
return $.ajax({
type: 'GET',
url: URL,
contentType: "application/json",
async: true,
success : function(data) {
pr("nodes:")
pr(data.nodes)
pr("---------")
pr("links: ")
pr(data.links)
if(!isUndef(getUrlParam.seed))seed=getUrlParam.seed;
parseSimpleJSON(data,seed)
},
error: function(){
console.log("lalalala")
console.log( URL )
pr("Page Not found. parseCustom, inside the IF");
}
});
}
function parseSimpleJSON( data , seed ) {
var i, j, k;
rand=new RVUniformC(seed);
//partialGraph.emptyGraph();
// Parse Attributes
// This is confusing, so I'll comment heavily
var nodesAttributes = []; // The list of attributes of the nodes of the graph that we build in json
var edgesAttributes = []; // The list of attributes of the edges of the graph that we build in json
//var attributesNodes = gexf.getElementsByTagName('attributes'); // In the gexf (that is an xml), the list of xml nodes 'attributes' (note the plural 's')
var nodesNodes = data.nodes // The list of xml nodes 'nodes' (plural)
labels = [];
numberOfDocs=0;
numberOfNGrams=0;
//Manually assigning ONE category
categories[catSoc]=catSoc;
categoriesIndex[0]=catSoc;
for(var i in nodesNodes) {
var color, label;
if(isUndef(nodesNodes[i].color)) color = "#800000";
if(isUndef(nodesNodes[i].label)) label = "node_"+i;
var node = ({
id: i ,
label:label,
size:1,
x:rand.getRandom(),
y:rand.getRandom(),
type:catSoc,
htmlCont:"",
color:color
}); // The graph node
pr(node)
Nodes[i] = node;
partialGraph.addNode( i , node );
}
var edgeId = 0;
var edgesNodes = data.links;
for(var i in edgesNodes) {
var source = edgesNodes[i].source;
var target = edgesNodes[i].target;
var indice=source+";"+target;
var edge = {
id: indice,
sourceID: source,
targetID: target,
lock : false,
label: "",
weight: (edgesNodes[i].w)?edgesNodes[i].w:1
};
if(edge.weight < minEdgeWeight) minEdgeWeight= edge.weight;
if(edge.weight > maxEdgeWeight) maxEdgeWeight= edge.weight;
idS=Nodes[edge.sourceID].type;
idT=Nodes[edge.targetID].type;
if(idS==catSoc && idT==catSoc) {
edge.label = "nodes1";
if(isUndef(nodes1[source])) {
nodes1[source] = {
label: Nodes[source].label,
neighbours: []
};
}
if(isUndef(nodes1[target])) {
nodes1[target] = {
label: Nodes[target].label,
neighbours: []
};
}
nodes1[source].neighbours.push(target);
nodes1[target].neighbours.push(source);
Edges[indice] = edge;
partialGraph.addEdge(indice,source,target,edge);
}
}
}
function extractFromJson(data,seed){
var i, j, k;
rand=new RVUniformC(seed);
//partialGraph.emptyGraph();
// Parse Attributes
// This is confusing, so I'll comment heavily
var nodesAttributes = []; // The list of attributes of the nodes of the graph that we build in json
var edgesAttributes = []; // The list of attributes of the edges of the graph that we build in json
//var attributesNodes = gexf.getElementsByTagName('attributes'); // In the gexf (that is an xml), the list of xml nodes 'attributes' (note the plural 's')
var nodesNodes = data.nodes // The list of xml nodes 'nodes' (plural)
labels = [];
numberOfDocs=0;
numberOfNGrams=0;
for (var uid in data.ID) egonode[uid] = data.ID[uid]
//Manually assigning categories
categories[catSoc]=catSoc;
categories[catSem]=catSem;
categoriesIndex[0]=catSoc;
categoriesIndex[1]=catSem;
for(var i in nodesNodes) {
if(nodesNodes[i].color) {
colorRaw = nodesNodes[i].color.split(",");
color = '#'+sigma.tools.rgbToHex(
parseFloat(colorRaw[2]),
parseFloat(colorRaw[1]),
parseFloat(colorRaw[0]));
//Colors inverted... Srsly??
} else color = "#800000";
var node = ({
id:i,
label:nodesNodes[i].label,
size:1,
x:rand.getRandom(),
y:rand.getRandom(),
// x:Math.random(),
// y:Math.random(),
type:"",
htmlCont:"",
color:color
}); // The graph node
if(nodesNodes[i].type=="Document"){
node.htmlCont = nodesNodes[i].content;
node.type="Document";
node.shape="square";
numberOfDocs++;
node.size=desirableScholarSize;
node.CC = nodesNodes[i].CC;
node.ACR = nodesNodes[i].ACR;
}
else {
node.type="NGram";
numberOfNGrams++;
node.size=parseInt(nodesNodes[i].term_occ).toFixed(2);
if(parseInt(node.size) < parseInt(minNodeSize)) minNodeSize= node.size;
if(parseInt(node.size) > parseInt(maxNodeSize)) maxNodeSize= node.size;
}
Nodes[i] = node;
}
for(var i in Nodes){
if(Nodes[i].type=="NGram") {
normalizedSize=desirableNodeSizeMIN+(Nodes[i].size-1)*((desirableNodeSizeMAX-desirableNodeSizeMIN)/(parseInt(maxNodeSize)-parseInt(minNodeSize)));
Nodes[i].size = ""+normalizedSize;
nodeK = Nodes[i];
otherGraph.addNode(i,nodeK);
}
else {
partialGraph.addNode(i,Nodes[i]);
updateSearchLabels(i,Nodes[i].label,Nodes[i].type);
}
}
var edgeId = 0;
var edgesNodes = data.links;
for(var i in edgesNodes) {
var source = edgesNodes[i].s;
var target = edgesNodes[i].t;
var indice=source+";"+target;
var edge = {
id: indice,
sourceID: source,
targetID: target,
lock : false,
label: "",
weight: edgesNodes[i].w
};
if(edge.weight < minEdgeWeight) minEdgeWeight= edge.weight;
if(edge.weight > maxEdgeWeight) maxEdgeWeight= edge.weight;
Edges[indice] = edge;
idS=Nodes[edge.sourceID].type;
idT=Nodes[edge.targetID].type;
if(idS==catSoc && idT==catSoc){
edge.label = "nodes1";
if(isUndef(nodes1[source])) {
nodes1[source] = {
label: Nodes[source].label,
neighbours: []
};
}
if(isUndef(nodes1[target])) {
nodes1[target] = {
label: Nodes[target].label,
neighbours: []
};
}
nodes1[source].neighbours.push(target);
nodes1[target].neighbours.push(source);
// social edges = 1
Edges[indice].bweight = edgesNodes[i].w;//realweight just in bigraph-weight
edge.weight = 1;
partialGraph.addEdge(indice,source,target,edge);
}
if(idS==catSem && idT==catSem){
edge.label = "nodes2";
if(isUndef(nodes2[source])) {
nodes2[source] = {
label: Nodes[source].label,
neighbours: []
};
}
if(isUndef(nodes2[target])) {
nodes2[target] = {
label: Nodes[target].label,
neighbours: []
};
}
nodes2[source].neighbours.push(target);
nodes2[target].neighbours.push(source);
otherGraph.addEdge(indice,source,target,edge);
}
if((idS==catSoc && idT==catSem)||(idS==catSem && idT==catSoc)) {
edge.label = "bipartite";
s = edge.sourceID
// // Source is Document
if(Nodes[s].type == catSoc) {
if(isUndef(bipartiteD2N[source])) {
bipartiteD2N[source] = {
label: Nodes[source].label,
neighbours: []
};
}
if(isUndef(bipartiteN2D[target])) {
bipartiteN2D[target] = {
label: Nodes[target].label,
neighbours: []
};
}
bipartiteD2N[source].neighbours.push(target);
bipartiteN2D[target].neighbours.push(source);
// // Source is NGram
} else {
if(isUndef(bipartiteN2D[source])) {
bipartiteN2D[source] = {
label: Nodes[source].label,
neighbours: []
};
}
if(isUndef(bipartiteD2N[target])) {
bipartiteD2N[target] = {
label: Nodes[target].label,
neighbours: []
};
}
bipartiteN2D[source].neighbours.push(target);
bipartiteD2N[target].neighbours.push(source);
}
}
}
}
//for socialgraph
function showMeSomeLabels(N){
/*======= Show some labels at the beginning =======*/
minIn=50,
maxIn=0,
minOut=50,
maxOut=0;
partialGraph.iterNodes(function(n){
if(n.hidden==false){
if(parseInt(n.inDegree) < minIn) minIn= n.inDegree;
if(parseInt(n.inDegree) > maxIn) maxIn= n.inDegree;
if(parseInt(n.outDegree) < minOut) minOut= n.outDegree;
if(parseInt(n.outDegree) > maxOut) maxOut= n.outDegree;
}
});
counter=0;
n = getVisibleNodes();
for(i=0;i<n.length;i++) {
if(n[i].hidden==false){
if(n[i].inDegree==minIn && n[i].forceLabel==false) {
n[i].forceLabel=true;
counter++;
}
if(n[i].inDegree==maxIn && n[i].forceLabel==false) {
n[i].forceLabel=true;
counter++;
}
if(n[i].outDegree==minOut && n[i].forceLabel==false) {
n[i].forceLabel=true;
counter++;
}
if(n[i].outDegree==maxOut && n[i].forceLabel==false) {
n[i].forceLabel=true;
counter++;
}
if(counter==N) break;
}
}
partialGraph.draw()
/*======= Show some labels at the beginning =======*/
}
function getnodes(){
return partialGraph._core.graph.nodes;
}
function getnodesIndex(){
return partialGraph._core.graph.nodesIndex;
}
function getedges(){
return partialGraph._core.graph.edges;
}
function getedgesIndex(){
return partialGraph._core.graph.edgesIndex;
}
function getVisibleEdges() {
return partialGraph._core.graph.edges.filter(function(e) {
return !e['hidden'];
});
}
function getVisibleNodes() {
return partialGraph._core.graph.nodes.filter(function(n) {
return !n['hidden'];
});
}
function getNodesByAtt(att) {
return partialGraph._core.graph.nodes.filter(function(n) {
return n['type']==att;
});
}
function getn(id){
return partialGraph._core.graph.nodesIndex[id];
}
function gete(id){
return partialGraph._core.graph.edgesIndex[id];
}
function find(label){
var results=[];
var nds=getnodesIndex();
label=label.toLowerCase()
for(var i in nds){
var n=nds[i];
if(n.hidden==false){
var possiblematch=n.label.toLowerCase()
if (possiblematch.indexOf(label)!==-1) {
results.push(n);
}
}
}
return results;
}
function exactfind(label) {
nds=getnodesIndex();
for(var i in nds){
n=nds[i];
if(!n.hidden){
if (n.label==label) {
return n;
}
}
}
return null;
}
function getNodeLabels(elems){
var labelss=[]
for(var i in elems){
var id=(!isUndef(elems[i].key))?elems[i].key:i
labelss.push(Nodes[id].label)
}
return labelss
}
function getNodeIDs(elems){
return Object.keys(elems)
}
function getSelections(){
params=[];
for(var i in selections){
params.push(Nodes[i].label);
}
return params;
}
//This receives an array not a dict!
// i added an excpt... why
function getNeighs(sels,arr){
neighDict={};
for(var i in sels) {
id = sels[i]
if(!isUndef(arr[id])) {
A=arr[id].neighbours;
for(var j in A){
neighDict[A[j]]=1
}
neighDict[id]=1;
}
}
return Object.keys(neighDict);
}//It returns an array not a dict!
//Using bipartiteN2D or bipartiteD2N
//This receives an array not a dict!
function getNeighs2(sels,arr){
neighDict={};
for(var i in sels) {
id = sels[i]
if(!isUndef(arr[id])) {
A=arr[id].neighbours;
for(var j in A){
neighDict[A[j]]=1
}
// neighDict[id]=1;
}
}
return Object.keys(neighDict);
}//It returns an array not a dict!
//to general utils
function getArrSubkeys(arr,id) {
var result = []
for(var i in arr) {
result.push(arr[i][id])
}
return result;
}
function getCountries(){
var nodes = getVisibleNodes();
var countries = {}
pr("in getCountries")
for(var i in nodes) {
theid = nodes[i].id;
// pr(i)
// pr(Nodes[theid])
// pr(theid+" : "+Nodes[theid].attr["CC"]+" , "+nodes[i].attr["ACR"])
if (Nodes[theid]["CC"]!="-")
countries[Nodes[theid]["CC"]]=1
// pr("")
}
return Object.keys(countries);
}
function getAcronyms() {
var nodes = getVisibleNodes();
var acrs = {}
pr("in getAcronyms")
for(var i in nodes) {
theid = nodes[i].id;
// pr(i)
// pr(nodes[i].id+" : "+nodes[i].attr["CC"]+" , "+nodes[i].attr["ACR"])
if (Nodes[theid]["ACR"]!="-")
acrs[Nodes[theid]["ACR"]]=1
// pr("")
}
return ( Object.keys(acrs) );
}
function clustersBy(daclass) {
if (daclass=="country") {
CCs = getCountries()
CCxID = {}
for(var i in CCs) {
code = CCs[i]
CCxID[code]=parseInt(i);
}
pr(CCxID)
var nodes = getVisibleNodes();
for(var i in nodes) {
nodes[i].color = Nodes[ nodes[i].id ].color;
}
colorList.sort(function(){ return Math.random()-0.5; });
// pr(colorList);
for(var i in nodes) {
cc = Nodes[nodes[i].id]["CC"]
if( !isUndef( cc ) && cc!="-" ) {
nodes[i].color = colorList[ CCxID[cc] ];
}
}
}
if (daclass=="acronym") {
CCs = getAcronyms()
CCxID = {}
for(var i in CCs) {
code = CCs[i]
CCxID[code]=parseInt(i);
}
pr(CCxID)
var nodes = getVisibleNodes();
for(var i in nodes) {
nodes[i].color = Nodes[ nodes[i].id ].color;
}
colorList.sort(function(){ return Math.random()-0.5; });
// pr(colorList);
for(var i in nodes) {
cc = Nodes[nodes[i].id]["ACR"]
if( !isUndef( cc ) && cc!="-" ) {
nodes[i].color = colorList[ CCxID[cc] ];
}
}
}
if (daclass=="default") {
var nodes = getVisibleNodes();
for(var i in nodes) {
nodes[i].color = Nodes[ nodes[i].id ].color;
}
}
partialGraph.refresh()
partialGraph.draw();
}
//just for fun
function makeEdgeWeightUndef() {
for(var e in partialGraph._core.graph.edges) {
partialGraph._core.graph.edges[e].weight=1;
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment