-
Notifications
You must be signed in to change notification settings - Fork 1
/
morphogenesis.html
657 lines (558 loc) · 21 KB
/
morphogenesis.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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
<!DOCTYPE html><!--{{{-->
<html>
<head>
<title>Morphogenesis</title>
<meta charset="utf-8">
<script type="text/javascript" src="d3.v3.js"></script>
<script type="text/javascript" src="underscore.js"></script>
<link type="text/css" rel="stylesheet" href="voronoi.css"/>
</head>
<body>
<input id='zoomin' type='button' onclick='splitAllNodesA_AA()' value = 'A --> A, A' />
<input id='zoomin' type='button' onclick='splitAllNodesB_BA()' value = 'B --> B, A' />
<br />
<input id='plause' type='button' style="width:5em" onclick='stop()' value='pause' />
<!--<input id='generating' type='button' style="width:9em" onclick='stopGen()' value='stop generating' />-->
<input id='toggleMouseHighlighting' type='button' style="width:13em" onclick='toggleMouseHighlighting()' value='remove highlights' />
<ul id="casting">
Casting:
<!--<li><label><input type="radio" name="casting" value="multi"/>Multi Cast</li>-->
<!--<li><label><input type="radio" name="casting" value="mono"/>Mono Cast</li>-->
<li><label><input type="radio" name="casting" value="monoToEdge" checked="checked"/>Random Walk Until Reaching An Edge Cell</li>
<!--<li><label><input type="radio" name="casting" value="monoToEdgeWithSpine" checked="checked"/>Walk to edge, then make head and spine</li>-->
<li><label><input type="radio" name="casting" value="automation" checked="checked"/>Start Automation (click on edge cell) <input id='step' type='button' style="width:4em" onclick='automateIteration()' value='iterate' /></li>
</ul>
<br /><!--}}}-->
<script type="text/javascript">
//{{{TODO BEFORE PUBLISHING!:
// - get rid of this todo section
// - link to the paper I wrote (upload to mattwoelk.ca first)
// Allow nodes to choose their state depending on the state of their neighbours.
// - make this easy to work with a nice architecture.
// Implement the following:
// Cell differentiation: These are the options we see in nature
// 1. Symmetric cell division --> two identical cells
// 2. Asymmetric cell division --> two daughter cells of different types (also different from the mother cell)
// 3. Stem cell asymmetric division --> one daughter like the mother, the other different
// 4. No cell division --> mysterious process called "induction". Changes the cell to a new type
// 1. A -> A, A [done]
// 2. A -> B, C []
// 3. A -> A, B [done]
// 4. A -> B [done]
// Action Plan:
// make a few head cells.
// use those head cells to make a spine structure
// use relation to the head and spine to make arms on either side of the spine
// TODO }}}
//{{{ VARIABLES
var generating = false;
var generationPeriod = 500;
var paused = false;
var showingMouseHighlights = false;
var startingQuantity = 0; //6 is best
var headParent = 0;
//document.getElementById('generating').value = generating ? 'stop generating' : 'start simulation';
document.getElementById('plause').value = paused ? 'play' : 'pause';
document.getElementById('toggleMouseHighlighting').value = showingMouseHighlights ? 'remove mouse highlighting' : 'engage mouse highlighting';
var w = 860;
var h = 430;
var fill = d3.scale.category10();
var nodes = []; // this is treated like a global variable
//var links = []; // "global" variable, links between the nodes, by index.
var foci = {x: w/2, y: h/2};
var cellRadius = 34; //34 for charge strength of -30, distance of 20, and gravity 0.05
var nucleusradius = 7;
var vis = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h)
.attr("class", "PiYG");
//defaults: size 1×1
// friction 0.9
// distance 20
// charge strength -30
// gravity strength 0.1
// and theta parameter 0.8
var force = d3.layout.force()
.nodes(nodes)
//.linkDistance(0) // this affected nothing
.links([])
// .linkStrength() // TODO: could be useful someday
//.linkDistance(cellRadius)
.friction(0.85)
.gravity(0.05)
.size([w, h]);
var clips = vis.append("svg:clipPath");
// usage: colors[type/state]
var colors = {
"normal" : "#aaa", // grey,
"head" : "#000", // black,
"spine" : "#FC8D62", // orangish,
"right" : "#8DA0CB", // blueish,
"left" : "#66C2A5", // greenish,
"indicator" : "#ddd",
"deselected" : "#000",
"interest" : "#000",
"selected" : "#F00",
}
// VARIABLES }}}
//{{{ TICK
force.on("tick", function(e) {
// Push different nodes in different directions for clustering.
//var k = 0.010 * e.alpha;
//nodes.forEach(function(o, i) {
// if (o.type === "head") {
// if (i === headParent) {
// //console.log("unconsolable");
// }
// var distx = 20;
// var disty = 20;
// var distx = nodes[headParent].x - o.x;
// var disty = nodes[headParent].y - o.y;
// o.y += disty * k;
// o.x += distx * k;
// }
//});
// ENTER voronoi //
vis.selectAll("path")
.data(d3.geom.voronoi(_.map(nodes, function (d) { return [d.x, d.y]; })))
.enter().append("path")
.attr("clip-path", function (d, i) { return "url(#clip"+i+")"; })
.attr("class", function(d, i) { return i ? "q" + (i % 9) + "-9" : null; })
.on("mouseover", function (d, i) {
if (showingMouseHighlights) {
return highlightNeighboursIncludingSelf(i);
} else {
return;
}})
.on("click", function (d, i) { return cloock(i); })
.style("stroke", "#aaa")
.attr("d", function(d) { return "M" + d.join("L") + "Z"; });
// UPDATE voronoi //
vis.selectAll("path")
.data(d3.geom.voronoi(_.map(nodes, function (d) { return [d.x, d.y]; }))
.map(function(d) { return "M" + d.join("L") + "Z"; }))
.filter(function(d) { return this.getAttribute("d") != d; })
.attr("d", function(d) { return d; });
// ENTER circles //
vis.selectAll("circle.node")
.data(nodes)
.enter().append("svg:circle")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", nucleusradius)
.style("stroke", function(d) { return colors[d.state]; })
.style("stroke-width", 1.5)
.style("fill", function(d) { return colors[d.type]; })
.call(force.drag);
// UPDATE circles //
vis.selectAll("circle.node")
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("stroke", function (d) {
return colors[d.state];
})
.attr("fill", function (d) {
return colors[d.type];
});
// DELETE AND THEN ENTER clipping regions //
vis.selectAll(".clipper")
.remove(); // TODO: why do I have to delete them all in order to fix this ???
// why can't I just move around clipPaths ?
vis.selectAll(".clipper")
.data(nodes)
.enter().append("svg:clipPath")
.attr("id", function (d, i) { return "clip"+i; })
.attr("class", "clipper")
.append("svg:circle")
.attr('cx', function (d) { return d.x; })
.attr('cy', function (d) { return d.y; })
.attr('r', cellRadius);
});
// TICK }}}
//{{{ INITIAL SETUP
vis.selectAll("path")
.data(d3.geom.voronoi(_.map(nodes, function (d) { return [d.x, d.y]; })))
.enter().append("path")
.attr("class", function(d, i) { return i ? "q" + (i % 9) + "-9" : null; })
.attr("d", function(d) { return "M" + d.join("L") + "Z"; });
var incrementer = -1
// set up interval of generation
setInterval('addNodeIfGen', generationPeriod);
console.log("===Simulation Started===");
// INITIAL SETUP }}}
//{{{ INTERFACE
function cloock (index) {
var b = document.querySelector("#casting input:checked").value;
if (b.localeCompare("mono") === 0) {
propagateOneToOne(index);
} else if (b.localeCompare("multi") === 0){
propagateOneToAll(index);
} else if (b.localeCompare("monoToEdge") === 0){
propagateMonoToEdge(index, true, 3);
} else if (b.localeCompare("monoToEdgeWithSpine") === 0){
propagateMonoToEdgeWithSpine(index, true, 3);
} else if (b.localeCompare("automation") === 0){
startAutomation(index);
} else {
console.log("UNIMPLEMENTED")
}
}
var stopGen = function () {
if (generating === false) {
generating = true;
//document.getElementById('generating').value = "stop simulation";
}else{
generating = false;
//document.getElementById('generating').value = "start simulation";
}
}
var stop = function () {
if (paused === false) {
paused = true;
force.stop();
document.getElementById('plause').value = "play";
}else{
paused = false;
force.start();
document.getElementById('plause').value = "pause";
}
}
// INTERFACE }}}
//{{{ CHANGING STATE
// TODO: figure out why this is necessary to
// do so frequently ...
function updateColors () {
vis.selectAll("circle.node")
.style("stroke", function(d) {
return colors[d.state];
})
.style("fill", function(d) {
return colors[d.type];
});
}
function highlightSelf (nodeOfInterestIndex) {
nodes[nodeOfInterestIndex].type = "head";
updateColors();
}
function highlightSelfState (nodeOfInterestIndex) {
nodes[nodeOfInterestIndex].state = "selected";
updateColors();
}
function highlightNeighboursIncludingSelf (nodeOfInterestIndex) {
var index = nodeOfInterestIndex;
removeHighlights();
highlightSelfState(nodeOfInterestIndex);
highlightNeighbours(nodeOfInterestIndex);
updateColors();
}
function toggleMouseHighlighting () {
showingMouseHighlights = showingMouseHighlights ? false : true;
document.getElementById('toggleMouseHighlighting').value = showingMouseHighlights ? 'remove mouse highlighting' : 'engage mouse highlighting';
if (!showingMouseHighlights) {
removeHighlights();
}
}
function removeHighlights () {
_.each(nodes, function (d, i) {
//if (d.state === "selected") {
nodes[i].state = "deselected";
//}
});
updateColors();
}
function highlightNeighbours (nodeOfInterestIndex) {
var neighbours = generateAllNeighbours()[nodeOfInterestIndex];
_.each(neighbours, function (i) {
nodes[i].state = "selected";
});
updateColors();
}
// CHANGING STATE }}}
//{{{ PROPAGATING
function propagateOneToAll (index) {
var neighbours = generateAllNeighbours()[index];
var nbs = _.filter(neighbours, function (d) { return nodes[d].state.localeCompare("deselected") === 0 || nodes[d].state.localeCompare("selected") === 0; });
highlightSelf(index);
if (!paused && nbs.length > 0) {
_.forEach(nbs, function (d,i) {
setTimeout(propagateOneToAll, generationPeriod, d);
});
}
}
function propagateOneToOne (index) {
var neighbours = generateAllNeighbours()[index];
var nbs = _.filter(neighbours, function (d) { return nodes[d].state.localeCompare("deselected") === 0 || nodes[d].state.localeCompare("selected") === 0; });
var rndm = _.random(0, nbs.length - 1);
highlightSelf(index);
if (!paused && nbs.length > 0) {
setTimeout(propagateOneToOne, generationPeriod, [nbs[rndm]]);
}
}
function propagateMonoToEdgeWithSpine (index, startGrowingThere, howManyToGrow) {
var neighbours = generateAllNeighbours()[index];
if (checkIfEdge(index)) {
nodes[index].type = "head";
updateColors();
headParent = index;
//nodes[headParent].fixed = true;
if (startGrowingThere) {
startAutomation(index);
splitNodeAmountOfTimesHead(index, howManyToGrow, "head");
//splitNodeAmountOfTimesHead(index, howManyToGrow, "spine");
}
} else if (!paused && neighbours.length > 0) {
var rndm = _.random(0, neighbours.length - 1);
highlightSelf(index);
setTimeout(propagateMonoToEdge, generationPeriod, neighbours[rndm], startGrowingThere, howManyToGrow);
}
}
function propagateMonoToEdge (index, startGrowingThere, howManyToGrow) {
var neighbours = generateAllNeighbours()[index];
if (checkIfEdge(index)) {
nodes[index].type = "head";
updateColors();
headParent = index;
//nodes[headParent].fixed = true;
if (startGrowingThere) {
splitNodeAmountOfTimesHead(index, howManyToGrow, "head");
//splitNodeAmountOfTimesHead(index, howManyToGrow, "spine");
}
} else if (!paused && neighbours.length > 0) {
var rndm = _.random(0, neighbours.length - 1);
highlightSelfState(index);
updateColors();
setTimeout(propagateMonoToEdge, generationPeriod, neighbours[rndm], startGrowingThere, howManyToGrow);
}
}
function automateIteration() {
var allNeighbours = generateAllNeighbours();
for (nod in nodes) {
if (nodes[nod].type.localeCompare("head") === 0) { continue; } // don't affect head nodes
var r = _.some(allNeighbours[nod], function (d) {
return nodes[d].type.localeCompare("right") === 0;
}); // if it has a right neighbour
var l = _.some(allNeighbours[nod], function (d) {
return nodes[d].type.localeCompare("left") === 0;
}); // if it has a left neighbour
if (r && l) {
/*it is touching right and left*/
nodes[nod].type = "spine";
} else if (r) {
nodes[nod].type = "right";//make it right
} else if (l) {
nodes[nod].type = "left";//make it left
}
}
updateColors();
// TODO: if any are still of type "normal", keep iterating
}
function startAutomation(index) {
var neighbours = generateAllNeighbours()[index];
var edgeNeighbours = _.filter(neighbours, function (d) {
return checkIfEdge(d);
});
if(edgeNeighbours.length < 2) {
alert("Please select a cell with more than one edge cell neighbour");
return;
}
nodes[edgeNeighbours[0]].type = "left";
nodes[edgeNeighbours[1]].type = "right";
automateIteration();
}
// PROPAGATING }}}
//{{{ ADDING AND REMOVING NODES
function copyLinks(ln) {
var lnew = []
_.each(ln, function (l) {
lnew.push({source:l.source, target:l.target});
});
return lnew;
}
var addNode = function (indexOfNodeToMultiply, type, state) {
if (!state) {
var state = "deselected";
}
// TODO:
// - if indexOfNodeToMultiply is a head node,
// then the new node should link to it, and
// also be a head node
//force.links(copyLinks( links ));
if (paused === false){
var rad = Math.random() * Math.PI * 2;
var xoffset = Math.cos(rad) * nucleusradius;
var yoffset = Math.sin(rad) * nucleusradius;
// spawn a new node nucleusradius away from the previous node in a random direction.
nodes.push({ // push a new node at the location of the previous one
x: (incrementer === -1) ? foci.x : nodes[indexOfNodeToMultiply].x + xoffset,
y: (incrementer === -1) ? foci.y : nodes[indexOfNodeToMultiply].y + yoffset,
type: type,
state: state,
}); //{id: ~~(Math.random())});
incrementer++;
force.start();
}
};
var splitNodeAmountOfTimesHead = function (indexOfNodeToMultiply, howManyTimes, type) {
var i = howManyTimes;
//nodes[indexOfNodeToMultiply].type = "head";
while (i >= 0) {
setTimeout(addNode, generationPeriod * i / 2, indexOfNodeToMultiply, type);
i = i - 1;
}
}
function addLink(nodChild, nodParent) {
//links.push({source: nodChild,
//target: nodParent});
//force.links(copyLinks(links));
//force.start();
}
function splitAllOfTypeWithLink (type) {
_.each(nodes, function (nod, i) {
if (nod.type === type) {
addNode(i, "normal");
nodes[nodes.length - 1].type = type;
addLink(i, nodes.length - 1);
}
});
}
var splitNodeAmountOfTimes = function (indexOfNodeToMultiply, howManyTimes) {
var i = howManyTimes;
while (i >= 0) {
setTimeout(addNode, generationPeriod * i / 2, indexOfNodeToMultiply, "normal");
i = i - 1;
}
}
var addNewNodeToEndOfList = function () {
addNode(incrementer, "normal");
}
var splitAllNodesA_AA = function () {
// split every node into two nodes
var i = 0;
incNow = incrementer + 1;
//for every node, make a new node
for (i = 0; i < incNow; i++) {
addNode(i, nodes[i].type);
}
};
var splitAllNodesB_BA = function () {
// split every node into two nodes
var i = 0;
incNow = incrementer + 1;
//for every node, make a new node
for (i = 0; i < incNow; i++) {
addNode(i, "head");
}
};
var splitAllNodesA_AAwithState = function () {
// split every node into two nodes
var i = 0;
incNow = incrementer + 1;
//for every node, make a new node
for (i = 0; i < incNow; i++) {
addNode(i, nodes[i].type, nodes[i].state);
}
};
var splitAllNodesB_BAwithState = function () {
// split every node into two nodes
var i = 0;
incNow = incrementer + 1;
//for every node, make a new node
for (i = 0; i < incNow; i++) {
var toChange = nodes[i].type.localeCompare("left") === 0 ||
nodes[i].type.localeCompare("right") === 0 ||
nodes[i].type.localeCompare("normal") === 0;
if (toChange) {
addNode(i, nodes[i].type);
} else {
addNode(i, nodes[i].type, nodes[i].state);
}
}
};
var addNodeIfGen = function () {
if (generating) { addNewNodeToEndOfList(); }
}
// ADDING AND REMOVING NODES }}}
//{{{ HELPER METHODS
function generateAllNeighbours () {
var tmpN = d3.get_delaunay_neighbours(_.map(nodes, function (d) { return [Math.round(d.x), Math.round(d.y)]; }));
var tmpN2 = [];
_.each(tmpN, function (d, i) {
tmpN2.push(_.filter(d, function (x) { return closeNeighbours(nodes[i], nodes[x]); }));
});
// TODO: better idea:
// - determine if all neighbours connect in a ring.
// - this is in order to find edge nodes.
return tmpN2;
}
function countNeighbours (index) {
return generateAllNeighbours()[index].length;
}
function checkIfEdge (index) {
//Not a perfect method:
// There are occasional edge nodes which are NOT considered to be edge nodes,
// but it will work fine for us.
// There are also occasional inner nodes which ARE considered to be edge nodes,
// but it's rare enough that it should be okay.
// If we have a cycle that means we are NOT an edge node.
return !findCycle(index)
}
function findCycle (index) {
var neighbours = generateAllNeighbours();
var neighboursOfIndex = neighbours[index];
// there is only one node
if (neighboursOfIndex.length == 0) {
return false;
}
// the neighbours' neighbours, which only include the neighbours.
// AKA we are only considering nodes which are neighbours of index.
var filteredNeighbours = _.map(neighbours, function (nei) { return _.filter(nei, function (nod) {
return neighboursOfIndex.indexOf(nod) > -1;
})});
var previousNode = -1;
var currentNode = neighboursOfIndex[0];
do {
var fil = _.filter(filteredNeighbours[currentNode], function (nod) { return nod != previousNode; });
if (fil.length == 0) return false;
previousNode = currentNode;
currentNode = fil[0];
} while (currentNode != neighboursOfIndex[0])
return true;
//var currentNode = neighboursOfIndex[0];
//var previousNode = -1;
//while (currentNode != neighboursOfIndex[0]) {
//}
//return true;
}
function distanceBetweenTwoPoints(x1, x2, y1, y2) {
return Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2));
}
function distanceBetweenTwoNodes(n1, n2) {
return distanceBetweenTwoPoints(n1.x, n2.x, n1.y, n2.y)
}
function closeNeighbours(n1, n2) {
return distanceBetweenTwoNodes(n1, n2) <= cellRadius*2;
}
// HELPER METHODS }}}
// set up the initial mass (mostly for testing)
_.times(1, addNewNodeToEndOfList);
_.times(startingQuantity, splitAllNodesA_AA);
</script>
</br>
<h2>Instructions:</h2>
<h3>Pattern Formation:</h3>
<ul>
<li>Start with one cell, then click the 'A->A,A' and 'B->B,B' buttons.</li>
<li>Try these sequences: AABAAA (splotches), AAAABA (streaks), and AABBBA (dots).</li>
<li>Refresh the page to try another one.</li>
</ul>
<h3>Shape Formation:</h3>
<ul>
<li>Click 'A->A,A' five or six times (to get enough cells)</li>
<li>Wait for the cells to settle down.</li>
<li>With 'Start Automation' selected, click on an edge cell.</li>
<li>Click 'iterate' until the organism has a full spine and two distinct sides.</li>
</ul>
</body><!--{{{-->
</html><!--}}}-->
<!-- vim: set foldmethod=marker: -->