Sigma.js - modifying node attributes in existing graph

6.8k Views Asked by At

I'm working on a project using sigma.js, in which I'd like to dynamically add and remove subgraphs from the main graph while forceAtlas2 is running. I'm a JS newbie, so my questions are probably JavaScript issues, but I can't get around them.

This is the function for loading a graph graph into the Sigma instance:

function loadGraph (json) {
    console.log ("load graph");
    sigInst.stopForceAtlas2();
    $.getJSON(json, function (data) {
        var edges = data.edges;
        var nodes = data.nodes;
        $.each(nodes, function (index, value) {
            addNode(value.label, value.x, value.y, value.id, value.size, value.color);
        });
        $.each(edges, function (index, value) {
            addEdge(value.source, value.target, value.id, value.weight);
        });
    });
    sigInst.draw(2,2,2);

}

this is the addNode function:

function addNode (label, x, y, id, size, color) {
if (!sigInst.hasNode(id)) {
    sigInst.addNode(id,{
        'x': x,
        'y': y,
        label: label,
        size:size,
        color: color
    }); 
    console.log ("added node " + id);
}
else {
    var nodeExisting = sigInst.getNodes(id);
    var exSize = parseInt(nodeExisting.size);
    console.log ("node " + id + " former size: "+ exSize);
    exSize += parseInt(size);
    nodeExisting.size = exSize;
    console.log ("node " + id + " size now: " + exSize);
}
sigInst.draw();

}

and the addEdge function:

function addEdge (source, target,id, weight) {
if (!sigInst.hasEdge(id)) {
    sigInst.addEdge(id, source, target, weight).draw();
}
else {
    var edgeExisting = sigInst.getEdges(id);
    //console.log("existing weight: " + edgeExisting.weight);
    var exSize = parseInt(edgeExisting.weight);
    exSize += parseInt(weight);
    edgeExisting.weight = exSize;
    //console.log("modified weight: " + edgeExisting.weight + " (" + edgeExisting.source + " -> " + edgeExisting.target + ")");
}

}

for this to work, I added two functions into sigma.min.js:

this.hasNode = function(id){return typeof(b.graph.nodesIndex[id]) != 'undefined';};

and

this.hasEdge = function (id) {return typeof(b.graph.edgesIndex[id])!='undefined';};

My problem is that addNode function doesn't really increase the size of an existing node. I come from Java, and I know that in JavaScript existing node is probably not passed by reference, so I can't modify a field and expect the sigInst object to reflect this, but I don't know how to do it. I'd be most grateful if anyone could help. Thanks in advance!

1

There are 1 best solutions below

1
On

OK, solved: i added two functions to sigma.min.js:

this.setEdgeWeight = function(id,n){b.graph.edgesIndex[id].weight=n;}

and

this.setNodeSize = function(id,n){b.graph.nodesIndex[id].size=n;};

I was apparently lazy. Maybe someone can benefit from these functions.