Files
d3-spring-model/src/stress.js
Pitchaya Boonsarngsuk 816a086ebd Refactor: Extract getStress
2018-01-19 10:56:30 +00:00

20 lines
728 B
JavaScript

/**
* Calculates the stress. Basically, it computes the difference between
* high dimensional distance and real distance. The lower the stress is,
* the better layout.
* @return {number} - stress of the layout.
*/
export function getStress(nodes, distance) {
let totalDiffSq = 0, totalHighDistSq = 0;
for (let j = 0; j < nodes.length; j++) {
for (let i = 0; i < j; i++) {
let source = nodes[i], target = nodes[j];
let lowDDist = Math.hypot(target.x - source.x, target.y - source.y);
let highDDist = distance(source, target);
totalDiffSq += Math.pow(highDDist - lowDDist, 2);
totalHighDistSq += highDDist * highDDist;
}
}
return Math.sqrt(totalDiffSq / totalHighDistSq);
}