Skip to content

Instantly share code, notes, and snippets.

@twedl
Last active January 7, 2016 03:48
Show Gist options
  • Save twedl/83783977b931aa60336a to your computer and use it in GitHub Desktop.
Save twedl/83783977b931aa60336a to your computer and use it in GitHub Desktop.
Uniform Attachment for Erdos-Renyi Graph

Visualize a dynamic uniform attachment model.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #000;
stroke-opacity: 1;
}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script>
var nodes=[], //[{ "id": 0 }],
links=[];
var width = 650,
height = 550;
var N=175; // nodes.
var p=Math.log(N)/N/5; // probability of edge.
//for (i = 0; i < N; i++) {
//
//}
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.nodes(nodes)
.links(links)
.charge(-50)
.linkDistance(30)
.size([width, height])
.on("tick", tick);
var link = svg.selectAll(".link");
link.data(links)
.enter().append("line")
.attr("class", "link");
var node = svg.selectAll(".node");
node.data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5);
function nodeStart() {
nodes.push({"id": i});
node = node.data(force.nodes(), function(d) { return d.id;});
node.enter().append("circle").attr("class", function(d) {
return "node" + d.id;
}).attr("r", 5);
node.exit().remove();
force.start();
}
function linkStart() {
console.log(force.links().push({source: i, target: j})); // need to add nodes too.
link = link.data(force.links()); //, function(d) { return d.source.id + "-" + d.target.id; });
link.enter().append("line").attr("class","link"); //.insert("line", ".node").attr("class", "link");
link.exit().remove();
force.start();
}
function tick() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
force.start();
}
var i=0,
j=0;
function update() {
if (i+1==N) {
clearInterval(int);
}
i++;
nodeStart();
for (j=0; j<i; j++) {
if (i!=j & Math.random() < p) {
linkStart();
}
}
// console.log('(i,j): (' + i + ',' + j + ')');
}
nodeStart();
linkStart();
var int = setInterval(update, 100);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment