Non numeric node IDs
sscarduzio opened this issue · 1 comments
sscarduzio commented
This would be infinitely more practical if I could add nodes and edges by unique string ID rather than numbers.
For example, G6 graph visualization library works exclusively with string IDs.
blakelapierre commented
Here's my attempt so far. I'll put it in a helper package if I get my project working correctly.
This seems to work ok until I try using the BellmanFord algorith on a larger graph (hundreds of nodes and edges)....
const g = createWeightedDiGraph([
['btc', 'usd', -Math.log(20549.38), -Math.log(1/20549.38)]
]);
function createWeightedDiGraph(edgeInfo) {
const labels = edgeInfo.reduce((acc, [n1, n2, weight]) => {
const indices = [acc.symbolMap[n1], acc.symbolMap[n2]];
if (indices[0] === undefined) {
const i = indices[0] = acc.symbolArray.length;
acc.symbolMap[n1] = i;
acc.symbolArray.push(n1);
}
if (indices[1] === undefined) {
const i = indices[1] = acc.symbolArray.length;
acc.symbolMap[n2] = i;
acc.symbolArray.push(n2);
}
return acc;
}, {symbolMap: {}, symbolArray: []});
//edgeInfo.forEach(())
const g = new jsgraphs.WeightedDiGraph(labels.symbolArray.length);
edgeInfo.forEach(([n1, n2, weight, rweight]) => {
const i1 = labels.symbolMap[n1],
i2 = labels.symbolMap[n2];
if (weight !== undefined) {
console.log('adding edge', n1, '->', n2, '(', weight, ')');
g.addEdge(new jsgraphs.Edge(i1, i2, weight));
}
if (rweight !== undefined) {
console.log('adding edge', n2, '->', n1, '(', rweight, ')');
g.addEdge(new jsgraphs.Edge(i2, i1, rweight));
}
g.node(i1).label = n1;
g.node(i2).label = n2;
});
return {g, labels};
}