diff --git a/README.md b/README.md index be26b20..814351f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # Reorder.js -[Reorder.js](http://www.reorderjs.org/) is a JavaScript library for reordering matrices. +[Reorder.js](https://github.com/jdfekete/reorder.js/) is a JavaScript library for reordering matrices. + +Want to learn more? [See the wiki.](https://github.com/jdfekete/reorder.js/wiki) ## Development diff --git a/src/graph2distmat.js b/src/graph2distmat.js new file mode 100644 index 0000000..42826ef --- /dev/null +++ b/src/graph2distmat.js @@ -0,0 +1,37 @@ +// Converts a graph with weighted edges (weight in l.value) +// into a distance matrix suitable for reordering with e.g. +// Optimal Leaf Ordering. + +function distmat2valuemat(distmat) { + var n = distmat.length, + valuemat = reorder.zeroes(n, n), + max_dist = reorder.distmax(distmat), + i, j; + + for (i = 0; i < n; i++) { + for (j = i; j < n; j++) { + valuemat[j][i] = valuemat[i][j] = 1+max_dist - distmat[i][j]; + } + } + return valuemat; +} +reorder.distmat2valuemat = distmat2valuemat; + +reorder.graph2valuemats = function(graph, comps) { + if (! comps) + comps = graph.components(); + + var dists = reorder.all_pairs_distance(graph, comps); + return dists.map(distmat2valuemat); +}; + +reorder.valuemats_reorder = function(valuemats, leaforder, comps) { + var orders = valuemats.map(leaforder); + + if (comps) { + orders = orders.map(function(d, i) { + return reorder.permute(comps[i], d); + }); + } + return orders.reduce(reorder.flatten); +}; diff --git a/test/graph2distmat-test.js b/test/graph2distmat-test.js new file mode 100644 index 0000000..cca7f21 --- /dev/null +++ b/test/graph2distmat-test.js @@ -0,0 +1,53 @@ +require("science"); +require("../reorder.v1"); +require("../reorder.v1"); + +var vows = require("vows"), + assert = require("assert"); +var seedrandom = require('seedrandom'); +Math.seedrandom('reorder'); + +var suite = vows.describe("reorder.graph2distmat"); + +suite.addBatch({ + "graph2distmat": { + "simple": function() { + var mat = [ + [0, 1, 0], + [1, 0, 1], + [0, 1, 0] + ], + dist = [ + [0, 1, 2], + [1, 0, 1], + [2, 1, 0] + ]; + var graph = reorder.mat2graph(mat); + assert.equal(graph.nodes().length, 3); + assert.equal(graph.links().length, 2); + var dists = reorder.all_pairs_distance(graph); + assert.deepEqual(dists[0], dist); + var valuemat = reorder.distmat2valuemat(dist); + assert.deepEqual(valuemat, + [[3, 2, 1], + [2, 3, 2], + [1, 2, 3]]); + // var max_link = graph.links().reduce( + // function(a, b) { + // return a.value > b.value ? a : b; + // }), + // max_value = max_link ? max_link.value : 0; + // var links = graph.links() + // .map(function(l) { + // return { + // value: (max_value - l.value)/max_value, + // source: l.source.index, + // target: l.target.index + // }; + // }); + // console.log(links); + } + } +}); + +suite.export(module);