-
Notifications
You must be signed in to change notification settings - Fork 31
/
narrative.js
1475 lines (1253 loc) · 37.9 KB
/
narrative.js
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Narrative Charts
// ================
//
// `d3.layout.narrative()`
//
// The constructor takes no arguements. All relevant object properties should
// be set using the setter functions.
d3.layout.narrative = function(){
// Import jLouvian
// ---------------
// [jLouvian](https://github.com/upphiminn/jLouvain) is a open source (MIT)
// javascript implementation of the Louvian method of
// [community detection](https://www.wikiwand.com/en/Louvain_Modularity).
// Graph clustering algorithm
// --------------------------
//
// Author: Corneliu S. (github.com/upphiminn)
//
// Lightly cleaned up and documented by Simon Elvery.
//
// This is a javascript implementation of the Louvain
// community detection algorithm (http://arxiv.org/abs/0803.0476)
// Based on https://bitbucket.org/taynaud/python-louvain/overview
//
// TODO: Make this into an ES6 Module.
function jLouvain() {
// Constants
var __PASS_MAX = -1;
var __MIN = 0.0000001;
// Local vars
var original_graph_nodes;
var original_graph_edges;
var original_graph = {};
var partition_init;
// Helpers
function make_set(array){
var set = {};
array.forEach(function(d){
set[d] = true;
});
return Object.keys(set);
}
function obj_values(obj){
var vals = [];
for( var key in obj ) {
if ( obj.hasOwnProperty(key) ) {
vals.push(obj[key]);
}
}
return vals;
}
function get_degree_for_node(graph, node){
var neighbours = graph._assoc_mat[node] ? Object.keys(graph._assoc_mat[node]) : [];
var weight = 0;
neighbours.forEach(function(neighbour){
var value = graph._assoc_mat[node][neighbour] || 1;
if(node === neighbour) {
value *= 2;
}
weight += value;
});
return weight;
}
function get_neighbours_of_node(graph, node){
if(typeof graph._assoc_mat[node] === 'undefined') {
return [];
}
var neighbours = Object.keys(graph._assoc_mat[node]);
return neighbours;
}
function get_edge_weight(graph, node1, node2){
return graph._assoc_mat[node1] ? graph._assoc_mat[node1][node2] : undefined;
}
function get_graph_size(graph){
var size = 0;
graph.edges.forEach(function(edge){
size += edge.weight;
});
return size;
}
function add_edge_to_graph(graph, edge){
update_assoc_mat(graph, edge);
var edge_index = graph.edges.map(function(d){
return d.source+'_'+d.target;
}).indexOf(edge.source+'_'+edge.target);
if(edge_index !== -1) {
graph.edges[edge_index].weight = edge.weight;
} else {
graph.edges.push(edge);
}
}
function make_assoc_mat(edge_list){
var mat = {};
edge_list.forEach(function(edge){
mat[edge.source] = mat[edge.source] || {};
mat[edge.source][edge.target] = edge.weight;
mat[edge.target] = mat[edge.target] || {};
mat[edge.target][edge.source] = edge.weight;
});
return mat;
}
function update_assoc_mat(graph, edge){
graph._assoc_mat[edge.source] = graph._assoc_mat[edge.source] || {};
graph._assoc_mat[edge.source][edge.target] = edge.weight;
graph._assoc_mat[edge.target] = graph._assoc_mat[edge.target] || {};
graph._assoc_mat[edge.target][edge.source] = edge.weight;
}
function clone(obj){
if(obj === null || typeof(obj) !== 'object') {
return obj;
}
var temp = obj.constructor();
for(var key in obj) {
temp[key] = clone(obj[key]);
}
return temp;
}
//Core-Algorithm Related
function init_status(graph, status, part){
status['nodes_to_com'] = {};
status['total_weight'] = 0;
status['internals'] = {};
status['degrees'] = {};
status['gdegrees'] = {};
status['loops'] = {};
status['total_weight'] = get_graph_size(graph);
if (typeof part === 'undefined'){
graph.nodes.forEach(function(node,i){
status.nodes_to_com[node] = i;
var deg = get_degree_for_node(graph, node);
if (deg < 0) {
throw 'Bad graph type, use positive weights!';
}
status.degrees[i] = deg;
status.gdegrees[node] = deg;
status.loops[node] = get_edge_weight(graph, node, node) || 0;
status.internals[i] = status.loops[node];
});
} else {
graph.nodes.forEach(function(node){
var com = part[node];
status.nodes_to_com[node] = com;
var deg = get_degree_for_node(graph, node);
status.degrees[com] = (status.degrees[com] || 0) + deg;
status.gdegrees[node] = deg;
var inc = 0.0;
var neighbours = get_neighbours_of_node(graph, node);
neighbours.forEach(function(neighbour){
var weight = graph._assoc_mat[node][neighbour];
if (weight <= 0) {
throw "Bad graph type, use positive weights";
}
if (part[neighbour] === com) {
if (neighbour === node) {
inc += weight;
} else {
inc += weight/2.0;
}
}
});
status.internals[com] = (status.internals[com] || 0) + inc;
});
}
}
function __modularity(status){
var links = status.total_weight;
var result = 0.0;
var communities = make_set(obj_values(status.nodes_to_com));
communities.forEach(function(com){
var in_degree = status.internals[com] || 0 ;
var degree = status.degrees[com] || 0 ;
if (links > 0) {
result = result + in_degree / links - Math.pow((degree / (2.0*links)), 2);
}
});
return result;
}
function __neighcom(node, graph, status){
// compute the communities in the neighb. of the node, with the graph given by
// node_to_com
var weights = {};
var neighboorhood = get_neighbours_of_node(graph, node);//make iterable;
neighboorhood.forEach(function(neighbour){
if (neighbour !== node) {
var weight = graph._assoc_mat[node][neighbour] || 1;
var neighbourcom = status.nodes_to_com[neighbour];
weights[neighbourcom] = (weights[neighbourcom] || 0) + weight;
}
});
return weights;
}
function __insert(node, com, weight, status){
//insert node into com and modify status
status.nodes_to_com[node] = +com;
status.degrees[com] = (status.degrees[com] || 0) + (status.gdegrees[node]||0);
status.internals[com] = (status.internals[com] || 0) + weight + (status.loops[node]||0);
}
function __remove(node, com, weight, status){
//remove node from com and modify status
status.degrees[com] = ((status.degrees[com] || 0) - (status.gdegrees[node] || 0));
status.internals[com] = ((status.internals[com] || 0) - weight -(status.loops[node] ||0));
status.nodes_to_com[node] = -1;
}
function __renumber(dict){
var count = 0;
var ret = clone(dict); //deep copy :)
var new_values = {};
var dict_keys = Object.keys(dict);
dict_keys.forEach(function(key){
var value = dict[key];
var new_value = (typeof new_values[value] === 'undefined') ? -1 : new_values[value];
if (new_value === -1) {
new_values[value] = count;
new_value = count;
count = count + 1;
}
ret[key] = new_value;
});
return ret;
}
function __one_level(graph, status){
//Compute one level of the Communities Dendogram.
var modif = true,
nb_pass_done = 0,
cur_mod = __modularity(status),
new_mod = cur_mod;
while (modif && nb_pass_done !== __PASS_MAX) {
cur_mod = new_mod;
modif = false;
nb_pass_done += 1;
graph.nodes.forEach(eachNode);
new_mod = __modularity(status);
if(new_mod - cur_mod < __MIN) {
break;
}
}
function eachNode(node) {
var com_node = status.nodes_to_com[node];
var degc_totw = (status.gdegrees[node] || 0) / (status.total_weight * 2.0);
var neigh_communities = __neighcom(node, graph, status);
__remove(node, com_node, (neigh_communities[com_node] || 0.0), status);
var best_com = com_node;
var best_increase = 0;
var neigh_communities_entries = Object.keys(neigh_communities);//make iterable;
neigh_communities_entries.forEach(function(com){
var incr = neigh_communities[com] - (status.degrees[com] || 0.0) * degc_totw;
if (incr > best_increase){
best_increase = incr;
best_com = com;
}
});
__insert(node, best_com, neigh_communities[best_com] || 0, status);
if(best_com !== com_node) {
modif = true;
}
}
}
function induced_graph(partition, graph){
var ret = {nodes:[], edges:[], _assoc_mat: {}};
var w_prec, weight;
//add nodes from partition values
var partition_values = obj_values(partition);
ret.nodes = ret.nodes.concat(make_set(partition_values)); //make set
graph.edges.forEach(function(edge){
weight = edge.weight || 1;
var com1 = partition[edge.source];
var com2 = partition[edge.target];
w_prec = (get_edge_weight(ret, com1, com2) || 0);
var new_weight = (w_prec + weight);
add_edge_to_graph(ret, {'source': com1, 'target': com2, 'weight': new_weight});
});
return ret;
}
function partition_at_level(dendogram, level){
var partition = clone(dendogram[0]);
for(var i = 1; i < level + 1; i++ ) {
Object.keys(partition).forEach(eachKey);
}
return partition;
function eachKey(key){
var node = key;
var com = partition[key];
partition[node] = dendogram[i][com];
}
}
function generate_dendogram(graph, part_init){
if (graph.edges.length === 0) {
var part = {};
graph.nodes.forEach(function(node){
part[node] = node;
});
return part;
}
var status = {};
init_status(original_graph, status, part_init);
var mod = __modularity(status);
var status_list = [];
__one_level(original_graph, status);
var new_mod = __modularity(status);
var partition = __renumber(status.nodes_to_com);
status_list.push(partition);
mod = new_mod;
var current_graph = induced_graph(partition, original_graph);
init_status(current_graph, status);
while (true){
__one_level(current_graph, status);
new_mod = __modularity(status);
if(new_mod - mod < __MIN) {
break;
}
partition = __renumber(status.nodes_to_com);
status_list.push(partition);
mod = new_mod;
current_graph = induced_graph(partition, current_graph);
init_status(current_graph, status);
}
return status_list;
}
var core = function(){
var dendogram = generate_dendogram(original_graph, partition_init);
return partition_at_level(dendogram, dendogram.length - 1);
};
core.nodes = function(nds){
if(arguments.length > 0){
original_graph_nodes = nds;
}
return core;
};
core.edges = function(edgs){
if (typeof original_graph_nodes === 'undefined') {
throw 'Please provide the graph nodes first!';
}
if (arguments.length > 0) {
original_graph_edges = edgs;
var assoc_mat = make_assoc_mat(edgs);
original_graph = { 'nodes': original_graph_nodes,
'edges': original_graph_edges,
'_assoc_mat': assoc_mat };
}
return core;
};
core.partition_init = function(prttn){
if(arguments.length > 0){
partition_init = prttn;
}
return core;
};
return core;
}
// Define all the variables.
var narrative,
scenes, characters, introductions, links,
size, orientation, pathSpace, scale,
labelSize, labelPosition, groupMargin, scenePadding,
groups;
// Set some defaults.
size = [1,1];
scale = 1;
pathSpace = 10;
labelSize = [100,15];
labelPosition = 'right';
scenePadding = [0,0,0,0];
groupMargin = 0;
orientation = 'horizontal';
// Public functions (the API)
// ==========================
// The narrative object which is returned and exposes the public API.
narrative = {};
// Scenes
// ------
//
// `narrative.scenes([array])`
//
// Set or get the scenes array. If an array is passed, sets the narrative's
// scenes to the passed array, else returns the scenes array.
narrative.scenes = function(_) {
if (!arguments.length) {
return scenes;
}
scenes = _;
return narrative;
};
// Characters
// ----------
//
// `narrative.characters([array])`
//
// Set or get the characters array. If an array is passed, sets the
// narrative's characters array, otherwise returns the characters array.
narrative.characters = function(_) {
if (!arguments.length) {
return characters;
}
characters = _;
return narrative;
};
// Size
// ----
//
// `narrative.size([array])`
//
// Set or get the size of the layout. A two element array `[width,height]`. Note
// that this is considered a guide for the layout algorithm.
// See `narrative.extent()` for getting the final size of the layout.
narrative.size = function(_) {
if (!arguments.length) {
return size;
}
size = _;
return narrative;
};
// Orientation
// -----------
//
// `narrative.orientation([orientation])`
//
// *Incomplete:* Only the default (horizontal) option is fully supported.
//
// Set the orientation to use for the layout. The choices are `'horizontal'` (default)
// or `'vertical'`. In a horizontal orientation 'time' runs from left to right
// and in vertical, top to bottom.
narrative.orientation = function(_) {
if (!arguments.length) {
return orientation;
}
orientation = _;
return narrative;
};
// Extent
// ------
//
// `narrative.extent()`
//
// Get the extent of the space used by the layout. This is useful for adjusting
// the size of the containing element after the layout has been calculated.
//
// Despite being able to set the size (see `narrative.size()`), it's not always
// possible to contain the chart in the available space. This function will
// provide a `[width,height]` array of the layout extent *after* the layout has
// run.
narrative.extent = function(){
return scenes.concat(introductions).reduce(function(max, d){
var bounds = d.bounds();
if (bounds[1][1] > max[1]) {
max[1] = bounds[1][1];
}
if (bounds[1][0] > max[0]) {
max[0] = bounds[1][0];
}
return max;
}, [0,0]);
};
// Path space
// ----------
//
// `narrative.pathSpace([number])`
//
// Set or get the space available to each character's path.
narrative.pathSpace = function(_) {
if (!arguments.length) {
return pathSpace;
}
pathSpace = _;
return narrative;
};
// Group margin
// ------------
//
// `narrative.groupMargin([margin])`
//
// The characters are divided into groups based on the strength of their relationships
// (i.e. co-appearances in scenes). These groups are then arranged in a way designed
// to reduce congestion in the centre of the chart. To give thelayout a more open
// feel, a group margin can be set.
narrative.groupMargin = function(_) {
if (!arguments.length) {
return groupMargin;
}
groupMargin = _;
return narrative;
};
// Scene padding
// -------------
//
// `narrative.scenePadding([array])`
//
// By default scenes have a height equal to `character height × character count`
// and a width of zero. You may want to allow for extra space around scenes so
// collisions with labels can be avoided. To set a padding pass an array of values
// matching the CSS padding argument order `[top, right, bottom, left]`.
narrative.scenePadding = function(_) {
if (!arguments.length) {
return scenePadding;
}
scenePadding = _;
return narrative;
};
// Label size
// ----------
//
// `narrative.labelSize([array])`
//
// Set or get the default space to allocate in the layout for character labels.
// Must be a two element array `[width,height]`. Label sizes specific to each
// character which will override these defaults can be set by defining `height`
// and `width` properties on individual character objects.
narrative.labelSize = function(_) {
if (!arguments.length) {
return labelSize;
}
labelSize = _;
return narrative;
};
// Label position
// --------------
//
// `narrative.labelPosition([string])`
//
// Set or get the default label position for character labels. Valid options are
// `above`, `below`, `left`, `right`. This can be overridden by setting defining
// a `labelPosition` property on individual character objects.
narrative.labelPosition = function(_) {
if (!arguments.length) {
return labelPosition;
}
labelPosition = _;
return narrative;
};
// Links
// -----
//
// `narrative.links()`
//
// Returns an array of links. Each link is consecutive appearances for a given
// character. Links are an object with `source` and `target` properties which
// are both appearance objects.
narrative.links = function() {
return links;
};
// Link
// ----
//
// `narrative.link()`
//
// Returns a function for generating path strings for links.
// Links are objects with `source` and `target` properties which each contain
// an `x` and `y` property. In the context of the narrative chart these are
// either character apperance or introduction nodes.
narrative.link = function() {
var curvature = 0.5;
// ### Link path
//
// `link([object])`
//
// This function should be used to set the `path` attribute of links when
// displaying the narrative chart. It accepts an object and returns a path
// string linking the two.
function link(d) {
var x0,x1,y0,y1,cx0,cy0,cx1,cy1,ci;
// Set path end positions.
x0 = (d.source.scene) ? d.source.scene.x + d.source.x : d.source.x;
y0 = (d.source.scene) ? d.source.scene.y + d.source.y : d.source.y;
x1 = (d.target.scene) ? d.target.scene.x + d.target.x : d.target.x;
y1 = (d.target.scene) ? d.target.scene.y + d.target.y : d.target.y;
// Set control points.
if (orientation === 'vertical') {
ci = d3.interpolateNumber(y0, y1);
cx0 = x0;
cy0 = ci(curvature);
cx1 = x1;
cy1 = ci(1-curvature);
} else {
ci = d3.interpolateNumber(x0, x1);
cx0 = ci(curvature);
cy0 = y0;
cx1 = ci(1-curvature);
cy1 = y1;
}
return "M" + x0 + "," + y0 +
"C" + cx0 + "," + cy0 +
" " + cx1 + "," + cy1 +
" " + x1 + "," + y1;
}
// ### Curvature
//
// `link.curvature([number])`
//
// Set or get the curvature which should be used to generate links. Should be
// in the range zero to one.
link.curvature = function(_) {
if (!arguments.length) {
return curvature;
}
curvature = _;
return link;
};
return link;
};
// Introductions
// -------------
//
// `narrative.introductions()`
//
// Get an array of character introductions for plotting on the graph. Introductions
// are nodes (usually with labels) displayed before the first scene in which each
// character appears.
narrative.introductions = function() {
return introductions;
};
// Layout
// ------
//
// `narrative.layout()`
//
// Compute the narrative layout. This should be called after all options and
// data have been set and before attempting to use the layout's output for
// display purposes.
narrative.layout = function() {
computeSceneCharacters();
computeCharacterGroups();
setSceneGroups();
computeGroupAppearances();
sortGroups();
computeGroupPositions();
computeCharacterGroupPositions();
sortGroupAppearances();
computeSceneTiming();
computeAppearancePositions();
computeScenePositions();
createIntroductionNodes();
computeIntroductionPositions();
createLinks();
return narrative;
};
// Return the public API.
return narrative;
// Private functions
// =================
// Initial data wrangling
// ----------------------
//
// Populate the scenes with characters from the characters array.
// This method also cleanses the data to exclude characters which appear only once
// and scenes with fewer than two characters.
function computeSceneCharacters() {
var appearances, finished;
// Create a map of scenes to characters (i.e. appearances).
appearances = [];
scenes.forEach(function(scene){
scene.characters.forEach(function(character) {
// If the character isn't an object assume it's an index from the characters array.
character = (typeof character === 'object') ? character : characters[character];
// Note forced character positions and sizes.
character._x = character.x || false;
character._y = character.y || false;
character._width = character.width || false;
character._height = character.height || false;
// Add this appearance to the map.
appearances.push({character: character, scene: scene});
// Setup some properties on the character and scene that we'll need later.
scene.appearances = [];
scene.bounds = getSceneBounds;
character.appearances = [];
});
// note forces scene positions.
scene._x = scene.x || false;
scene._y = scene.y || false;
});
// Recursively filter appearances so we ultimately only include characters
// with more than a single appearance and scenes with more than a single
// character.
while(!finished) {
finished = true;
appearances = appearances.filter(filterAppearances);
}
// Filter appearances.
//
// TODO: this could probably be more efficient (maybe with an index https://gist.github.com/AshKyd/adc7fb024787bd543fc5)
function filterAppearances(appearance){
var counts, keep;
counts = appearances.reduce(function(c, a){
if (appearance.character === a.character) {
c[0]++;
}
if (appearance.scene === a.scene) {
c[1]++;
}
return c;
}, [0,0]);
keep = counts[0] >= 1 && counts[1] >= 1;
finished = finished && keep;
return keep;
}
// Re-construct `characters` and `scenes` arrays with filtered appearances.
characters = [];
scenes = [];
appearances.forEach(function(appearance){
// Cross reference scenes and characters based on appearances.
appearance.scene.appearances.push(appearance);
appearance.character.appearances.push(appearance);
if (characters.indexOf(appearance.character) === -1) {
characters.push(appearance.character);
}
if (scenes.indexOf(appearance.scene) === -1) {
scenes.push(appearance.scene);
}
});
}
// Character clustering
// --------------------
//
// Cluster characters based on their co-occurence in scenes
function computeCharacterGroups() {
var nodes, edges, clusters, partitioner, groupsMap, initGroups;
// An array of character indexes.
nodes = characters.map(function(d,i){return i;});
initGroups = characters.reduce(function(g,d,i){
if (d.initialgroup) {
g[i] = +d.initialgroup;
}
return g;
},{});
// Calculate the edges based on a character's involvement in scenes.
edges = [];
scenes.forEach(function(scene){
edges = edges.concat(sceneEdges(scene.appearances));
});
// Consolidate edges into a unique set of relationships with a weighting
// based on how often they appear together.
edges = edges.reduce(function(result, edge) {
var resultEdge;
resultEdge = result.filter(function(resultEdge){
return (resultEdge.target === edge[0] || resultEdge.target === edge[1]) &&
(resultEdge.source === edge[0] || resultEdge.source === edge[1]);
})[0] || {source: edge[0], target: edge[1], weight: 0};
resultEdge.weight++;
if (resultEdge.weight === 1) {
result.push(resultEdge);
}
return result;
}, []);
// Generate the groups.
partitioner = jLouvain().nodes(nodes).edges(edges);
if (initGroups) {
partitioner.partition_init(initGroups);
}
clusters = partitioner();
// Put all characters in groups with bi-directional reference.
groups = [];
groupsMap = {};
characters.forEach(function(character, i){
var groupId, group;
groupId = clusters[i];
group = groupsMap[groupId];
if (!group) {
group = {id: groupId, characters: []};
groups.push(group);
groupsMap[groupId] = group;
}
group.characters.push(character);
character.group = group;
});
// Creates a single link between each pair of characters in a scene.
function sceneEdges(list) {
var i, j, matrix;
matrix = [];
for (i=list.length;i--;){
for (j=i;j--;){
matrix.push([characters.indexOf(list[i].character),characters.indexOf(list[j].character)]);
}
}
return matrix;
}
}
// Group scenes
// ------------
//
// Each scene is assigned to a group based on the median character group for
// characters appearing in that scene.
// *Note:* "median" here is a mistake, it should be mode.
function setSceneGroups() {
scenes.forEach(function(scene){
var groupCounts, groupCountsMap, medianGroup;
groupCounts = [];
groupCountsMap = {};
scene.appearances.forEach(function(appearance){
var count, index;
index = groups.indexOf(appearance.character.group);
count = groupCountsMap[index];
if (!count) {
count = {groupIndex: index, count: 0};
groupCountsMap[index] = count;
groupCounts.push(count);
}
count.count++;
});
groupCounts.sort(function(a,b){
return a.count-b.count;
});
medianGroup = groups[groupCounts.pop().groupIndex];
// While we're here record how many scenes this group is the modal group for.
medianGroup.medianCount = medianGroup.medianCount || 0;
medianGroup.medianCount++;
scene.group = medianGroup;
});
}
// Group appearances
// -----------------
//
// Assign unique set of characters to each group based on appearances in
// scenes belonging to that group.
function computeGroupAppearances() {
scenes.forEach(function(scene){
var characters;
characters = scene.appearances.map(function(a){
return a.character;
});
scene.group.appearances = scene.group.appearances || [];
scene.group.appearances = scene.group.appearances.concat(characters.filter(function(character){
return scene.group.appearances.indexOf(character) === -1;
}));
});
}
// Sort groups
// -----------
//
// Sort the array of groups so groups which are most often the median are at
// the extremes of the array. The centre most group should be the group which
// is least often the median group of a scene.
function sortGroups() {
var alt, sortedGroups, group, i;
// First sort by the group's medianCount property (the number of times the
// group is the median group in a scene).
groups.sort(function(a,b){
return b.medianCount-a.medianCount;
});
// Specify order property and shuffle out groups into an ordered array.
sortedGroups = [];
i = 0;
while (groups.length) {
group = (alt) ? groups.pop() : groups.shift();
group.order = i;
i++;
sortedGroups.push(group);
alt = !alt;
}
groups = sortedGroups;
}
// Group positions
// ---------------
//
// Compute the actual min and max y-positions of each group.
function computeGroupPositions() {
var max;
max = 0;
groups.forEach(function(group){
group.min = max;
group.max = max = characterGroupHeight(group.appearances.length) + group.min;
max += groupMargin;
});
}
// Character group positions
// -------------------------
//
// Compute the position of each character within its group.
function computeCharacterGroupPositions() {
characters.forEach(function(character){
var sum, count;
sum = count = 0;