File size: 37,901 Bytes
bc20498 |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 |
/*
The CoSE layout was written by Gerardo Huck.
https://www.linkedin.com/in/gerardohuck/
Based on the following article:
http://dl.acm.org/citation.cfm?id=1498047
Modifications tracked on Github.
*/
import * as util from '../../util';
import * as math from '../../math';
import * as is from '../../is';
var DEBUG;
/**
* @brief : default layout options
*/
var defaults = {
// Called on `layoutready`
ready: function(){},
// Called on `layoutstop`
stop: function(){},
// Whether to animate while running the layout
// true : Animate continuously as the layout is running
// false : Just show the end result
// 'end' : Animate with the end result, from the initial positions to the end positions
animate: true,
// Easing of the animation for animate:'end'
animationEasing: undefined,
// The duration of the animation for animate:'end'
animationDuration: undefined,
// A function that determines whether the node should be animated
// All nodes animated by default on animate enabled
// Non-animated nodes are positioned immediately when the layout starts
animateFilter: function ( node, i ){ return true; },
// The layout animates only after this many milliseconds for animate:true
// (prevents flashing on fast runs)
animationThreshold: 250,
// Number of iterations between consecutive screen positions update
refresh: 20,
// Whether to fit the network view after when done
fit: true,
// Padding on fit
padding: 30,
// Constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
boundingBox: undefined,
// Excludes the label when calculating node bounding boxes for the layout algorithm
nodeDimensionsIncludeLabels: false,
// Randomize the initial positions of the nodes (true) or use existing positions (false)
randomize: false,
// Extra spacing between components in non-compound graphs
componentSpacing: 40,
// Node repulsion (non overlapping) multiplier
nodeRepulsion: function( node ){ return 2048; },
// Node repulsion (overlapping) multiplier
nodeOverlap: 4,
// Ideal edge (non nested) length
idealEdgeLength: function( edge ){ return 32; },
// Divisor to compute edge forces
edgeElasticity: function( edge ){ return 32; },
// Nesting factor (multiplier) to compute ideal edge length for nested edges
nestingFactor: 1.2,
// Gravity force (constant)
gravity: 1,
// Maximum number of iterations to perform
numIter: 1000,
// Initial temperature (maximum node displacement)
initialTemp: 1000,
// Cooling factor (how the temperature is reduced between consecutive iterations
coolingFactor: 0.99,
// Lower temperature threshold (below this point the layout will end)
minTemp: 1.0
};
/**
* @brief : constructor
* @arg options : object containing layout options
*/
function CoseLayout( options ){
this.options = util.extend( {}, defaults, options );
this.options.layout = this;
// Exclude any edge that has a source or target node that is not in the set of passed-in nodes
const nodes = this.options.eles.nodes();
const edges = this.options.eles.edges();
const notEdges = edges.filter((e) => {
const sourceId = e.source().data('id');
const targetId = e.target().data('id');
const hasSource = nodes.some((n) => n.data('id') === sourceId);
const hasTarget = nodes.some((n) => n.data('id') === targetId);
return !hasSource || !hasTarget;
});
this.options.eles = this.options.eles.not(notEdges);
}
/**
* @brief : runs the layout
*/
CoseLayout.prototype.run = function(){
var options = this.options;
var cy = options.cy;
var layout = this;
layout.stopped = false;
if( options.animate === true || options.animate === false ){
layout.emit( { type: 'layoutstart', layout: layout } );
}
// Set DEBUG - Global variable
if( true === options.debug ){
DEBUG = true;
} else {
DEBUG = false;
}
// Initialize layout info
var layoutInfo = createLayoutInfo( cy, layout, options );
// Show LayoutInfo contents if debugging
if( DEBUG ){
printLayoutInfo( layoutInfo );
}
// If required, randomize node positions
if (options.randomize) {
randomizePositions( layoutInfo, cy );
}
var startTime = util.performanceNow();
var refresh = function(){
refreshPositions( layoutInfo, cy, options );
// Fit the graph if necessary
if( true === options.fit ){
cy.fit( options.padding );
}
};
var mainLoop = function( i ){
if( layout.stopped || i >= options.numIter ){
// logDebug("Layout manually stopped. Stopping computation in step " + i);
return false;
}
// Do one step in the phisical simulation
step( layoutInfo, options, i );
// Update temperature
layoutInfo.temperature = layoutInfo.temperature * options.coolingFactor;
// logDebug("New temperature: " + layoutInfo.temperature);
if( layoutInfo.temperature < options.minTemp ){
// logDebug("Temperature drop below minimum threshold. Stopping computation in step " + i);
return false;
}
return true;
};
var done = function(){
if( options.animate === true || options.animate === false ){
refresh();
// Layout has finished
layout.one('layoutstop', options.stop);
layout.emit({ type: 'layoutstop', layout: layout });
} else {
var nodes = options.eles.nodes();
var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);
nodes.layoutPositions(layout, options, getScaledPos);
}
};
var i = 0;
var loopRet = true;
if( options.animate === true ){
var frame = function(){
var f = 0;
while( loopRet && f < options.refresh ){
loopRet = mainLoop(i);
i++;
f++;
}
if( !loopRet ){ // it's done
separateComponents( layoutInfo, options );
done();
} else {
var now = util.performanceNow();
if( now - startTime >= options.animationThreshold ){
refresh();
}
util.requestAnimationFrame(frame);
}
};
frame();
} else {
while( loopRet ){
loopRet = mainLoop(i);
i++;
}
separateComponents( layoutInfo, options );
done();
}
return this; // chaining
};
/**
* @brief : called on continuous layouts to stop them before they finish
*/
CoseLayout.prototype.stop = function(){
this.stopped = true;
if( this.thread ){
this.thread.stop();
}
this.emit( 'layoutstop' );
return this; // chaining
};
CoseLayout.prototype.destroy = function(){
if( this.thread ){
this.thread.stop();
}
return this; // chaining
};
/**
* @brief : Creates an object which is contains all the data
* used in the layout process
* @arg cy : cytoscape.js object
* @return : layoutInfo object initialized
*/
var createLayoutInfo = function( cy, layout, options ){
// Shortcut
var edges = options.eles.edges();
var nodes = options.eles.nodes();
var bb = math.makeBoundingBox( options.boundingBox ? options.boundingBox : {
x1: 0, y1: 0, w: cy.width(), h: cy.height()
} );
var layoutInfo = {
isCompound: cy.hasCompoundNodes(),
layoutNodes: [],
idToIndex: {},
nodeSize: nodes.size(),
graphSet: [],
indexToGraph: [],
layoutEdges: [],
edgeSize: edges.size(),
temperature: options.initialTemp,
clientWidth: bb.w,
clientHeight: bb.h,
boundingBox: bb
};
var components = options.eles.components();
var id2cmptId = {};
for( var i = 0; i < components.length; i++ ){
var component = components[ i ];
for( var j = 0; j < component.length; j++ ){
var node = component[ j ];
id2cmptId[ node.id() ] = i;
}
}
// Iterate over all nodes, creating layout nodes
for( var i = 0; i < layoutInfo.nodeSize; i++ ){
var n = nodes[ i ];
var nbb = n.layoutDimensions( options );
var tempNode = {};
tempNode.isLocked = n.locked();
tempNode.id = n.data( 'id' );
tempNode.parentId = n.data( 'parent' );
tempNode.cmptId = id2cmptId[ n.id() ];
tempNode.children = [];
tempNode.positionX = n.position( 'x' );
tempNode.positionY = n.position( 'y' );
tempNode.offsetX = 0;
tempNode.offsetY = 0;
tempNode.height = nbb.w;
tempNode.width = nbb.h;
tempNode.maxX = tempNode.positionX + tempNode.width / 2;
tempNode.minX = tempNode.positionX - tempNode.width / 2;
tempNode.maxY = tempNode.positionY + tempNode.height / 2;
tempNode.minY = tempNode.positionY - tempNode.height / 2;
tempNode.padLeft = parseFloat( n.style( 'padding' ) );
tempNode.padRight = parseFloat( n.style( 'padding' ) );
tempNode.padTop = parseFloat( n.style( 'padding' ) );
tempNode.padBottom = parseFloat( n.style( 'padding' ) );
// forces
tempNode.nodeRepulsion = is.fn( options.nodeRepulsion ) ? options.nodeRepulsion(n) : options.nodeRepulsion;
// Add new node
layoutInfo.layoutNodes.push( tempNode );
// Add entry to id-index map
layoutInfo.idToIndex[ tempNode.id ] = i;
}
// Inline implementation of a queue, used for traversing the graph in BFS order
var queue = [];
var start = 0; // Points to the start the queue
var end = -1; // Points to the end of the queue
var tempGraph = [];
// Second pass to add child information and
// initialize queue for hierarchical traversal
for( var i = 0; i < layoutInfo.nodeSize; i++ ){
var n = layoutInfo.layoutNodes[ i ];
var p_id = n.parentId;
// Check if node n has a parent node
if( null != p_id ){
// Add node Id to parent's list of children
layoutInfo.layoutNodes[ layoutInfo.idToIndex[ p_id ] ].children.push( n.id );
} else {
// If a node doesn't have a parent, then it's in the root graph
queue[ ++end ] = n.id;
tempGraph.push( n.id );
}
}
// Add root graph to graphSet
layoutInfo.graphSet.push( tempGraph );
// Traverse the graph, level by level,
while( start <= end ){
// Get the node to visit and remove it from queue
var node_id = queue[ start++ ];
var node_ix = layoutInfo.idToIndex[ node_id ];
var node = layoutInfo.layoutNodes[ node_ix ];
var children = node.children;
if( children.length > 0 ){
// Add children nodes as a new graph to graph set
layoutInfo.graphSet.push( children );
// Add children to que queue to be visited
for( var i = 0; i < children.length; i++ ){
queue[ ++end ] = children[ i ];
}
}
}
// Create indexToGraph map
for( var i = 0; i < layoutInfo.graphSet.length; i++ ){
var graph = layoutInfo.graphSet[ i ];
for( var j = 0; j < graph.length; j++ ){
var index = layoutInfo.idToIndex[ graph[ j ] ];
layoutInfo.indexToGraph[ index ] = i;
}
}
// Iterate over all edges, creating Layout Edges
for( var i = 0; i < layoutInfo.edgeSize; i++ ){
var e = edges[ i ];
var tempEdge = {};
tempEdge.id = e.data( 'id' );
tempEdge.sourceId = e.data( 'source' );
tempEdge.targetId = e.data( 'target' );
// Compute ideal length
var idealLength = is.fn( options.idealEdgeLength ) ? options.idealEdgeLength(e) : options.idealEdgeLength;
var elasticity = is.fn( options.edgeElasticity ) ? options.edgeElasticity(e) : options.edgeElasticity;
// Check if it's an inter graph edge
var sourceIx = layoutInfo.idToIndex[ tempEdge.sourceId ];
var targetIx = layoutInfo.idToIndex[ tempEdge.targetId ];
var sourceGraph = layoutInfo.indexToGraph[ sourceIx ];
var targetGraph = layoutInfo.indexToGraph[ targetIx ];
if( sourceGraph != targetGraph ){
// Find lowest common graph ancestor
var lca = findLCA( tempEdge.sourceId, tempEdge.targetId, layoutInfo );
// Compute sum of node depths, relative to lca graph
var lcaGraph = layoutInfo.graphSet[ lca ];
var depth = 0;
// Source depth
var tempNode = layoutInfo.layoutNodes[ sourceIx ];
while( -1 === lcaGraph.indexOf( tempNode.id ) ){
tempNode = layoutInfo.layoutNodes[ layoutInfo.idToIndex[ tempNode.parentId ] ];
depth++;
}
// Target depth
tempNode = layoutInfo.layoutNodes[ targetIx ];
while( -1 === lcaGraph.indexOf( tempNode.id ) ){
tempNode = layoutInfo.layoutNodes[ layoutInfo.idToIndex[ tempNode.parentId ] ];
depth++;
}
// logDebug('LCA of nodes ' + tempEdge.sourceId + ' and ' + tempEdge.targetId +
// ". Index: " + lca + " Contents: " + lcaGraph.toString() +
// ". Depth: " + depth);
// Update idealLength
idealLength *= depth * options.nestingFactor;
}
tempEdge.idealLength = idealLength;
tempEdge.elasticity = elasticity;
layoutInfo.layoutEdges.push( tempEdge );
}
// Finally, return layoutInfo object
return layoutInfo;
};
/**
* @brief : This function finds the index of the lowest common
* graph ancestor between 2 nodes in the subtree
* (from the graph hierarchy induced tree) whose
* root is graphIx
*
* @arg node1: node1's ID
* @arg node2: node2's ID
* @arg layoutInfo: layoutInfo object
*
*/
var findLCA = function( node1, node2, layoutInfo ){
// Find their common ancester, starting from the root graph
var res = findLCA_aux( node1, node2, 0, layoutInfo );
if( 2 > res.count ){
// If aux function couldn't find the common ancester,
// then it is the root graph
return 0;
} else {
return res.graph;
}
};
/**
* @brief : Auxiliary function used for LCA computation
*
* @arg node1 : node1's ID
* @arg node2 : node2's ID
* @arg graphIx : subgraph index
* @arg layoutInfo : layoutInfo object
*
* @return : object of the form {count: X, graph: Y}, where:
* X is the number of ancestors (max: 2) found in
* graphIx (and it's subgraphs),
* Y is the graph index of the lowest graph containing
* all X nodes
*/
var findLCA_aux = function( node1, node2, graphIx, layoutInfo ){
var graph = layoutInfo.graphSet[ graphIx ];
// If both nodes belongs to graphIx
if( -1 < graph.indexOf( node1 ) && -1 < graph.indexOf( node2 ) ){
return {count: 2, graph: graphIx};
}
// Make recursive calls for all subgraphs
var c = 0;
for( var i = 0; i < graph.length; i++ ){
var nodeId = graph[ i ];
var nodeIx = layoutInfo.idToIndex[ nodeId ];
var children = layoutInfo.layoutNodes[ nodeIx ].children;
// If the node has no child, skip it
if( 0 === children.length ){
continue;
}
var childGraphIx = layoutInfo.indexToGraph[ layoutInfo.idToIndex[ children[0] ] ];
var result = findLCA_aux( node1, node2, childGraphIx, layoutInfo );
if( 0 === result.count ){
// Neither node1 nor node2 are present in this subgraph
continue;
} else if( 1 === result.count ){
// One of (node1, node2) is present in this subgraph
c++;
if( 2 === c ){
// We've already found both nodes, no need to keep searching
break;
}
} else {
// Both nodes are present in this subgraph
return result;
}
}
return {count: c, graph: graphIx};
};
/**
* @brief: printsLayoutInfo into js console
* Only used for debbuging
*/
if( process.env.NODE_ENV !== 'production' ){
var printLayoutInfo = function( layoutInfo ){
/* eslint-disable */
if( !DEBUG ){
return;
}
console.debug( 'layoutNodes:' );
for( var i = 0; i < layoutInfo.nodeSize; i++ ){
var n = layoutInfo.layoutNodes[ i ];
var s =
'\nindex: ' + i +
'\nId: ' + n.id +
'\nChildren: ' + n.children.toString() +
'\nparentId: ' + n.parentId +
'\npositionX: ' + n.positionX +
'\npositionY: ' + n.positionY +
'\nOffsetX: ' + n.offsetX +
'\nOffsetY: ' + n.offsetY +
'\npadLeft: ' + n.padLeft +
'\npadRight: ' + n.padRight +
'\npadTop: ' + n.padTop +
'\npadBottom: ' + n.padBottom;
console.debug( s );
}
console.debug( 'idToIndex' );
for( var i in layoutInfo.idToIndex ){
console.debug( 'Id: ' + i + '\nIndex: ' + layoutInfo.idToIndex[ i ] );
}
console.debug( 'Graph Set' );
var set = layoutInfo.graphSet;
for( var i = 0; i < set.length; i ++ ){
console.debug( 'Set : ' + i + ': ' + set[ i ].toString() );
}
var s = 'IndexToGraph';
for( var i = 0; i < layoutInfo.indexToGraph.length; i ++ ){
s += '\nIndex : ' + i + ' Graph: ' + layoutInfo.indexToGraph[ i ];
}
console.debug( s );
s = 'Layout Edges';
for( var i = 0; i < layoutInfo.layoutEdges.length; i++ ){
var e = layoutInfo.layoutEdges[ i ];
s += '\nEdge Index: ' + i + ' ID: ' + e.id +
' SouceID: ' + e.sourceId + ' TargetId: ' + e.targetId +
' Ideal Length: ' + e.idealLength;
}
console.debug( s );
s = 'nodeSize: ' + layoutInfo.nodeSize;
s += '\nedgeSize: ' + layoutInfo.edgeSize;
s += '\ntemperature: ' + layoutInfo.temperature;
console.debug( s );
return;
/* eslint-enable */
};
}
/**
* @brief : Randomizes the position of all nodes
*/
var randomizePositions = function( layoutInfo, cy ){
var width = layoutInfo.clientWidth;
var height = layoutInfo.clientHeight;
for( var i = 0; i < layoutInfo.nodeSize; i++ ){
var n = layoutInfo.layoutNodes[ i ];
// No need to randomize compound nodes or locked nodes
if( 0 === n.children.length && !n.isLocked ){
n.positionX = Math.random() * width;
n.positionY = Math.random() * height;
}
}
};
var getScaleInBoundsFn = function( layoutInfo, options, nodes ){
var bb = layoutInfo.boundingBox;
var coseBB = { x1: Infinity, x2: -Infinity, y1: Infinity, y2: -Infinity };
if( options.boundingBox ){
nodes.forEach( function( node ){
var lnode = layoutInfo.layoutNodes[ layoutInfo.idToIndex[ node.data( 'id' ) ] ];
coseBB.x1 = Math.min( coseBB.x1, lnode.positionX );
coseBB.x2 = Math.max( coseBB.x2, lnode.positionX );
coseBB.y1 = Math.min( coseBB.y1, lnode.positionY );
coseBB.y2 = Math.max( coseBB.y2, lnode.positionY );
} );
coseBB.w = coseBB.x2 - coseBB.x1;
coseBB.h = coseBB.y2 - coseBB.y1;
}
return function( ele, i ){
var lnode = layoutInfo.layoutNodes[ layoutInfo.idToIndex[ ele.data( 'id' ) ] ];
if( options.boundingBox ){ // then add extra bounding box constraint
var pctX = (lnode.positionX - coseBB.x1) / coseBB.w;
var pctY = (lnode.positionY - coseBB.y1) / coseBB.h;
return {
x: bb.x1 + pctX * bb.w,
y: bb.y1 + pctY * bb.h
};
} else {
return {
x: lnode.positionX,
y: lnode.positionY
};
}
};
};
/**
* @brief : Updates the positions of nodes in the network
* @arg layoutInfo : LayoutInfo object
* @arg cy : Cytoscape object
* @arg options : Layout options
*/
var refreshPositions = function( layoutInfo, cy, options ){
// var s = 'Refreshing positions';
// logDebug(s);
var layout = options.layout;
var nodes = options.eles.nodes();
var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);
nodes.positions(getScaledPos);
// Trigger layoutReady only on first call
if( true !== layoutInfo.ready ){
// s = 'Triggering layoutready';
// logDebug(s);
layoutInfo.ready = true;
layout.one( 'layoutready', options.ready );
layout.emit( { type: 'layoutready', layout: this } );
}
};
/**
* @brief : Logs a debug message in JS console, if DEBUG is ON
*/
// var logDebug = function(text) {
// if (DEBUG) {
// console.debug(text);
// }
// };
/**
* @brief : Performs one iteration of the physical simulation
* @arg layoutInfo : LayoutInfo object already initialized
* @arg cy : Cytoscape object
* @arg options : Layout options
*/
var step = function( layoutInfo, options, step ){
// var s = "\n\n###############################";
// s += "\nSTEP: " + step;
// s += "\n###############################\n";
// logDebug(s);
// Calculate node repulsions
calculateNodeForces( layoutInfo, options );
// Calculate edge forces
calculateEdgeForces( layoutInfo, options );
// Calculate gravity forces
calculateGravityForces( layoutInfo, options );
// Propagate forces from parent to child
propagateForces( layoutInfo, options );
// Update positions based on calculated forces
updatePositions( layoutInfo, options );
};
/**
* @brief : Computes the node repulsion forces
*/
var calculateNodeForces = function( layoutInfo, options ){
// Go through each of the graphs in graphSet
// Nodes only repel each other if they belong to the same graph
// var s = 'calculateNodeForces';
// logDebug(s);
for( var i = 0; i < layoutInfo.graphSet.length; i ++ ){
var graph = layoutInfo.graphSet[ i ];
var numNodes = graph.length;
// s = "Set: " + graph.toString();
// logDebug(s);
// Now get all the pairs of nodes
// Only get each pair once, (A, B) = (B, A)
for( var j = 0; j < numNodes; j++ ){
var node1 = layoutInfo.layoutNodes[ layoutInfo.idToIndex[ graph[ j ] ] ];
for( var k = j + 1; k < numNodes; k++ ){
var node2 = layoutInfo.layoutNodes[ layoutInfo.idToIndex[ graph[ k ] ] ];
nodeRepulsion( node1, node2, layoutInfo, options );
}
}
}
};
var randomDistance = function( max ){
return -max + 2 * max * Math.random();
};
/**
* @brief : Compute the node repulsion forces between a pair of nodes
*/
var nodeRepulsion = function( node1, node2, layoutInfo, options ){
// var s = "Node repulsion. Node1: " + node1.id + " Node2: " + node2.id;
var cmptId1 = node1.cmptId;
var cmptId2 = node2.cmptId;
if( cmptId1 !== cmptId2 && !layoutInfo.isCompound ){ return; }
// Get direction of line connecting both node centers
var directionX = node2.positionX - node1.positionX;
var directionY = node2.positionY - node1.positionY;
var maxRandDist = 1;
// s += "\ndirectionX: " + directionX + ", directionY: " + directionY;
// If both centers are the same, apply a random force
if( 0 === directionX && 0 === directionY ){
directionX = randomDistance( maxRandDist );
directionY = randomDistance( maxRandDist );
}
var overlap = nodesOverlap( node1, node2, directionX, directionY );
if( overlap > 0 ){
// s += "\nNodes DO overlap.";
// s += "\nOverlap: " + overlap;
// If nodes overlap, repulsion force is proportional
// to the overlap
var force = options.nodeOverlap * overlap;
// Compute the module and components of the force vector
var distance = Math.sqrt( directionX * directionX + directionY * directionY );
// s += "\nDistance: " + distance;
var forceX = force * directionX / distance;
var forceY = force * directionY / distance;
} else {
// s += "\nNodes do NOT overlap.";
// If there's no overlap, force is inversely proportional
// to squared distance
// Get clipping points for both nodes
var point1 = findClippingPoint( node1, directionX, directionY );
var point2 = findClippingPoint( node2, -1 * directionX, -1 * directionY );
// Use clipping points to compute distance
var distanceX = point2.x - point1.x;
var distanceY = point2.y - point1.y;
var distanceSqr = distanceX * distanceX + distanceY * distanceY;
var distance = Math.sqrt( distanceSqr );
// s += "\nDistance: " + distance;
// Compute the module and components of the force vector
var force = ( node1.nodeRepulsion + node2.nodeRepulsion ) / distanceSqr;
var forceX = force * distanceX / distance;
var forceY = force * distanceY / distance;
}
// Apply force
if( !node1.isLocked ){
node1.offsetX -= forceX;
node1.offsetY -= forceY;
}
if( !node2.isLocked ){
node2.offsetX += forceX;
node2.offsetY += forceY;
}
// s += "\nForceX: " + forceX + " ForceY: " + forceY;
// logDebug(s);
return;
};
/**
* @brief : Determines whether two nodes overlap or not
* @return : Amount of overlapping (0 => no overlap)
*/
var nodesOverlap = function( node1, node2, dX, dY ){
if( dX > 0 ){
var overlapX = node1.maxX - node2.minX;
} else {
var overlapX = node2.maxX - node1.minX;
}
if( dY > 0 ){
var overlapY = node1.maxY - node2.minY;
} else {
var overlapY = node2.maxY - node1.minY;
}
if( overlapX >= 0 && overlapY >= 0 ){
return Math.sqrt( overlapX * overlapX + overlapY * overlapY );
} else {
return 0;
}
};
/**
* @brief : Finds the point in which an edge (direction dX, dY) intersects
* the rectangular bounding box of it's source/target node
*/
var findClippingPoint = function( node, dX, dY ){
// Shorcuts
var X = node.positionX;
var Y = node.positionY;
var H = node.height || 1;
var W = node.width || 1;
var dirSlope = dY / dX;
var nodeSlope = H / W;
// var s = 'Computing clipping point of node ' + node.id +
// " . Height: " + H + ", Width: " + W +
// "\nDirection " + dX + ", " + dY;
//
// Compute intersection
var res = {};
// Case: Vertical direction (up)
if( 0 === dX && 0 < dY ){
res.x = X;
// s += "\nUp direction";
res.y = Y + H / 2;
return res;
}
// Case: Vertical direction (down)
if( 0 === dX && 0 > dY ){
res.x = X;
res.y = Y + H / 2;
// s += "\nDown direction";
return res;
}
// Case: Intersects the right border
if( 0 < dX &&
-1 * nodeSlope <= dirSlope &&
dirSlope <= nodeSlope ){
res.x = X + W / 2;
res.y = Y + (W * dY / 2 / dX);
// s += "\nRightborder";
return res;
}
// Case: Intersects the left border
if( 0 > dX &&
-1 * nodeSlope <= dirSlope &&
dirSlope <= nodeSlope ){
res.x = X - W / 2;
res.y = Y - (W * dY / 2 / dX);
// s += "\nLeftborder";
return res;
}
// Case: Intersects the top border
if( 0 < dY &&
( dirSlope <= -1 * nodeSlope ||
dirSlope >= nodeSlope ) ){
res.x = X + (H * dX / 2 / dY);
res.y = Y + H / 2;
// s += "\nTop border";
return res;
}
// Case: Intersects the bottom border
if( 0 > dY &&
( dirSlope <= -1 * nodeSlope ||
dirSlope >= nodeSlope ) ){
res.x = X - (H * dX / 2 / dY);
res.y = Y - H / 2;
// s += "\nBottom border";
return res;
}
// s += "\nClipping point found at " + res.x + ", " + res.y;
// logDebug(s);
return res;
};
/**
* @brief : Calculates all edge forces
*/
var calculateEdgeForces = function( layoutInfo, options ){
// Iterate over all edges
for( var i = 0; i < layoutInfo.edgeSize; i++ ){
// Get edge, source & target nodes
var edge = layoutInfo.layoutEdges[ i ];
var sourceIx = layoutInfo.idToIndex[ edge.sourceId ];
var source = layoutInfo.layoutNodes[ sourceIx ];
var targetIx = layoutInfo.idToIndex[ edge.targetId ];
var target = layoutInfo.layoutNodes[ targetIx ];
// Get direction of line connecting both node centers
var directionX = target.positionX - source.positionX;
var directionY = target.positionY - source.positionY;
// If both centers are the same, do nothing.
// A random force has already been applied as node repulsion
if( 0 === directionX && 0 === directionY ){
continue;
}
// Get clipping points for both nodes
var point1 = findClippingPoint( source, directionX, directionY );
var point2 = findClippingPoint( target, -1 * directionX, -1 * directionY );
var lx = point2.x - point1.x;
var ly = point2.y - point1.y;
var l = Math.sqrt( lx * lx + ly * ly );
var force = Math.pow( edge.idealLength - l, 2 ) / edge.elasticity;
if( 0 !== l ){
var forceX = force * lx / l;
var forceY = force * ly / l;
} else {
var forceX = 0;
var forceY = 0;
}
// Add this force to target and source nodes
if( !source.isLocked ){
source.offsetX += forceX;
source.offsetY += forceY;
}
if( !target.isLocked ){
target.offsetX -= forceX;
target.offsetY -= forceY;
}
// var s = 'Edge force between nodes ' + source.id + ' and ' + target.id;
// s += "\nDistance: " + l + " Force: (" + forceX + ", " + forceY + ")";
// logDebug(s);
}
};
/**
* @brief : Computes gravity forces for all nodes
*/
var calculateGravityForces = function( layoutInfo, options ){
if (options.gravity === 0) {
return;
}
var distThreshold = 1;
// var s = 'calculateGravityForces';
// logDebug(s);
for( var i = 0; i < layoutInfo.graphSet.length; i ++ ){
var graph = layoutInfo.graphSet[ i ];
var numNodes = graph.length;
// s = "Set: " + graph.toString();
// logDebug(s);
// Compute graph center
if( 0 === i ){
var centerX = layoutInfo.clientHeight / 2;
var centerY = layoutInfo.clientWidth / 2;
} else {
// Get Parent node for this graph, and use its position as center
var temp = layoutInfo.layoutNodes[ layoutInfo.idToIndex[ graph[0] ] ];
var parent = layoutInfo.layoutNodes[ layoutInfo.idToIndex[ temp.parentId ] ];
var centerX = parent.positionX;
var centerY = parent.positionY;
}
// s = "Center found at: " + centerX + ", " + centerY;
// logDebug(s);
// Apply force to all nodes in graph
for( var j = 0; j < numNodes; j++ ){
var node = layoutInfo.layoutNodes[ layoutInfo.idToIndex[ graph[ j ] ] ];
// s = "Node: " + node.id;
if( node.isLocked ){ continue; }
var dx = centerX - node.positionX;
var dy = centerY - node.positionY;
var d = Math.sqrt( dx * dx + dy * dy );
if( d > distThreshold ){
var fx = options.gravity * dx / d;
var fy = options.gravity * dy / d;
node.offsetX += fx;
node.offsetY += fy;
// s += ": Applied force: " + fx + ", " + fy;
} else {
// s += ": skypped since it's too close to center";
}
// logDebug(s);
}
}
};
/**
* @brief : This function propagates the existing offsets from
* parent nodes to its descendents.
* @arg layoutInfo : layoutInfo Object
* @arg cy : cytoscape Object
* @arg options : Layout options
*/
var propagateForces = function( layoutInfo, options ){
// Inline implementation of a queue, used for traversing the graph in BFS order
var queue = [];
var start = 0; // Points to the start the queue
var end = -1; // Points to the end of the queue
// logDebug('propagateForces');
// Start by visiting the nodes in the root graph
queue.push.apply( queue, layoutInfo.graphSet[0] );
end += layoutInfo.graphSet[0].length;
// Traverse the graph, level by level,
while( start <= end ){
// Get the node to visit and remove it from queue
var nodeId = queue[ start++ ];
var nodeIndex = layoutInfo.idToIndex[ nodeId ];
var node = layoutInfo.layoutNodes[ nodeIndex ];
var children = node.children;
// We only need to process the node if it's compound
if( 0 < children.length && !node.isLocked ){
var offX = node.offsetX;
var offY = node.offsetY;
// var s = "Propagating offset from parent node : " + node.id +
// ". OffsetX: " + offX + ". OffsetY: " + offY;
// s += "\n Children: " + children.toString();
// logDebug(s);
for( var i = 0; i < children.length; i++ ){
var childNode = layoutInfo.layoutNodes[ layoutInfo.idToIndex[ children[ i ] ] ];
// Propagate offset
childNode.offsetX += offX;
childNode.offsetY += offY;
// Add children to queue to be visited
queue[ ++end ] = children[ i ];
}
// Reset parent offsets
node.offsetX = 0;
node.offsetY = 0;
}
}
};
/**
* @brief : Updates the layout model positions, based on
* the accumulated forces
*/
var updatePositions = function( layoutInfo, options ){
// var s = 'Updating positions';
// logDebug(s);
// Reset boundaries for compound nodes
for( var i = 0; i < layoutInfo.nodeSize; i++ ){
var n = layoutInfo.layoutNodes[ i ];
if( 0 < n.children.length ){
// logDebug("Resetting boundaries of compound node: " + n.id);
n.maxX = undefined;
n.minX = undefined;
n.maxY = undefined;
n.minY = undefined;
}
}
for( var i = 0; i < layoutInfo.nodeSize; i++ ){
var n = layoutInfo.layoutNodes[ i ];
if( 0 < n.children.length || n.isLocked ){
// No need to set compound or locked node position
// logDebug("Skipping position update of node: " + n.id);
continue;
}
// s = "Node: " + n.id + " Previous position: (" +
// n.positionX + ", " + n.positionY + ").";
// Limit displacement in order to improve stability
var tempForce = limitForce( n.offsetX, n.offsetY, layoutInfo.temperature );
n.positionX += tempForce.x;
n.positionY += tempForce.y;
n.offsetX = 0;
n.offsetY = 0;
n.minX = n.positionX - n.width;
n.maxX = n.positionX + n.width;
n.minY = n.positionY - n.height;
n.maxY = n.positionY + n.height;
// s += " New Position: (" + n.positionX + ", " + n.positionY + ").";
// logDebug(s);
// Update ancestry boudaries
updateAncestryBoundaries( n, layoutInfo );
}
// Update size, position of compund nodes
for( var i = 0; i < layoutInfo.nodeSize; i++ ){
var n = layoutInfo.layoutNodes[ i ];
if( 0 < n.children.length && !n.isLocked ){
n.positionX = (n.maxX + n.minX) / 2;
n.positionY = (n.maxY + n.minY) / 2;
n.width = n.maxX - n.minX;
n.height = n.maxY - n.minY;
// s = "Updating position, size of compound node " + n.id;
// s += "\nPositionX: " + n.positionX + ", PositionY: " + n.positionY;
// s += "\nWidth: " + n.width + ", Height: " + n.height;
// logDebug(s);
}
}
};
/**
* @brief : Limits a force (forceX, forceY) to be not
* greater (in modulo) than max.
8 Preserves force direction.
*/
var limitForce = function( forceX, forceY, max ){
// var s = "Limiting force: (" + forceX + ", " + forceY + "). Max: " + max;
var force = Math.sqrt( forceX * forceX + forceY * forceY );
if( force > max ){
var res = {
x: max * forceX / force,
y: max * forceY / force
};
} else {
var res = {
x: forceX,
y: forceY
};
}
// s += ".\nResult: (" + res.x + ", " + res.y + ")";
// logDebug(s);
return res;
};
/**
* @brief : Function used for keeping track of compound node
* sizes, since they should bound all their subnodes.
*/
var updateAncestryBoundaries = function( node, layoutInfo ){
// var s = "Propagating new position/size of node " + node.id;
var parentId = node.parentId;
if( null == parentId ){
// If there's no parent, we are done
// s += ". No parent node.";
// logDebug(s);
return;
}
// Get Parent Node
var p = layoutInfo.layoutNodes[ layoutInfo.idToIndex[ parentId ] ];
var flag = false;
// MaxX
if( null == p.maxX || node.maxX + p.padRight > p.maxX ){
p.maxX = node.maxX + p.padRight;
flag = true;
// s += "\nNew maxX for parent node " + p.id + ": " + p.maxX;
}
// MinX
if( null == p.minX || node.minX - p.padLeft < p.minX ){
p.minX = node.minX - p.padLeft;
flag = true;
// s += "\nNew minX for parent node " + p.id + ": " + p.minX;
}
// MaxY
if( null == p.maxY || node.maxY + p.padBottom > p.maxY ){
p.maxY = node.maxY + p.padBottom;
flag = true;
// s += "\nNew maxY for parent node " + p.id + ": " + p.maxY;
}
// MinY
if( null == p.minY || node.minY - p.padTop < p.minY ){
p.minY = node.minY - p.padTop;
flag = true;
// s += "\nNew minY for parent node " + p.id + ": " + p.minY;
}
// If updated boundaries, propagate changes upward
if( flag ){
// logDebug(s);
return updateAncestryBoundaries( p, layoutInfo );
}
// s += ". No changes in boundaries/position of parent node " + p.id;
// logDebug(s);
return;
};
var separateComponents = function( layoutInfo, options ){
var nodes = layoutInfo.layoutNodes;
var components = [];
for( var i = 0; i < nodes.length; i++ ){
var node = nodes[ i ];
var cid = node.cmptId;
var component = components[ cid ] = components[ cid ] || [];
component.push( node );
}
var totalA = 0;
for( var i = 0; i < components.length; i++ ){
var c = components[ i ];
if( !c ){ continue; }
c.x1 = Infinity;
c.x2 = -Infinity;
c.y1 = Infinity;
c.y2 = -Infinity;
for( var j = 0; j < c.length; j++ ){
var n = c[ j ];
c.x1 = Math.min( c.x1, n.positionX - n.width / 2 );
c.x2 = Math.max( c.x2, n.positionX + n.width / 2 );
c.y1 = Math.min( c.y1, n.positionY - n.height / 2 );
c.y2 = Math.max( c.y2, n.positionY + n.height / 2 );
}
c.w = c.x2 - c.x1;
c.h = c.y2 - c.y1;
totalA += c.w * c.h;
}
components.sort( function( c1, c2 ){
return c2.w * c2.h - c1.w * c1.h;
} );
var x = 0;
var y = 0;
var usedW = 0;
var rowH = 0;
var maxRowW = Math.sqrt( totalA ) * layoutInfo.clientWidth / layoutInfo.clientHeight;
for( var i = 0; i < components.length; i++ ){
var c = components[ i ];
if( !c ){ continue; }
for( var j = 0; j < c.length; j++ ){
var n = c[ j ];
if( !n.isLocked ){
n.positionX += (x - c.x1);
n.positionY += (y - c.y1);
}
}
x += c.w + options.componentSpacing;
usedW += c.w + options.componentSpacing;
rowH = Math.max( rowH, c.h );
if( usedW > maxRowW ){
y += rowH + options.componentSpacing;
x = 0;
usedW = 0;
rowH = 0;
}
}
};
export default CoseLayout;
|