summaryrefslogtreecommitdiff
path: root/code/weightvis.js
blob: 409eb909e0cd0a8e333243f0c068cc89cdd3e7f1 (plain)
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
// material colors
var
    //              50         100       200        300        400        500       
    pDeepPurple = ['#ede7f6', '#d1c4e9', '#b39ddb', '#9575cd', '#7e57c2', '#673ab7',
    //              600        700        800       900
                   '#5e35b1', '#512da8', '#4527a0', '#311b92'],
    pPink       = ['#fce4ec', '#f8bbd0', '#f48fb1', '#f06292', '#ec407a', '#e91e63',
                   '#d81b60', '#c2185b', '#ad1457', '#880e4f'],
    //               A100      A200        A400       A700
    pDeepPurpleA = ['#b388ff', '#7c4dff', '#651fff', '#6200ea'],
    pGreenA      = ['#b9f6ca', '#69f0ae', '#00e676', '#00c853'],
    pBlueA       = ['#82b1ff', '#448aff', '#2979ff', '#2962ff'],
    pPinkA       = ['#ff80ab', '#ff4081', '#f50057', '#c51162'],

    pDark  = ['#000000', '#212121', '#303030', '#424242'],
    pLight = ['#E0E0E0', '#F5F5F5', '#FAFAFA', '#FFFFFF'],

    oText     = [0.87, 0.54, 0.38, 0.12],
    textColor = ['#000000'],

    primaryColor   = [pDeepPurple[1], pDeepPurple[5], pDeepPurple[7]],
    secondaryColor = pBlueA[3],
    tertiaryColor  = [pPink[1], pPink[5], pPink[7]],
    themeColor     = pLight,

    accentColor = secondaryColor,
    bgColor     = themeColor[3],

    linkColor             = primaryColor[0],
    linkColorAlt          = tertiaryColor[0],
    linkHighlightColor    = primaryColor[1],
    linkHighlightColorAlt = tertiaryColor[1],
    nodeColor             = textColor[0],
    nodeHighlightColor    = accentColor
;


/* network construction */

var Network = (function() {
    function Network(layout) {
        this.layout = layout;
    }

    Network.prototype.init = function() {
        this._createNodes();
        this._createLinks();
    };

    Network.prototype.resize = function(env) {
        var largestLayerSize = 0;
        for (layer=0; layer<this.layout.net.layers; layer++) {
            if (this.layout.net[layer].size > largestLayerSize) largestLayerSize = this.layout.net[layer].size;
        }
        this.responsiveRadius = d3.min([env.width, env.height]) / d3.max([this.layout.net.layers, largestLayerSize]);
        this._updateNodes(env);
    };

    Network.prototype._createNodes = function() {
        // create layers
        this.nodes = [];
        for (layer=0; layer<this.layout.net.layers; layer++) {
            for (node=0; node<this.layout.net[layer].size; node++) {
                this.nodes.push({
                    id: layer.toString() + "_" + node.toString(),
                    layer: layer,
                    fixed: true
                });
            }
        }
    };

    Network.prototype._createLinks = function() {
        this.links = [];
        var nodesMap = d3.map();
        this.nodes.forEach(function (n) {
            return nodesMap.set(n.id, n);
        });
        // create links between adjacent layers
        for (layer=0; layer<this.layout.net.layers-1; layer++) { // for every layer except the last
            for (src=0; src<this.layout.net[layer].size; src++) { // get all nodes
                if (this.layout.net[layer].isBias) {
                    this.links.push({ // in case of a bias layer, connect 1:1
                        source: nodesMap.get(layer.toString() + "_" + src.toString()),
                        target: nodesMap.get((layer+1).toString() + "_" + src.toString()),
                        weight: 1,
                        positive: true
                    });
                } else { // normal layer
                    for (tar=0; tar<this.layout.net[layer+1].size; tar++) { // get all nodes of the next layer
                        this.links.push({ // connect both nodes
                            source: nodesMap.get(layer.toString() + "_" + src.toString()),
                            target: nodesMap.get((layer+1).toString() + "_" + tar.toString()),
                            weight: 1,
                            positive: true
                        });
                    }
                }
            }
        }
    };

    Network.prototype._updateNodes = function(env) {
        biasLayers = 0;
        for (layer=0; layer<this.layout.net.layers; layer++) {
            if (this.layout.net[layer].isBias) biasLayers++;
        }
        var cnt = 0;
        for (layer=0; layer<this.layout.net.layers; layer++) {
            for (node=0; node<this.layout.net[layer].size; node++) {
                // dynamic ("responsive") attributes for all window sizes
                if (this.layout.net[layer].isBias) {
                    this.nodes[cnt].x = (layer - biasLayers + 1.25) * (env.width / (this.layout.net.layers - biasLayers));
                    this.nodes[cnt].y = (node + 0.25) * (env.height / this.layout.net[layer].size);
                    this.nodes[cnt].r = this.responsiveRadius * 0.2;
                } else {
                    this.nodes[cnt].x = (layer - biasLayers + 0.5) * (env.width / (this.layout.net.layers - biasLayers));
                    this.nodes[cnt].y = (node + 0.5) * (env.height / this.layout.net[layer].size);
                    this.nodes[cnt].r = this.responsiveRadius * 0.3;
                }
                cnt++;
            }
        }
    };

    Network.prototype.updateWeights = function(weights, epochLayout) {
        var cnt = 0;
        for (layer=0; layer<weights.length; layer++) {
            for (layer2=0; layer2<weights[layer].length; layer2++) {
                for (node=0; node<weights[layer][layer2].length; node++) {
                    this.links[cnt].positive = (weights[layer][layer2][node] >= 0);
                    // scaled = (x - min) / (max - min)
                    this.links[cnt++].weight = (Math.abs(weights[layer][layer2][node]) - epochLayout.min) / (epochLayout.max - epochLayout.min);
                }
            }
        }
    };

    return Network;
})();


