Skip to content
This repository has been archived by the owner on May 4, 2022. It is now read-only.

Commit

Permalink
Update Sankey to be able to handle cycles
Browse files Browse the repository at this point in the history
See here for more details: d3/d3-plugins#39
  • Loading branch information
itay committed Sep 26, 2013
1 parent b6fb2be commit 349f8f7
Showing 1 changed file with 303 additions and 22 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
// A modified d3 sankey plugin
// This is taken verbatim from:
// https://github.com/kunalb/d3-plugins/blob/sankey/sankey/sankey.js
// Referenced from pull request:
// https://github.com/d3/d3-plugins/pull/39

d3.sankey = function() {
var sankey = {},
nodeWidth = 24,
nodePadding = 8,
size = [1, 1],
nodes = [],
links = [];
links = [],
components = [];

sankey.nodeWidth = function(_) {
if (!arguments.length) return nodeWidth;
Expand Down Expand Up @@ -39,9 +46,13 @@ d3.sankey = function() {
sankey.layout = function(iterations) {
computeNodeLinks();
computeNodeValues();

computeNodeStructure();
computeNodeBreadths();

computeNodeDepths(iterations);
computeLinkDepths();

return sankey;
};

Expand All @@ -50,6 +61,137 @@ d3.sankey = function() {
return sankey;
};

// A more involved path generator that requires 3 elements to render --
// It draws a starting element, intermediate and end element that are useful
// while drawing reverse links to get an appropriate fill.
//
// Each link is now an area and not a basic spline and no longer guarantees
// fixed width throughout.
//
// Sample usage:
//
// linkNodes = this._svg.append("g").selectAll(".link")
// .data(this.links)
// .enter().append("g")
// .attr("fill", "none")
// .attr("class", ".link")
// .sort(function(a, b) { return b.dy - a.dy; });
//
// linkNodePieces = [];
// for (var i = 0; i < 3; i++) {
// linkNodePieces[i] = linkNodes.append("path")
// .attr("class", ".linkPiece")
// .attr("d", path(i))
// .attr("fill", ...)
// }
sankey.reversibleLink = function() {
var curvature = .5;

// Used when source is behind target, the first and last paths are simple
// lines at the start and end node while the second path is the spline
function forwardLink(part, d) {
var x0 = d.source.x + d.source.dx,
x1 = d.target.x,
xi = d3.interpolateNumber(x0, x1),
x2 = xi(curvature),
x3 = xi(1 - curvature),
y0 = d.source.y + d.sy,
y1 = d.target.y + d.ty,
y2 = d.source.y + d.sy + d.dy,
y3 = d.target.y + d.ty + d.dy;

switch (part) {
case 0:
return "M" + x0 + "," + y0 + "L" + x0 + "," + (y0 + d.dy);

case 1:
return "M" + x0 + "," + y0
+ "C" + x2 + "," + y0 + " " + x3 + "," + y1 + " " + x1 + "," + y1
+ "L" + x1 + "," + y3
+ "C" + x3 + "," + y3 + " " + x2 + "," + y2 + " " + x0 + "," + y2
+ "Z";

case 2:
return "M" + x1 + "," + y1 + "L" + x1 + "," + (y1 + d.dy);
}
}

// Used for self loops and when the source is actually in front of the
// target; the first element is a turning path from the source to the
// destination, the second element connects the two twists and the last
// twists into the target element.
//
//
// /--Target
// \----------------------\
// Source--/
//
function backwardLink(part, d) {
var curveExtension = 30;
var curveDepth = 15;

function getDir(d) {
return d.source.y + d.sy > d.target.y + d.ty ? -1 : 1;
}

function p(x, y) {
return x + "," + y + " ";
}

var dt = getDir(d) * curveDepth,
x0 = d.source.x + d.source.dx,
y0 = d.source.y + d.sy,
x1 = d.target.x,
y1 = d.target.y + d.ty;

switch (part) {
case 0:
return "M" + p(x0, y0) +
"C" + p(x0, y0) +
p(x0 + curveExtension, y0) +
p(x0 + curveExtension, y0 + dt) +
"L" + p(x0 + curveExtension, y0 + dt + d.dy) +
"C" + p(x0 + curveExtension, y0 + d.dy) +
p(x0, y0 + d.dy) +
p(x0, y0 + d.dy) +
"Z";
case 1:
return "M" + p(x0 + curveExtension, y0 + dt) +
"C" + p(x0 + curveExtension, y0 + 3 * dt) +
p(x1 - curveExtension, y1 - 3 * dt) +
p(x1 - curveExtension, y1 - dt) +
"L" + p(x1 - curveExtension, y1 - dt + d.dy) +
"C" + p(x1 - curveExtension, y1 - 3 * dt + d.dy) +
p(x0 + curveExtension, y0 + 3 * dt + d.dy) +
p(x0 + curveExtension, y0 + dt + d.dy) +
"Z";

case 2:
return "M" + p(x1 - curveExtension, y1 - dt) +
"C" + p(x1 - curveExtension, y1) +
p(x1, y1) +
p(x1, y1) +
"L" + p(x1, y1 + d.dy) +
"C" + p(x1, y1 + d.dy) +
p(x1 - curveExtension, y1 + d.dy) +
p(x1 - curveExtension, y1 + d.dy - dt) +
"Z";
}
}

return function(part) {
return function(d) {
if (d.source.x < d.target.x) {
return forwardLink(part, d);
} else {
return backwardLink(part, d);
}
}
}
};

// The standard link path using a constant width spline that needs a
// single path element.
sankey.link = function() {
var curvature = .5;

Expand Down Expand Up @@ -83,6 +225,7 @@ d3.sankey = function() {
node.sourceLinks = [];
node.targetLinks = [];
});

links.forEach(function(link) {
var source = link.source,
target = link.target;
Expand All @@ -103,31 +246,169 @@ d3.sankey = function() {
});
}

// Iteratively assign the breadth (x-position) for each node.
// Nodes are assigned the maximum breadth of incoming neighbors plus one;
// nodes with no incoming links are assigned breadth zero, while
// nodes with no outgoing links are assigned the maximum breadth.
// Take the list of nodes and create a DAG of supervertices, each consisting
// of a strongly connected component of the graph
//
// Based off:
// http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
function computeNodeStructure() {
var nodeStack = [],
index = 0;

nodes.forEach(function(node) {
if (!node.index) {
connect(node);
}
});

function connect(node) {
node.index = index++;
node.lowIndex = node.index;
node.onStack = true;
nodeStack.push(node);

if (node.sourceLinks) {
node.sourceLinks.forEach(function(sourceLink){
var target = sourceLink.target;
if (!target.hasOwnProperty('index')) {
connect(target);
node.lowIndex = Math.min(node.lowIndex, target.lowIndex);
} else if (target.onStack) {
node.lowIndex = Math.min(node.lowIndex, target.index);
}
});

if (node.lowIndex === node.index) {
var component = [], currentNode;
do {
currentNode = nodeStack.pop()
currentNode.onStack = false;
component.push(currentNode);
} while (currentNode != node);
components.push({
root: node,
scc: component
});
}
}
}

components.forEach(function(component, i){
component.index = i;
component.scc.forEach(function(node) {
node.component = i;
});
});
}

// Assign the breadth (x-position) for each strongly connected component,
// followed by assigning breadth within the component.
function computeNodeBreadths() {
var remainingNodes = nodes,
nextNodes,
x = 0;

while (remainingNodes.length) {
nextNodes = [];
remainingNodes.forEach(function(node) {
node.x = x;
node.dx = nodeWidth;
node.sourceLinks.forEach(function(link) {
nextNodes.push(link.target);

layerComponents();

components.forEach(function(component, i){
bfs(component.root, function(node){
var result = node.sourceLinks
.filter(function(sourceLink){
return sourceLink.target.component == i;
})
.map(function(sourceLink){
return sourceLink.target;
});
return result;
});
});

var max = 0;
var componentsByBreadth = d3.nest()
.key(function(d) { return d.x; })
.sortKeys(d3.ascending)
.entries(components)
.map(function(d) { return d.values; });

var max = -1, nextMax = -1;
componentsByBreadth.forEach(function(c){
c.forEach(function(component){
component.x = max + 1;
component.scc.forEach(function(node){
node.x = component.x + node.x;
nextMax = Math.max(nextMax, node.x);
});
});
remainingNodes = nextNodes;
++x;
max = nextMax;
});


nodes
.filter(function(node) {
var outLinks = node.sourceLinks.filter(function(link){ return link.source.name != link.target.name; });
return (outLinks.length == 0);
})
.forEach(function(node) { node.x = max; })

scaleNodeBreadths((size[0] - nodeWidth) / Math.max(max, 1));

function flatten(a) {
return [].concat.apply([], a);
}

//
moveSinksRight(x);
scaleNodeBreadths((size[0] - nodeWidth) / (x - 1));
function layerComponents() {
var remainingComponents = components,
nextComponents,
visitedIndex,
x = 0;

while (remainingComponents.length) {
nextComponents = [];
visitedIndex = {};

remainingComponents.forEach(function(component) {
component.x = x;

component.scc.forEach(function(n) {
n.sourceLinks.forEach(function(l) {
if (!visitedIndex.hasOwnProperty(l.target.component) &&
l.target.component != component.index) {
nextComponents.push(components[l.target.component]);
visitedIndex[l.target.component] = true;
}
})
});
});

remainingComponents = nextComponents;
++x;
}
}

function bfs(node, extractTargets) {
var queue = [node], currentCount = 1, nextCount = 0;
var x = 0;

while(currentCount > 0) {
var currentNode = queue.shift();
currentCount--;

if (!currentNode.hasOwnProperty('x')) {
currentNode.x = x;
currentNode.dx = nodeWidth;

var targets = extractTargets(currentNode);

queue = queue.concat(targets);
nextCount += targets.length;
}


if (currentCount == 0) { // level change
x++;
currentCount = nextCount;
nextCount = 0;
}

}
}
}

function moveSourcesRight() {
Expand Down Expand Up @@ -289,4 +570,4 @@ d3.sankey = function() {
}

return sankey;
};
};

1 comment on commit 349f8f7

@arunep-aruneprasaath
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi Nice work.. If i update my sankey.js with this changes i am getting below error in console. Is there any other changes i need to do.

Error: Invalid value for attribute d="function (d) {
if (d.source.x < d.target.x) {
return forwardLink(part, d);
} else {
return backwardLink(part, d);
}
}"

Please sign in to comment.