UNPKG

2.63 kBJavaScriptView Raw
1/**
2 * Created by Alex on 5/20/2015.
3 */
4
5function loadJSON(path, success, error) {
6 var xhr = new XMLHttpRequest();
7 xhr.onreadystatechange = function () {
8 if (xhr.readyState === 4) {
9 if (xhr.status === 200) {
10 success(JSON.parse(xhr.responseText));
11 }
12 else {
13 error(xhr);
14 }
15 }
16 };
17 xhr.open('GET', path, true);
18 xhr.send();
19}
20
21
22function getScaleFreeNetwork(nodeCount) {
23 var nodes = [];
24 var edges = [];
25 var connectionCount = [];
26
27 // randomly create some nodes and edges
28 for (var i = 0; i < nodeCount; i++) {
29 nodes.push({
30 id: i,
31 label: String(i)
32 });
33
34 connectionCount[i] = 0;
35
36 // create edges in a scale-free-network way
37 if (i == 1) {
38 var from = i;
39 var to = 0;
40 edges.push({
41 from: from,
42 to: to
43 });
44 connectionCount[from]++;
45 connectionCount[to]++;
46 }
47 else if (i > 1) {
48 var conn = edges.length * 2;
49 var rand = Math.floor(Math.random() * conn);
50 var cum = 0;
51 var j = 0;
52 while (j < connectionCount.length && cum < rand) {
53 cum += connectionCount[j];
54 j++;
55 }
56
57
58 var from = i;
59 var to = j;
60 edges.push({
61 from: from,
62 to: to
63 });
64 connectionCount[from]++;
65 connectionCount[to]++;
66 }
67 }
68
69 return {nodes:nodes, edges:edges};
70}
71
72var randomSeed = 764; // Math.round(Math.random()*1000);
73function seededRandom() {
74 var x = Math.sin(randomSeed++) * 10000;
75 return x - Math.floor(x);
76}
77
78function getScaleFreeNetworkSeeded(nodeCount, seed) {
79 if (seed) {
80 randomSeed = Number(seed);
81 }
82 var nodes = [];
83 var edges = [];
84 var connectionCount = [];
85 var edgesId = 0;
86
87
88 // randomly create some nodes and edges
89 for (var i = 0; i < nodeCount; i++) {
90 nodes.push({
91 id: i,
92 label: String(i)
93 });
94
95 connectionCount[i] = 0;
96
97 // create edges in a scale-free-network way
98 if (i == 1) {
99 var from = i;
100 var to = 0;
101 edges.push({
102 id: edgesId++,
103 from: from,
104 to: to
105 });
106 connectionCount[from]++;
107 connectionCount[to]++;
108 }
109 else if (i > 1) {
110 var conn = edges.length * 2;
111 var rand = Math.floor(seededRandom() * conn);
112 var cum = 0;
113 var j = 0;
114 while (j < connectionCount.length && cum < rand) {
115 cum += connectionCount[j];
116 j++;
117 }
118
119
120 var from = i;
121 var to = j;
122 edges.push({
123 id: edgesId++,
124 from: from,
125 to: to
126 });
127 connectionCount[from]++;
128 connectionCount[to]++;
129 }
130 }
131
132 return {nodes:nodes, edges:edges};
133}
\No newline at end of file