/* data handling */

var Loader = (function() {
    function Loader() {
    }

    Loader.prototype.load = function(url, callback) {
        var self = this;
        d3.json(url)
            .get(function(e, json) {
                if (e) console.log(e);
                self._parse(json);
        });
        this._finished = callback;
    };

    Loader.prototype._parse = function(json) {
        // json format:
        // json.
        //   [batch][epoch] [[sourceIndex x targetIndex]] (int)
        // careful - root and first level nodes are objects and have no '.length'

        var layout = {};
        // layout format:
        // layout.
        //   net.layers (int)
        //   net.[net.layers].
        //      isBias (bool)
        //      size (int)
        //   layers.[batch][epoch].
        //      min (int)
        //      max (int)
        //   data.
        //      batches (int)
        //      epochs  (int)
        layout.data = {};
        layout.data.batches = Object.keys(json).length;
        layout.data.epochs  = Object.keys(json[0]).length;
        layout.net = {};
        // network structure
        layout.net.layers = json[0][0].length;
        for (layer=0; layer<layout.net.layers; layer++) {
            layerObj = {};
            if (json[0][0][layer].length == 1) { // bias
                layerObj.isBias = true;
                layerObj.size = json[0][0][0][layer].length; // workaround - Matrix should be rotatet serverside
            } else {
                layerObj.isBias = false;
                layerObj.size = json[0][0][layer].length;
            }
            layout.net[layer] = layerObj;
        }
        layout.net[layout.net.layers] = {'isBias': false, 'size': json[0][0][layout.net.layers-1][0].length};
        layout.net.layers += 1; // output layer
        // layer properties
        layout.layers = {};
        for (batch=0; batch<layout.data.batches; batch++) {
            layout.layers[batch] = {};
            for (epoch=0; epoch<layout.data.epochs; epoch++) {
                layout.layers[batch][epoch] = {};
                layout.layers[batch][epoch].max = 0;
                layout.layers[batch][epoch].min = Infinity;
                for (layer=0; layer<json[batch][epoch].length; layer++) {
                    var layerMin = d3.min(json[batch][epoch][layer], Math.abs);
                    var layerMax = d3.max(json[batch][epoch][layer], Math.abs);
                    if (layerMin < layout.layers[batch][epoch].min) layout.layers[batch][epoch].min = layerMin;
                    if (layerMax > layout.layers[batch][epoch].max) layout.layers[batch][epoch].max = layerMax;
                }
            }
        }
        if (this._finished) this._finished(layout, json);
    };

    return Loader;
})();


