venn.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. (function(venn) {
  2. "use strict";
  3. /** given a list of set objects, and their corresponding overlaps.
  4. updates the (x, y, radius) attribute on each set such that their positions
  5. roughly correspond to the desired overlaps */
  6. venn.venn = function(sets, overlaps, parameters) {
  7. parameters = parameters || {};
  8. parameters.maxIterations = parameters.maxIterations || 500;
  9. var lossFunction = parameters.lossFunction || venn.lossFunction;
  10. var initialLayout = parameters.layoutFunction || venn.greedyLayout;
  11. // initial layout is done greedily
  12. sets = initialLayout(sets, overlaps);
  13. // transform x/y coordinates to a vector to optimize
  14. var initial = new Array(2*sets.length);
  15. for (var i = 0; i < sets.length; ++i) {
  16. initial[2 * i] = sets[i].x;
  17. initial[2 * i + 1] = sets[i].y;
  18. }
  19. // optimize initial layout from our loss function
  20. var totalFunctionCalls = 0;
  21. var solution = venn.fmin(
  22. function(values) {
  23. totalFunctionCalls += 1;
  24. var current = new Array(sets.length);
  25. for (var i = 0; i < sets.length; ++i) {
  26. current[i] = {x: values[2 * i],
  27. y: values[2 * i + 1],
  28. radius : sets[i].radius,
  29. size : sets[i].size};
  30. }
  31. return lossFunction(current, overlaps);
  32. },
  33. initial,
  34. parameters);
  35. // transform solution vector back to x/y points
  36. var positions = solution.solution;
  37. for (i = 0; i < sets.length; ++i) {
  38. sets[i].x = positions[2 * i];
  39. sets[i].y = positions[2 * i + 1];
  40. }
  41. return sets;
  42. };
  43. /** Returns the distance necessary for two circles of radius r1 + r2 to
  44. have the overlap area 'overlap' */
  45. venn.distanceFromIntersectArea = function(r1, r2, overlap) {
  46. // handle complete overlapped circles
  47. if (Math.min(r1, r2) * Math.min(r1,r2) * Math.PI <= overlap) {
  48. return Math.abs(r1 - r2);
  49. }
  50. return venn.bisect(function(distance) {
  51. return venn.circleOverlap(r1, r2, distance) - overlap;
  52. }, 0, r1 + r2);
  53. };
  54. /// gets a matrix of euclidean distances between all sets in venn diagram
  55. venn.getDistanceMatrix = function(sets, overlaps) {
  56. // initialize an empty distance matrix between all the points
  57. var distances = [];
  58. for (var i = 0; i < sets.length; ++i) {
  59. distances.push([]);
  60. for (var j = 0; j < sets.length; ++j) {
  61. distances[i].push(0);
  62. }
  63. }
  64. // compute distances between all the points
  65. for (i = 0; i < overlaps.length; ++i) {
  66. var current = overlaps[i];
  67. if (current.sets.length !== 2) {
  68. continue;
  69. }
  70. var left = current.sets[0],
  71. right = current.sets[1],
  72. r1 = Math.sqrt(sets[left].size / Math.PI),
  73. r2 = Math.sqrt(sets[right].size / Math.PI),
  74. distance = venn.distanceFromIntersectArea(r1, r2, current.size);
  75. distances[left][right] = distances[right][left] = distance;
  76. }
  77. return distances;
  78. };
  79. /** Lays out a Venn diagram greedily, going from most overlapped sets to
  80. least overlapped, attempting to position each new set such that the
  81. overlapping areas to already positioned sets are basically right */
  82. venn.greedyLayout = function(sets, overlaps) {
  83. // give each set a default position + radius
  84. var setOverlaps = {};
  85. for (var i = 0; i < sets.length; ++i) {
  86. setOverlaps[i] = [];
  87. sets[i].radius = Math.sqrt(sets[i].size / Math.PI);
  88. sets[i].x = sets[i].y = 0;
  89. }
  90. // map each set to a list of all the other sets that overlap it
  91. for (i = 0; i < overlaps.length; ++i) {
  92. var current = overlaps[i];
  93. if (current.sets.length !== 2) {
  94. continue;
  95. }
  96. var weight = (current.weight == null) ? 1.0 : current.weight;
  97. var left = current.sets[0], right = current.sets[1];
  98. setOverlaps[left].push ({set:right, size:current.size, weight:weight});
  99. setOverlaps[right].push({set:left, size:current.size, weight:weight});
  100. }
  101. // get list of most overlapped sets
  102. var mostOverlapped = [];
  103. for (var set in setOverlaps) {
  104. if (setOverlaps.hasOwnProperty(set)) {
  105. var size = 0;
  106. for (i = 0; i < setOverlaps[set].length; ++i) {
  107. size += setOverlaps[set][i].size * setOverlaps[set][i].weight;
  108. }
  109. mostOverlapped.push({set: set, size:size});
  110. }
  111. }
  112. // sort by size desc
  113. function sortOrder(a,b) {
  114. return b.size - a.size;
  115. }
  116. mostOverlapped.sort(sortOrder);
  117. // keep track of what sets have been laid out
  118. var positioned = {};
  119. function isPositioned(element) {
  120. return element.set in positioned;
  121. }
  122. // adds a point to the output
  123. function positionSet(point, index) {
  124. sets[index].x = point.x;
  125. sets[index].y = point.y;
  126. positioned[index] = true;
  127. }
  128. // add most overlapped set at (0,0)
  129. positionSet({x: 0, y: 0}, mostOverlapped[0].set);
  130. // get distances between all points
  131. var distances = venn.getDistanceMatrix(sets, overlaps);
  132. for (i = 1; i < mostOverlapped.length; ++i) {
  133. var setIndex = mostOverlapped[i].set,
  134. overlap = setOverlaps[setIndex].filter(isPositioned);
  135. set = sets[setIndex];
  136. overlap.sort(sortOrder);
  137. if (overlap.length === 0) {
  138. throw "Need overlap information for set " + JSON.stringify( set );
  139. }
  140. var points = [];
  141. for (var j = 0; j < overlap.length; ++j) {
  142. // get appropriate distance from most overlapped already added set
  143. var p1 = sets[overlap[j].set],
  144. d1 = distances[setIndex][overlap[j].set];
  145. // sample positions at 90 degrees for maximum aesthetics
  146. points.push({x : p1.x + d1, y : p1.y});
  147. points.push({x : p1.x - d1, y : p1.y});
  148. points.push({y : p1.y + d1, x : p1.x});
  149. points.push({y : p1.y - d1, x : p1.x});
  150. // if we have at least 2 overlaps, then figure out where the
  151. // set should be positioned analytically and try those too
  152. for (var k = j + 1; k < overlap.length; ++k) {
  153. var p2 = sets[overlap[k].set],
  154. d2 = distances[setIndex][overlap[k].set];
  155. var extraPoints = venn.circleCircleIntersection(
  156. { x: p1.x, y: p1.y, radius: d1},
  157. { x: p2.x, y: p2.y, radius: d2});
  158. for (var l = 0; l < extraPoints.length; ++l) {
  159. points.push(extraPoints[l]);
  160. }
  161. }
  162. }
  163. // we have some candidate positions for the set, examine loss
  164. // at each position to figure out where to put it at
  165. var bestLoss = 1e50, bestPoint = points[0];
  166. for (j = 0; j < points.length; ++j) {
  167. sets[setIndex].x = points[j].x;
  168. sets[setIndex].y = points[j].y;
  169. var loss = venn.lossFunction(sets, overlaps);
  170. if (loss < bestLoss) {
  171. bestLoss = loss;
  172. bestPoint = points[j];
  173. }
  174. }
  175. positionSet(bestPoint, setIndex);
  176. }
  177. return sets;
  178. };
  179. /// Uses multidimensional scaling to approximate a first layout here
  180. venn.classicMDSLayout = function(sets, overlaps) {
  181. // get the distance matrix
  182. var distances = venn.getDistanceMatrix(sets, overlaps);
  183. // get positions for each set
  184. var positions = mds.classic(distances);
  185. // translate back to (x,y,radius) coordinates
  186. for (var i = 0; i < sets.length; ++i) {
  187. sets[i].x = positions[i][0];
  188. sets[i].y = positions[i][1];
  189. sets[i].radius = Math.sqrt(sets[i].size / Math.PI);
  190. }
  191. return sets;
  192. };
  193. /** Given a bunch of sets, and the desired overlaps between these sets - computes
  194. the distance from the actual overlaps to the desired overlaps. Note that
  195. this method ignores overlaps of more than 2 circles */
  196. venn.lossFunction = function(sets, overlaps) {
  197. var output = 0;
  198. function getCircles(indices) {
  199. return indices.map(function(i) { return sets[i]; });
  200. }
  201. for (var i = 0; i < overlaps.length; ++i) {
  202. var area = overlaps[i], overlap;
  203. if (area.sets.length == 2) {
  204. var left = sets[area.sets[0]],
  205. right = sets[area.sets[1]];
  206. overlap = venn.circleOverlap(left.radius, right.radius,
  207. venn.distance(left, right));
  208. } else {
  209. overlap = venn.intersectionArea(getCircles(area.sets));
  210. }
  211. var weight = (area.weight == null) ? 1.0 : area.weight;
  212. output += weight * (overlap - area.size) * (overlap - area.size);
  213. }
  214. return output;
  215. };
  216. /** Scales a solution from venn.venn or venn.greedyLayout such that it fits in
  217. a rectangle of width/height - with padding around the borders. also
  218. centers the diagram in the available space at the same time */
  219. venn.scaleSolution = function(solution, width, height, padding) {
  220. var minMax = function(d) {
  221. var hi = Math.max.apply(null, solution.map(
  222. function(c) { return c[d] + c.radius; } )),
  223. lo = Math.min.apply(null, solution.map(
  224. function(c) { return c[d] - c.radius;} ));
  225. return {max:hi, min:lo};
  226. };
  227. width -= 2*padding;
  228. height -= 2*padding;
  229. var xRange = minMax('x'),
  230. yRange = minMax('y'),
  231. xScaling = width / (xRange.max - xRange.min),
  232. yScaling = height / (yRange.max - yRange.min),
  233. scaling = Math.min(yScaling, xScaling),
  234. // while we're at it, center the diagram too
  235. xOffset = (width - (xRange.max - xRange.min) * scaling) / 2,
  236. yOffset = (height - (yRange.max - yRange.min) * scaling) / 2;
  237. for (var i = 0; i < solution.length; ++i) {
  238. var set = solution[i];
  239. set.radius = scaling * set.radius;
  240. set.x = padding + xOffset + (set.x - xRange.min) * scaling;
  241. set.y = padding + yOffset + (set.y - yRange.min) * scaling;
  242. }
  243. return solution;
  244. };
  245. // sometimes text doesn't fit inside the circle, if thats the case lets wrap
  246. // the text here such that it fits
  247. // todo: looks like this might be merged into d3 (
  248. // https://github.com/mbostock/d3/issues/1642),
  249. // also worth checking out is
  250. // http://engineering.findthebest.com/wrapping-axis-labels-in-d3-js/
  251. // this seems to be one of those things that should be easy but isn't
  252. function wrapText() {
  253. var text = d3.select(this),
  254. data = text.datum(),
  255. width = data.radius,
  256. words = data.label.split(/\s+/).reverse(),
  257. maxLines = 3,
  258. minChars = (data.label.length + words.length) / maxLines,
  259. word = words.pop(),
  260. line = [word],
  261. joined,
  262. lineNumber = 0,
  263. lineHeight = 1.1, // ems
  264. tspan = text.text(null).append("tspan").text(word);
  265. while (word = words.pop()) {
  266. line.push(word);
  267. joined = line.join(" ");
  268. tspan.text(joined);
  269. if (joined.length > minChars && tspan.node().getComputedTextLength() > width) {
  270. line.pop();
  271. tspan.text(line.join(" "));
  272. line = [word];
  273. tspan = text.append("tspan").text(word);
  274. lineNumber++;
  275. }
  276. }
  277. var initial = 0.35 - lineNumber * lineHeight / 2,
  278. x = Math.floor(data.textCenter.x),
  279. y = Math.floor(data.textCenter.y);
  280. text.selectAll("tspan")
  281. .attr("x", x)
  282. .attr("y", y)
  283. .attr("dy", function(d, i) {
  284. return (initial + i * lineHeight) + "em";
  285. });
  286. }
  287. function weightedSum(a, b) {
  288. var ret = new Array(a[1].length || 0);
  289. for (var j = 0; j < ret.length; ++j) {
  290. ret[j] = a[0] * a[1][j] + b[0] * b[1][j];
  291. }
  292. return ret;
  293. }
  294. /** finds the zeros of a function, given two starting points (which must
  295. * have opposite signs */
  296. venn.bisect = function(f, a, b, parameters) {
  297. parameters = parameters || {};
  298. var maxIterations = parameters.maxIterations || 100,
  299. tolerance = parameters.tolerance || 1e-10,
  300. fA = f(a),
  301. fB = f(b),
  302. delta = b - a;
  303. if (fA * fB > 0) {
  304. throw "Initial bisect points must have opposite signs";
  305. }
  306. if (fA === 0) return a;
  307. if (fB === 0) return b;
  308. for (var i = 0; i < maxIterations; ++i) {
  309. delta /= 2;
  310. var mid = a + delta,
  311. fMid = f(mid);
  312. if (fMid * fA >= 0) {
  313. a = mid;
  314. }
  315. if ((Math.abs(delta) < tolerance) || (fMid === 0)) {
  316. return mid;
  317. }
  318. }
  319. return a + delta;
  320. };
  321. /** minimizes a function using the downhill simplex method */
  322. venn.fmin = function(f, x0, parameters) {
  323. parameters = parameters || {};
  324. var maxIterations = parameters.maxIterations || x0.length * 200,
  325. nonZeroDelta = parameters.nonZeroDelta || 1.1,
  326. zeroDelta = parameters.zeroDelta || 0.001,
  327. minErrorDelta = parameters.minErrorDelta || 1e-5,
  328. rho = parameters.rho || 1,
  329. chi = parameters.chi || 2,
  330. psi = parameters.psi || -0.5,
  331. sigma = parameters.sigma || 0.5,
  332. callback = parameters.callback;
  333. // initialize simplex.
  334. var N = x0.length,
  335. simplex = new Array(N + 1);
  336. simplex[0] = x0;
  337. simplex[0].fx = f(x0);
  338. for (var i = 0; i < N; ++i) {
  339. var point = x0.slice();
  340. point[i] = point[i] ? point[i] * nonZeroDelta : zeroDelta;
  341. simplex[i+1] = point;
  342. simplex[i+1].fx = f(point);
  343. }
  344. var sortOrder = function(a, b) { return a.fx - b.fx; };
  345. for (var iteration = 0; iteration < maxIterations; ++iteration) {
  346. simplex.sort(sortOrder);
  347. if (callback) {
  348. callback(simplex);
  349. }
  350. if (Math.abs(simplex[0].fx - simplex[N].fx) < minErrorDelta) {
  351. break;
  352. }
  353. // compute the centroid of all but the worst point in the simplex
  354. var centroid = new Array(N);
  355. for (i = 0; i < N; ++i) {
  356. centroid[i] = 0;
  357. for (var j = 0; j < N; ++j) {
  358. centroid[i] += simplex[j][i];
  359. }
  360. centroid[i] /= N;
  361. }
  362. // reflect the worst point past the centroid and compute loss at reflected
  363. // point
  364. var worst = simplex[N];
  365. var reflected = weightedSum([1+rho, centroid], [-rho, worst]);
  366. reflected.fx = f(reflected);
  367. var replacement = reflected;
  368. // if the reflected point is the best seen, then possibly expand
  369. if (reflected.fx <= simplex[0].fx) {
  370. var expanded = weightedSum([1+chi, centroid], [-chi, worst]);
  371. expanded.fx = f(expanded);
  372. if (expanded.fx < reflected.fx) {
  373. replacement = expanded;
  374. }
  375. }
  376. // if the reflected point is worse than the second worst, we need to
  377. // contract
  378. else if (reflected.fx >= simplex[N-1].fx) {
  379. var shouldReduce = false;
  380. var contracted;
  381. if (reflected.fx <= worst.fx) {
  382. // do an inside contraction
  383. contracted = weightedSum([1+psi, centroid], [-psi, worst]);
  384. contracted.fx = f(contracted);
  385. if (contracted.fx < worst.fx) {
  386. replacement = contracted;
  387. } else {
  388. shouldReduce = true;
  389. }
  390. } else {
  391. // do an outside contraction
  392. contracted = weightedSum([1-psi * rho, centroid], [psi*rho, worst]);
  393. contracted.fx = f(contracted);
  394. if (contracted.fx <= reflected.fx) {
  395. replacement = contracted;
  396. } else {
  397. shouldReduce = true;
  398. }
  399. }
  400. if (shouldReduce) {
  401. // do reduction. doesn't actually happen that often
  402. for (i = 1; i < simplex.length; ++i) {
  403. simplex[i] = weightedSum([1 - sigma, simplex[0]],
  404. [sigma - 1, simplex[i]]);
  405. simplex[i].fx = f(simplex[i]);
  406. }
  407. }
  408. }
  409. simplex[N] = replacement;
  410. }
  411. simplex.sort(sortOrder);
  412. return {f : simplex[0].fx,
  413. solution : simplex[0]};
  414. };
  415. /** returns a svg path of the intersection area of a bunch of circles */
  416. venn.intersectionAreaPath = function(circles) {
  417. var stats = {};
  418. venn.intersectionArea(circles, stats);
  419. var arcs = stats.arcs;
  420. if (arcs.length === 0) {
  421. return "M 0 0";
  422. }
  423. var ret = ["\nM", arcs[0].p2.x, arcs[0].p2.y];
  424. for (var i = 0; i < arcs.length; ++i) {
  425. var arc = arcs[i], r = arc.circle.radius, wide = arc.width > r;
  426. ret.push("\nA", r, r, 0, wide ? 1 : 0, 1, arc.p1.x, arc.p1.y);
  427. }
  428. return ret.join(" ");
  429. };
  430. // computes the center for text by sampling perimiter of circle, and taking
  431. // the average of points on perimeter that are only in that circle
  432. function computeTextCenters(sets, width, height, diagram) {
  433. // basically just finding the center point of each region by sampling
  434. // points in a grid and taking the average sampled point for each region
  435. // There is probably an analytic way of computing this exactly, but
  436. // this works well enough for our purposes
  437. var sums = [];
  438. for (var i = 0; i < sets.length; ++i) {
  439. sums.push({'x' : 0, 'y' : 0, 'count' : 0});
  440. }
  441. var samples = 32;
  442. for (var i = 0; i < samples; ++i) {
  443. var x = i * width / samples;
  444. for (var j = 0; j < samples; ++j) {
  445. var y = j * height / samples;
  446. var point = {'x' : x, 'y' : y};
  447. var contained = []
  448. for (var k = 0; k < sets.length; ++k) {
  449. if (venn.distance(point, sets[k]) <= sets[k].radius) {
  450. contained.push(k);
  451. }
  452. }
  453. if (contained.length == 1) {
  454. var sum = sums[contained[0]];
  455. sum.x += point.x;
  456. sum.y += point.y;
  457. sum.count += 1;
  458. }
  459. }
  460. }
  461. for (var i = 0; i < sets.length; ++i) {
  462. var sum = sums[i];
  463. if (sum.count) {
  464. sets[i].textCenter = { 'x' : sum.x / sum.count,
  465. 'y' : sum.y / sum.count};
  466. } else {
  467. // no sampled points, possibly completely overlapped (or tiny)
  468. // use circle centre
  469. sets[i].textCenter = { 'x' : sets[i].x,
  470. 'y' : sets[i].y};
  471. }
  472. }
  473. }
  474. venn.drawD3Diagram = function(element, dataset, width, height, parameters) {
  475. parameters = parameters || {};
  476. var colours = d3.scale.category10(),
  477. padding = ('padding' in parameters) ? parameters.padding : 6;
  478. dataset = venn.scaleSolution(dataset, width, height, padding);
  479. computeTextCenters(dataset, width, height);
  480. var svg = element.append("svg")
  481. .attr("width", width)
  482. .attr("height", height);
  483. var diagram = svg.append( "g" );
  484. var nodes = diagram.append("g").selectAll("circle")
  485. .data(dataset)
  486. .enter()
  487. .append("g");
  488. var circles = nodes.append("circle")
  489. .attr("r", function(d) { return d.radius; })
  490. .style("fill-opacity", 0.3)
  491. .attr("cx", function(d) { return d.x; })
  492. .attr("cy", function(d) { return d.y; })
  493. .style("fill", function(d, i) { return colours(i); });
  494. var text = nodes.append("text")
  495. .attr("dy", ".35em")
  496. .attr("x", function(d) { return Math.floor(d.textCenter.x); })
  497. .attr("y", function(d) { return Math.floor(d.textCenter.y); })
  498. .attr("text-anchor", "middle")
  499. .style("fill", function(d, i) { return colours(i); })
  500. .call(function (text) { text.each(wrapText); });
  501. return {'svg' : svg,
  502. 'nodes' : nodes,
  503. 'circles' : circles,
  504. 'text' : text };
  505. };
  506. venn.updateD3Diagram = function(diagram, dataset, parameters) {
  507. parameters = parameters || {};
  508. var padding = ('padding' in parameters) ? parameters.padding : 6,
  509. duration = ('duration' in parameters) ? parameters.duration : 400;
  510. var svg = diagram.svg,
  511. width = parseInt(svg.attr('width'), 10),
  512. height = parseInt(svg.attr('height'), 10);
  513. dataset = venn.scaleSolution(dataset, width, height, padding);
  514. computeTextCenters(dataset, width, height);
  515. var transition = diagram.nodes
  516. .data(dataset)
  517. .transition()
  518. .duration(duration);
  519. transition.select("circle")
  520. .attr("cx", function(d) { return d.x; })
  521. .attr("cy", function(d) { return d.y; })
  522. .attr("r", function(d) { return d.radius; });
  523. // transtitioning the text is a little tricky in the case
  524. // of wrapping. so lets basically transition unwrapped text
  525. // and at the end of the transition we'll wrap it again
  526. transition.select("text")
  527. .text(function (d) { return d.label; } )
  528. .each("end", wrapText)
  529. .attr("x", function(d) { return Math.floor(d.textCenter.x); })
  530. .attr("y", function(d) { return Math.floor(d.textCenter.y); });
  531. };
  532. var SMALL = 1e-10;
  533. /** Returns the intersection area of a bunch of circles (where each circle
  534. is an object having an x,y and radius property) */
  535. venn.intersectionArea = function(circles, stats) {
  536. // get all the intersection points of the circles
  537. var intersectionPoints = getIntersectionPoints(circles);
  538. // filter out points that aren't included in all the circles
  539. var innerPoints = intersectionPoints.filter(function (p) {
  540. return venn.containedInCircles(p, circles);
  541. });
  542. var arcArea = 0, polygonArea = 0, arcs = [], i;
  543. // if we have intersection points that are within all the circles,
  544. // then figure out the area contained by them
  545. if (innerPoints.length > 1) {
  546. // sort the points by angle from the center of the polygon, which lets
  547. // us just iterate over points to get the edges
  548. var center = venn.getCenter(innerPoints);
  549. for (i = 0; i < innerPoints.length; ++i ) {
  550. var p = innerPoints[i];
  551. p.angle = Math.atan2(p.x - center.x, p.y - center.y);
  552. }
  553. innerPoints.sort(function(a,b) { return b.angle - a.angle;});
  554. // iterate over all points, get arc between the points
  555. // and update the areas
  556. var p2 = innerPoints[innerPoints.length - 1];
  557. for (i = 0; i < innerPoints.length; ++i) {
  558. var p1 = innerPoints[i];
  559. // polygon area updates easily ...
  560. polygonArea += (p2.x + p1.x) * (p1.y - p2.y);
  561. // updating the arc area is a little more involved
  562. var midPoint = {x : (p1.x + p2.x) / 2,
  563. y : (p1.y + p2.y) / 2},
  564. arc = null;
  565. for (var j = 0; j < p1.parentIndex.length; ++j) {
  566. if (p2.parentIndex.indexOf(p1.parentIndex[j]) > -1) {
  567. // figure out the angle halfway between the two points
  568. // on the current circle
  569. var circle = circles[p1.parentIndex[j]],
  570. a1 = Math.atan2(p1.x - circle.x, p1.y - circle.y),
  571. a2 = Math.atan2(p2.x - circle.x, p2.y - circle.y);
  572. var angleDiff = (a2 - a1);
  573. if (angleDiff < 0) {
  574. angleDiff += 2*Math.PI;
  575. }
  576. // and use that angle to figure out the width of the
  577. // arc
  578. var a = a2 - angleDiff/2,
  579. width = venn.distance(midPoint, {
  580. x : circle.x + circle.radius * Math.sin(a),
  581. y : circle.y + circle.radius * Math.cos(a)
  582. });
  583. // pick the circle whose arc has the smallest width
  584. if ((arc === null) || (arc.width > width)) {
  585. arc = { circle : circle,
  586. width : width,
  587. p1 : p1,
  588. p2 : p2};
  589. }
  590. }
  591. }
  592. arcs.push(arc);
  593. arcArea += venn.circleArea(arc.circle.radius, arc.width);
  594. p2 = p1;
  595. }
  596. } else {
  597. // no intersection points, is either disjoint - or is completely
  598. // overlapped. figure out which by examining the smallest circle
  599. var smallest = circles[0];
  600. for (i = 1; i < circles.length; ++i) {
  601. if (circles[i].radius < smallest.radius) {
  602. smallest = circles[i];
  603. }
  604. }
  605. // make sure the smallest circle is completely contained in all
  606. // the other circles
  607. var disjoint = false;
  608. for (i = 0; i < circles.length; ++i) {
  609. if (venn.distance(circles[i], smallest) > Math.abs(smallest.radius - circles[i].radius)) {
  610. disjoint = true;
  611. break;
  612. }
  613. }
  614. if (disjoint) {
  615. arcArea = polygonArea = 0;
  616. } else {
  617. arcArea = smallest.radius * smallest.radius * Math.PI;
  618. arcs.push({circle : smallest,
  619. p1: { x: smallest.x, y : smallest.y + smallest.radius},
  620. p2: { x: smallest.x - SMALL, y : smallest.y + smallest.radius},
  621. width : smallest.radius * 2 });
  622. }
  623. }
  624. polygonArea /= 2;
  625. if (stats) {
  626. stats.area = arcArea + polygonArea;
  627. stats.arcArea = arcArea;
  628. stats.polygonArea = polygonArea;
  629. stats.arcs = arcs;
  630. stats.innerPoints = innerPoints;
  631. stats.intersectionPoints = intersectionPoints;
  632. }
  633. return arcArea + polygonArea;
  634. };
  635. /** returns whether a point is contained by all of a list of circles */
  636. venn.containedInCircles = function(point, circles) {
  637. for (var i = 0; i < circles.length; ++i) {
  638. if (venn.distance(point, circles[i]) > circles[i].radius + SMALL) {
  639. return false;
  640. }
  641. }
  642. return true;
  643. };
  644. /** Gets all intersection points between a bunch of circles */
  645. function getIntersectionPoints(circles) {
  646. var ret = [];
  647. for (var i = 0; i < circles.length; ++i) {
  648. for (var j = i + 1; j < circles.length; ++j) {
  649. var intersect = venn.circleCircleIntersection(circles[i],
  650. circles[j]);
  651. for (var k = 0; k < intersect.length; ++k) {
  652. var p = intersect[k];
  653. p.parentIndex = [i,j];
  654. ret.push(p);
  655. }
  656. }
  657. }
  658. return ret;
  659. }
  660. venn.circleIntegral = function(r, x) {
  661. var y = Math.sqrt(r * r - x * x);
  662. return x * y + r * r * Math.atan2(x, y);
  663. };
  664. /** Returns the area of a circle of radius r - up to width */
  665. venn.circleArea = function(r, width) {
  666. return venn.circleIntegral(r, width - r) - venn.circleIntegral(r, -r);
  667. };
  668. /** euclidean distance between two points */
  669. venn.distance = function(p1, p2) {
  670. return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) +
  671. (p1.y - p2.y) * (p1.y - p2.y));
  672. };
  673. /** Returns the overlap area of two circles of radius r1 and r2 - that
  674. have their centers separated by distance d. Simpler faster
  675. circle intersection for only two circles */
  676. venn.circleOverlap = function(r1, r2, d) {
  677. // no overlap
  678. if (d >= r1 + r2) {
  679. return 0;
  680. }
  681. // completely overlapped
  682. if (d <= Math.abs(r1 - r2)) {
  683. return Math.PI * Math.min(r1, r2) * Math.min(r1, r2);
  684. }
  685. var w1 = r1 - (d * d - r2 * r2 + r1 * r1) / (2 * d),
  686. w2 = r2 - (d * d - r1 * r1 + r2 * r2) / (2 * d);
  687. return venn.circleArea(r1, w1) + venn.circleArea(r2, w2);
  688. };
  689. /** Given two circles (containing a x/y/radius attributes),
  690. returns the intersecting points if possible.
  691. note: doesn't handle cases where there are infinitely many
  692. intersection points (circles are equivalent):, or only one intersection point*/
  693. venn.circleCircleIntersection = function(p1, p2) {
  694. var d = venn.distance(p1, p2),
  695. r1 = p1.radius,
  696. r2 = p2.radius;
  697. // if to far away, or self contained - can't be done
  698. if ((d >= (r1 + r2)) || (d <= Math.abs(r1 - r2))) {
  699. return [];
  700. }
  701. var a = (r1 * r1 - r2 * r2 + d * d) / (2 * d),
  702. h = Math.sqrt(r1 * r1 - a * a),
  703. x0 = p1.x + a * (p2.x - p1.x) / d,
  704. y0 = p1.y + a * (p2.y - p1.y) / d,
  705. rx = -(p2.y - p1.y) * (h / d),
  706. ry = -(p2.x - p1.x) * (h / d);
  707. return [{ x: x0 + rx, y : y0 - ry },
  708. { x: x0 - rx, y : y0 + ry }];
  709. };
  710. /** Returns the center of a bunch of points */
  711. venn.getCenter = function(points) {
  712. var center = { x: 0, y: 0};
  713. for (var i =0; i < points.length; ++i ) {
  714. center.x += points[i].x;
  715. center.y += points[i].y;
  716. }
  717. center.x /= points.length;
  718. center.y /= points.length;
  719. return center;
  720. };
  721. }(window.venn = window.venn || {}));