block by giorgi-ghviniashvili d9c7285153d75ebd4c99325d0f8a2e52

Force Stress Test

Full Screen

The mplate graph from the The University of Florida Sparse Matrix Collection.

This is a stress test of d3-force with 5,964 nodes and 68,115 edges. Self-edges were removed from the links array. Nodes are colored by their velocity.

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<style>
</style>
<canvas></canvas>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var width = 960,
    height = 800;

var linkColor = d3.scaleSequential(d3.interpolateMagma)
  .domain([240, -2])

var canvas = d3.select("canvas")
    .attr("width", width)
    .attr("height", height);

var context = canvas.node().getContext("2d");

var simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d) { return d.id; }).distance(8).strength(0.45))
    .force("charge", d3.forceManyBody().strength(-2).distanceMax(250))
    .force("center", d3.forceCenter(width / 2, height / 2));

var graph = {};

d3.text("mplate.mtx", function(error, raw) {
  if (error) throw error;

  var node_set = d3.set();

  var pairs = raw.split("\n")
    .slice(14)
    .map(function(d) { return d.split(" "); });

  pairs.forEach(function(d) {
    node_set.add(d[0]);
    node_set.add(d[1]);
  });

  graph.nodes = node_set.values().map(function(d) {
      return {
        id: d
      };
    });

  graph.links = pairs.map(function(d) {
      return {
        source: d[0],
        target: d[1]
      }
    })
    .filter(function(d) {
      return d.source !== d.target;
    });

  simulation
      .nodes(graph.nodes)

  simulation.force("link")
      .links(graph.links);

  d3.range(10).forEach(simulation.tick);

  simulation
      .on("tick", ticked);

  canvas.call(d3.drag()
          .container(canvas.node())
          .subject(dragsubject)
          .on("start", dragstarted)
          .on("drag", dragged)
          .on("end", dragended));

  function ticked() {
    context.clearRect(0, 0, width, height);

    context.globalAlpha = 0.15;
    context.beginPath();
    context.strokeStyle = "#777";
    graph.links.forEach(drawLink);
    context.stroke();

    context.globalAlpha = 1;
    graph.nodes.forEach(drawNode);
  }

  function dragsubject() {
    return simulation.find(d3.event.x, d3.event.y);
  }
});

function dragstarted() {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d3.event.subject.fx = d3.event.subject.x;
  d3.event.subject.fy = d3.event.subject.y;
}

function dragged() {
  d3.event.subject.fx = d3.event.x;
  d3.event.subject.fy = d3.event.y;
}

function dragended() {
  if (!d3.event.active) simulation.alphaTarget(0);
  d3.event.subject.fx = null;
  d3.event.subject.fy = null;
}

function drawLink(d) {
  context.moveTo(d.source.x, d.source.y);
  context.lineTo(d.target.x, d.target.y);
}

function drawNode(d) {
  context.fillStyle = d3.interpolateMagma(Math.sqrt(d.vx*d.vx + d.vy*d.vy)/3);
  context.fillRect(d.x-1, d.y-1, 2, 2);
}

</script>