/* animation stepping */

var Animator = (function() {
    function Animator(layout, time, step) {
        this.layout = layout;
        this.step = step;
        this.frameDuration = time / (this.layout.data.batches * this.layout.data.epochs / this.step);
    }

    Animator.prototype.start = function(bat, ep, callback, finishedCb) {
        var self = this;
        this.epoch = ep;
        this.batch = bat;
        this.finishedCb = finishedCb;
        wrapper = function() {
            callback(self.batch, self.epoch, self.frameDuration);
            self.animate();
        };
        this.pid = setInterval(wrapper, this.frameDuration);
    };

    Animator.prototype.stop = function() {
        if (this.finishedCb) this.finishedCb();
        clearInterval(this.pid);
    };

    Animator.prototype.animate = function() {
        this.epoch += this.step;
        if (this.epoch >= this.layout.data.epochs) {
            this.epoch = 0;
            if (++this.batch>= this.layout.data.batches) {
                this.batch = 0;
                this.stop();
            }
        }
    };

    return Animator;
})();


/* main */

var Visualizer = (function() {
    var _weightScaler = 10; // size of thickest line

    function Visualizer(svg) {
        this.loader = new Loader();
        this.svg = svg;
        this.stepHooks = [];
        this.stopHooks = [];
    }

    Visualizer.prototype.getSteps = function() {
        return this.layout.data.batches * this.layout.data.epochs;
    };
    Visualizer.prototype.getDatashape = function() {
        return this.layout.data;
    };

    Visualizer.prototype.load = function(url, callback) {
        var self = this;
        function wrapper(layout, data) {
            self.layout = layout;
            self.data = data;
            self._setup();
            callback();
        }
        this.loader.load("data/log.json", wrapper);
    };

    Visualizer.prototype.stopAnimation = function() {
        this.animator.stop();
    };

    Visualizer.prototype.animate = function(animationTime, resolution, step) {
        // animationTime in seconds per frame
        // resolution in epochs per frame
        var self = this;
        var batch = Math.floor(step / this.layout.data.epochs),
            epoch = step % this.layout.data.epochs;
        this.animator = new Animator(this.layout, animationTime * 1000, resolution);
        this.animator.start(batch, epoch, function(cbatch, cepoch) {
            self.show(cbatch, cepoch);
        }, function() {
            self.stopHooks.forEach(function(hook){ hook(); });
        });
    };

    Visualizer.prototype.hookStepper = function(hook) {
        this.stepHooks.push(hook);
    };

    Visualizer.prototype.hookStop = function(hook) {
        this.stopHooks.push(hook);
    };

    Visualizer.prototype.showStep = function(step) {
        var epoch = step % this.layout.data.epochs,
            batch = Math.floor(step / this.layout.data.epochs);
        this.show(batch, epoch);
    };

    Visualizer.prototype.show = function(batch, epoch, transitionDuration) {
        var self = this;
        this.network.updateWeights(this.data[batch][epoch], this.layout.layers[batch][epoch]);
        if (transitionDuration) {
            // 10% extra time per frame for the code execution
            this.domLink
                .transition()
                .duration(transitionDuration / 1.1);
        }
        this.domLink.style("stroke-width", function(d) { return d.weight * _weightScaler; })
            .style("stroke", function(d) {
                if (d3.select(this).attr("data-highlight") != "true") {
                    return d.positive?linkColor:linkColorAlt;
                } else {
                    return d.positive?linkHighlightColor:linkHighlightColorAlt;
                }
            });
        this.stepHooks.forEach(function(hook){ hook(batch * self.layout.data.epochs + epoch); });
    };

    Visualizer.prototype.reposition = function() {
        var width = parseInt(this.svg.style("width"))   || 800,
            height = parseInt(this.svg.style("height")) || 600;
        var node = this.svg.selectAll(".node");

        this.network.resize({"width": width, "height": height});

        node
            .attr("cx", function(d) { return d.x; })
            .attr("cy", function(d) { return d.y; })
            .attr("r",  function(d) { return d.r; });
        this.domLink
            .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; });
    };

    Visualizer.prototype._setup = function() {
        var self = this;
        // create empty elements and determine the visualisation's size
        var width = parseInt(this.svg.style("width"))   || 800,
            height = parseInt(this.svg.style("height")) || 600;

        this.network = new Network(this.layout);
        this.network.init();
        this.network.resize({"width": width, "height": height});
        this.network.updateWeights(this.data[0][0], this.layout.layers[0][0]);

        this.domLink = this.svg.selectAll(".link")
            .data(this.network.links)
            .enter().append("line")
            .attr("class", function(d) { return "link source-" + d.source.id + " target-" + d.target.id; })
            .style("stroke", function(d) { return (d.positive?linkColor:linkColorAlt); })
            .style("stroke-width", function(d) { return d.weight * _weightScaler; })
            .on("mouseover", function(d) {
                d3.select("#node-" + d.source.id).style("fill", nodeHighlightColor);
                d3.select("#node-" + d.target.id).style("fill", nodeHighlightColor);
                d3.select(this).style("stroke", function(d) { return (d.positive?linkHighlightColor:linkHighlightColorAlt); });
            })
            .on("mouseout", function(d) {
                var src = d3.select("#node-" + d.source.id);
                if (src.attr("data-highlight") != "true") src.style("fill", nodeColor);
                var tar = d3.select("#node-" + d.target.id);
                if (tar.attr("data-highlight") != "true") tar.style("fill", nodeColor);
                var me = d3.select(this);
                if (me.attr("data-highlight") != "true") me.style("stroke", d.positive?linkColor:linkColorAlt);
            })
            .on("click", function(d) {
                var me = d3.select(this);
                if (me.attr("data-highlight") != "true") {
                    d3.select(this).attr("data-highlight", "true");
                } else {
                    d3.select(this).attr("data-highlight", "false");
                }
            });
        var node = this.svg.selectAll(".node")
            .data(this.network.nodes)
            .enter().append("circle")
            .attr("class", function(d) { return "node layer-" + d.layer; })
            .attr("id", function(d) { return "node-" + d.id; })
            .style("fill", nodeColor)
            .on("mouseover", function(n) {
                d3.selectAll(".source-" + n.id).style("stroke", function(d) { return (d.positive?linkHighlightColor:linkHighlightColorAlt); });
                d3.selectAll(".target-" + n.id).style("stroke", function(d) { return (d.positive?linkHighlightColor:linkHighlightColorAlt); });
                d3.select(this).style("fill", nodeHighlightColor);
            })
            .on("mouseout", function(n) {
                d3.selectAll(".source-" + n.id)
                    .style("stroke", function(d) {
                        if (d3.select(this).attr("data-highlight") != "true") {
                            return (d.positive?linkColor:linkColorAlt);
                        } else {
                            return d3.select(this).style("stroke");
                        }
                    });
                d3.selectAll(".target-" + n.id)
                    .style("stroke", function(d) {
                        if (d3.select(this).attr("data-highlight") != "true") {
                            return (d.positive?linkColor:linkColorAlt);
                        } else {
                            return d3.select(this).style("stroke");
                        }
                    });
                var me = d3.select(this);
                if (me.attr("data-highlight") != "true") me.style("fill", nodeColor);
            })
            .on("click", function(d) {
                var me = d3.select(this);
                if (me.attr("data-highlight") == "true") {
                    d3.selectAll(".source-" + d.id).attr("data-highlight", "false");
                    //d3.selectAll(".target-" + d.id).attr("data-highlight", "false");
                    me.attr("data-highlight", "false");
                } else {
                    d3.selectAll(".source-" + d.id).attr("data-highlight", "true");
                    //d3.selectAll(".target-" + d.id).attr("data-highlight", "true");
                    me.attr("data-highlight", "true");
                }
            });

        this.reposition();
    };

    return Visualizer;
})();