-
Notifications
You must be signed in to change notification settings - Fork 3
/
avalanche2d.html
542 lines (492 loc) · 21.2 KB
/
avalanche2d.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
<!DOCTYPE html>
<html>
<head>
<title>Avalanche-JS Demo</title>
<link href="stylesheets/style.css" rel="stylesheet" type="text/css"/>
<script src="lib/sprintf.js" type="text/javascript" ></script>
<script src="src/grapher.js" type="text/javascript" ></script>
<script src="lib/d3/d3.js" type="text/javascript" ></script>
<style type="text/css">
#patchesCanvas {
width:400px;
height:400px;
padding:0px;
background-color:lightgray;
color:gray;
border: solid 1px #cccccc
}
</style>
<script type="text/javascript">
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
return window.setTimeout(callback, 1000/60);
};
})();
window.cancelRequestAnimFrame = (function() {
return window.cancelCancelRequestAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
window.clearTimeout;
})();
// a simple JavaScript source code loader
function myRequire(src, callback){
if (src.constructor == Array) {
var libraries = src;
} else {
var libraries = [src];
}
var script = document.createElement("script")
script.type = "text/javascript";
// IE
var ie = false;
script.onreadystatechange = function () {
ie = true;
if (script.readyState === 'loaded' || script.readyState == 'complete') {
script.onreadystatechange = null;
libraries.shift();
if (libraries.length > 0) {
myRequire(libraries)
}
if (callback) {
callback();
}
}
}
// Not IE
script.onload = function () {
if (!ie) {
libraries.shift();
if (libraries.length > 0) {
myRequire(libraries)
}
if (callback) {
callback();
}
}
}
script.src = libraries[0];
document.getElementsByTagName("head")[0].appendChild(script);
};
</script>
</head>
<div id="container">
<div id="header-inner">
<h1 id="title">Avalanche-JS Demo</h1>
<p>
A partial <a href='https://github.com/stepheneb/avalanche2d-js'>JavaScript adaptation</a>
of Bob Tinker's <a href='http://ccl.northwestern.edu/netlogo/'>NetLogo</a> model
<a href = 'nlogo/Bureaucrats.v6.nlogo'>Bureaucrats.v6</a> exploring
<a href="http://en.wikipedia.org/wiki/Self-organized_criticality">Self-Organised Criticality</a>.
</p>
<blockquote>
The mathematics of avalanche size and frequency follows a power law that can be simulated to
a first approximation by any system that exhibits self-organized criticality (SOC). In "How
Nature Works" Per Bak reports a simplified model of a sandpile that he, Chao Tang, and Curt
Wiesenfeld developed that shows SOC, the so-called BTW model. Bak also mentions that
Grassberger describes a representation of this model that is fanciful but equivalent to the
BTW model. Imagine an N-by-N grid of office desks and a bureaucrat sitting at each. A folder
is randomly assigned to one desk. The bureaucrat does nothing until four or more folders are
on his desk at which time he sends one to each of his four nearest neighbors. Any bureaucrat
sitting at the edge of this array throws a folder out the window if there is no desk to send
it to. Sometimes, adding one folder can cause multiple redistributions of folders as one
bureaucrat's actions causes neighbors to exceed three folders, which then ripples through
the office. In principle, just adding one new folder might involve redistribution at every
desk, sometimes multiple times.
</blockquote>
<p>
Seth Tisue, the lead NetLogo developer contributed <a href="nlogo/Bureaucrats-fast.nlogo">
Bureaucrats-fast</a> a simplified re-write of <a href='nlogo/Bureaucrats.v6.nlogo'>Bureaucrats.v6</a>
that runs about 20 times as fast as the original. Bureaucrats-fast is more appropriate to use when
comparing performance with this JavaScript adaptation.
</p>
<p>
Testing Oct 21 2011 show this JavaScript adaptation runs about 15 times faster than
<a href="nlogo/Bureaucrats-fast.nlogo">Bureaucrats-fast</a> in NetLogo 5.0RC2
when displaying folders and graphing and about 8 times faster running just the
computational model (<i>Chrome 14.0.835.186 on a Mac OS X 10.6.8 system with a
2.66 GHz Intel Core i7</i>).
<p>
<p>
The initial array of desks with folders consists of 100x100 cells. A yellow cell
indicates two folders on the desk, a blue cell is zero, green one, and red three
folders. The model will automatically stop after 5000 model steps if you leave it
running.
</p>
</div>
<div id="content">
<div id="webglCanvasContainer">
<ul id="visualizations" class="hlist">
<li>
<p>Avalanche-JS Model: Rendered using an HTML5 canvas</p>
<canvas id="patchesCanvas"></canvas>
</li>
<li>
<p>Average Number of folders on a desk</p>
<div id='chart'></div>
</li>
</ul>
<ul class="hlist">
<li>
<form id="step-model">
<fieldset>
<legend>Step</legend>
<label><input type="radio" name="step" value="stop" checked> Stop</input></label>
<label><input type="radio" name="step" value="step"> Step</input></label>
<label><input type="radio" name="step" value="go"> Go</input></label>
<label><input type="radio" name="step" value="reset"> Reset</input></label>
</fieldset>
</form>
</li>
<li>
<fieldset>
<legend>Desk Array Size</legend>
<select id="select-desk-array-size">
<option value="50">50x50</option>
<option value="100" selected>100x100</option>
<option value="200">200x200</option>
<option value="400">400x400</option>
</select>
</fieldset>
</li>
<li>
<form id="show-me">
<fieldset>
<legend>Rendering</legend>
<label><input id="show-visualization" type="checkbox" checked/> Visualization</label>
<label><input id="show-graph" type="checkbox" checked/> Graph</label>
<label><input id="show-data-table" type="checkbox"/> Folder-Desk Array</label>
</fieldset>
</form>
</li>
<li>
<fieldset>
<legend>JavaScript Array Type</legend>
<select id="select-array-type">
<option value="regular">Regular</option>
<option value="" disabled="disabled">Typed Arrays ...</option>
<option value="Uint8Array">Uint8Array</option>
<option value="Uint16Array">Uint16Array</option>
<option value="Uint32Array">Uint32Array</option>
<option value="Int8Array">Int8Array</option>
<option value="Int16Array">Int16Array</option>
<option value="Int32Array">Int32Array</option>
<option value="Float32Array">Float32Array</option>
<option value="Float64Array">Float64Array</option>
</select>
</fieldset>
</li>
<li id="step-model-warning"></li>
</ul>
</div>
<div id="stats"></div>
<div id="aloop-output"></div>
<div id="info">
<h3>About the Graph Interface built with the JavaScript library
<a href='http://mbostock.github.com/d3/'>d3.js</a></h3>
<ul>
<li><b>Translate/Pan:</b> drag on the graph canvas.</li>
<li><b>Zoom in:</b> double-click or swipe up with two fingers</li>
<li><b>Zoom out:</b> shift-double-click or swipe down with two fingers</li>
<li><b>Re-scale and axis:</b> drag on one of the X or Y axis numeric labels</li>
<li><b>Select data point:</b> click on a data point to select it</li>
<li><b>Change data point:</b> drag a selected data point to change it's value</li>
<li><b>Delete data point:</b> select data point and press the delete or backspace key</li>
<li><b>Add data point:</b> hold ALT/Option key down and click an empty area of the graph to add a data point</li>
</ul>
<h3>References</h3>
<p><a href="http://jasss.soc.surrey.ac.uk/4/4/reviews/bak.html">Review of: How Nature Works: The Science of Self-Organised Criticality, Per Bak, New York, NY: Copernicus Press 1996</a></p>
<p><a href="http://books.google.com/books?id=eBZbupdVnYAC&pg=PA94&lpg=PA94&dq=Grassberger++bureaucrat&source=bl&ots=XR7W1E61Wa&sig=06HmPg4d9YyBUz63RIphjUza1ik&hl=en&ei=MxGVTvThPIjk0QG4npnGBw&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBoQ6AEwAA#v=onepage&q=Grassberger%20%20bureaucrat&f=false">Self organized criticality in earth systems By Stefan Hergarten, page 94</a></p>
<p><a href="http://www.cmth.ph.ic.ac.uk/people/k.christensen/papers/preprints/preprint_btw.pdf">On the avalanche size distribution in the BTW model</a></p>
<h3>Getting a browser that supports JavaScript Typed Arrays</h3>
<div id="getting-webgl">
<p>
On some browsers using <a href=" https://developer.mozilla.org/en/JavaScript_typed_arrays">JavaScript Typed Arrays</a>
may be faster than using regular JavaScript Arrays. Typed Arrays are available in browsers that
are <a href='http://learningwebgl.com/blog/?p=11'>WebGL-enabled</a>. Get more information about
whether your browser supports WebGL here: <a href="http://get.webgl.org/">http://get.webgl.org/</a>.
</p>
</div>
<h3>Folder-Desk Data Array:</h3>
<pre id="folder-data"></pre>
</div>
</div>
<script type="text/javascript">
window.onload=function() {
myRequire([ 'src/avalanche2d.js' ],
function() {
var webgl = !!window.WebGLRenderingContext;
var select_array_type = document.getElementById("select-array-type");
var select_array_type_choices = select_array_type.getElementsByTagName("option")
var safari_browser = false;
var chrome_browser = navigator.userAgent.toLowerCase().indexOf('chrome') > 0;
if (!chrome_browser) {
safari_browser = navigator.userAgent.toLowerCase().indexOf('safari') > 0;
};
if (webgl) {
select_array_type.value = safari_browser ? "regular" : "Uint8Array";
} else {
for(var i=2; i < select_array_type_choices.length; i++) {
select_array_type_choices[i].disabled = true;
}
};
var canvas = document.getElementById("patchesCanvas");
var model, array_selection;
var folder_size = 100;
var max_model_step = folder_size * folder_size / 2;
var model_options = { model: { nx: folder_size, ny: folder_size, initial_value: 2 }};
function selectArrayTypeChange() {
array_selection = select_array_type.value;
model = new avalanche2d.Model(canvas, model_options, array_selection);
};
select_array_type.onchange = selectArrayTypeChange;
select_array_type.onchange();
var graph_data = [2];
var graph = grapher.graph({
"title": null,
"xlabel": "Model Step Count",
"xmin": 0, "xmax": 5000,
"ylabel": null,
"ymin": 2.0, "ymax": 2.2,
"dataset": graph_data
});
var select_desk_array_size = document.getElementById("select-desk-array-size");
var select_desk_array_size_choices = select_array_type.getElementsByTagName("option")
function selectDeskArraySizeChange() {
folder_size = +select_desk_array_size.value;
max_model_step = folder_size * folder_size / 2;
model_options = { model: { nx: folder_size, ny: folder_size, initial_value: 2 }};
model = new avalanche2d.Model(canvas, model_options, array_selection);
graph_data = [2];
graph.change_xaxis(max_model_step);
modelReset();
};
select_desk_array_size.onchange = selectDeskArraySizeChange;
// select_desk_array_size.onchange();
var visualizations = document.getElementById("visualizations");
var folder_data = document.getElementById("folder-data");
var step_model = document.getElementById("step-model");
var step_model_inputs = step_model.getElementsByTagName("input")
var show_visualization = document.getElementById("show-visualization");
var show_graph = document.getElementById("show-graph");
var show_data_table = document.getElementById("show-data-table");
var step_model_warning = document.getElementById("step-model-warning");
var stats = document.getElementById("stats");
var run_mode;
var start_time = +new Date();
var step_time = +new Date();
var last_step_time = step_time;
var step_duration = 0;
var step_duration_max = 0;
var step_start = 0;
var average_step_rate;
var foldersRunningAverage;
var loop_start, loop_time, loop_elapsed, previous_loop_start, animation_loop_timing;
function displayStats() {
average_step_rate = model.indexOfStep / (step_time - start_time) * 1000
stats.textContent = 'avalanches: ' + model.indexOfStep +
sprintf(", rate: %5.1f (steps/s)", average_step_rate) +
sprintf(", last sample time: %3f (ms)", step_duration) +
sprintf(", loop compute maximum: %3f", model_loop_time) +
sprintf(", anim loop timing: %3f", animation_loop_timing) +
sprintf(", folders: %2.3f (ave)", model.averageFolders);
};
var modelRunRequest;
var display_method;
function modelController() {
for(var i = 0; i < this.elements.length; i++)
if (this.elements[i].checked) run_mode = this.elements[i].value;
switch(run_mode) {
case "stop":
modelStop();
break;
case "step":
modelStep();
break;
case "go":
modelGo();
break;
case "reset":
modelReset();
break;
}
};
function modelStop() {
run_mode = "stop";
running = false;
if (modelRunRequest) cancelRequestAnimFrame(modelRunRequest);
displayStats();
if (!show_visualization.checked) {
model.renderFolderCanvas();
};
graph.hide_canvas();
graph.new_data(graph_data);
step_model_inputs[0].checked = true;
};
function modelStep() {
if (modelRunRequest) cancelRequestAnimFrame(modelRunRequest);
running = false;
runModelStep();
if (!show_visualization.checked) {
displayStats();
model.renderFolderCanvas();
};
graph.hide_canvas();
graph.new_data(graph_data);
if (model.indexOfStep >= max_model_step) displayResetWarning();
step_model_inputs[0].checked = true;
};
function modelGo() {
running = true;
if (model.indexOfStep >= max_model_step) {
displayResetWarning();
step_model_inputs[0].checked = true;
} else {
start_time = +new Date();
if (show_graph.checked) {
graph.show_canvas();
};
previous_loop_start = +new Date();
initial_model_loop_time = model_loop_time;
model_loop_goal = model_loop_time * model_loop_bump_factor;
animation_loop_timing = aloop_minimum;
if (show_visualization.checked || show_graph.checked || show_data_table.checked) {
modelRunRequest = requestAnimFrame(runModelLoop, visualizations);
} else {
while (model.indexOfStep < max_model_step) {
model.nextStep();
graph_data.push(model.averageFolders);
};
step_time = +new Date();
modelStop();
}
model.renderFolderTable(folder_data);
}
};
function modelReset() {
if (modelRunRequest) cancelRequestAnimFrame(modelRunRequest);
model.reset();
model.renderFolderCanvas();
folder_data.innerHTML = '';
stats.innerHTML = '';
step_model_warning.innerHTML = null;
graph.hide_canvas();
graph.clear_canvas();
graph_data = [2];
graph.new_data(graph_data);
step_model_inputs[0].checked = true;
}
function displayResetWarning() {
step_model_warning.innerHTML = "<fieldset><legend>Note</legend>Reset the model to start again.</fieldset>"
};
step_model.onchange = modelController;
model.renderFolderCanvas();
function displayGraph() {
if (show_graph.checked) {
graph.new_data(graph_data);
} else {
};
}
show_graph.onchange = displayGraph;
function displayFolderTable() {
if (show_data_table.checked) {
model.renderFolderTable(folder_data);
} else {
folder_data.innerHTML = '';
};
}
show_data_table.onchange = displayFolderTable;
function runModelStep() {
last_step_time = +new Date(step_time);
model.nextStep();
graph_data.push(model.averageFolders);
if (show_visualization.checked) model.renderFolderCanvas();
if (show_graph.checked) graph.add_canvas_point(model.averageFolders);
if (show_data_table.checked) model.renderFolderTable(folder_data);
step_time = +new Date();
step_duration = step_time - last_step_time;
if (show_visualization.checked) displayStats();
};
function runModelStepWithoutVisualization() {
last_step_time = +new Date(step_time);
model.nextStep();
graph_data.push(model.averageFolders);
if (show_graph.checked) graph.add_canvas_point(model.averageFolders);
step_time = +new Date();
step_duration = step_time - last_step_time;
};
var initial_model_loop_time = 13;
var model_loop_bump_factor = 1.2;
var model_loop_time = initial_model_loop_time;
var model_loop_goal = model_loop_time * model_loop_bump_factor;
var average_loop_time = 0, max_loop_time = 0;
function runModelLoop(){
if (model.indexOfStep < max_model_step && running) {
loop_start = +new Date();
animation_loop_timing = loop_start - previous_loop_start;
modelRunRequest = requestAnimFrame(runModelLoop, visualizations);
step_duration_max = 0;
runModelStep();
if (step_duration > step_duration_max) step_duration_max = step_duration;
loop_time = +new Date();
loop_elapsed = loop_time - loop_start;
while (loop_elapsed < model_loop_time) {
runModelStepWithoutVisualization();
if (step_duration > step_duration_max) step_duration_max = step_duration;
loop_time = +new Date()
loop_elapsed = loop_time - loop_start;
if (model.indexOfStep >= max_model_step) {
running = false;
break;
};
};
if (animation_loop_timing > model_loop_goal && loop_elapsed < model_loop_goal) {
model_loop_time++;
} else {
if (model_loop_goal > aloop_minimum) model_loop_time--;
};
model_loop_goal = model_loop_time * model_loop_bump_factor;
previous_loop_start = loop_start;
} else {
modelStop()
}
};
var aloop = 0;
var aloop_max_count = 20;
var aloop_timings = [];
var aloop_average = 0;
var aloop_minimum = 16;
var aloop_output = document.getElementById("aloop-output");
function measureAnimationLoop() {
if (aloop <= aloop_max_count) {
loop_time = +new Date();
requestAnimFrame(measureAnimationLoop, visualizations);
aloop_timings[aloop] = loop_time - loop_start;
aloop++;
loop_start = loop_time;
} else {
aloop_timings.shift();
aloop_minimum = Math.min.apply(null, aloop_timings)
var str = "Animation loop timing measurements for this browser: ";
aloop_output.innerHTML = str + aloop_timings.join(", ");
}
};
function startAnimationLoopMeasurement() {
aloop = 0;
aloop_timings = [];
loop_start = +new Date();
requestAnimFrame(measureAnimationLoop, visualizations);
};
startAnimationLoopMeasurement();
});
};
</script>
</body>
</html>