VennSeries.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. /* *
  2. *
  3. * Experimental Highcharts module which enables visualization of a Venn
  4. * diagram.
  5. *
  6. * (c) 2016-2020 Highsoft AS
  7. * Authors: Jon Arild Nygard
  8. *
  9. * Layout algorithm by Ben Frederickson:
  10. * https://www.benfrederickson.com/better-venn-diagrams/
  11. *
  12. * License: www.highcharts.com/license
  13. *
  14. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  15. *
  16. * */
  17. import A from '../Core/Animation/AnimationUtilities.js';
  18. var animObject = A.animObject;
  19. import BaseSeries from '../Core/Series/Series.js';
  20. var seriesTypes = BaseSeries.seriesTypes;
  21. import Color from '../Core/Color/Color.js';
  22. var color = Color.parse;
  23. import DrawPointMixin from '../Mixins/DrawPoint.js';
  24. var draw = DrawPointMixin.draw;
  25. import GeometryMixin from '../Mixins/Geometry.js';
  26. var getCenterOfPoints = GeometryMixin.getCenterOfPoints, getDistanceBetweenPoints = GeometryMixin.getDistanceBetweenPoints;
  27. import GeometryCirclesModule from '../Mixins/GeometryCircles.js';
  28. var getAreaOfCircle = GeometryCirclesModule.getAreaOfCircle, getAreaOfIntersectionBetweenCircles = GeometryCirclesModule.getAreaOfIntersectionBetweenCircles, getCircleCircleIntersection = GeometryCirclesModule.getCircleCircleIntersection, getCirclesIntersectionPolygon = GeometryCirclesModule.getCirclesIntersectionPolygon, getOverlapBetweenCirclesByDistance = GeometryCirclesModule.getOverlapBetweenCircles, isCircle1CompletelyOverlappingCircle2 = GeometryCirclesModule.isCircle1CompletelyOverlappingCircle2, isPointInsideAllCircles = GeometryCirclesModule.isPointInsideAllCircles, isPointInsideCircle = GeometryCirclesModule.isPointInsideCircle, isPointOutsideAllCircles = GeometryCirclesModule.isPointOutsideAllCircles;
  29. import NelderMeadMixin from '../Mixins/NelderMead.js';
  30. var nelderMead = NelderMeadMixin.nelderMead;
  31. import U from '../Core/Utilities.js';
  32. var addEvent = U.addEvent, extend = U.extend, isArray = U.isArray, isNumber = U.isNumber, isObject = U.isObject, isString = U.isString, merge = U.merge;
  33. import './ScatterSeries.js';
  34. var objectValues = function objectValues(obj) {
  35. return Object.keys(obj).map(function (x) {
  36. return obj[x];
  37. });
  38. };
  39. /**
  40. * Calculates the area of overlap between a list of circles.
  41. * @private
  42. * @todo add support for calculating overlap between more than 2 circles.
  43. * @param {Array<Highcharts.CircleObject>} circles
  44. * List of circles with their given positions.
  45. * @return {number}
  46. * Returns the area of overlap between all the circles.
  47. */
  48. var getOverlapBetweenCircles = function getOverlapBetweenCircles(circles) {
  49. var overlap = 0;
  50. // When there is only two circles we can find the overlap by using their
  51. // radiuses and the distance between them.
  52. if (circles.length === 2) {
  53. var circle1 = circles[0];
  54. var circle2 = circles[1];
  55. overlap = getOverlapBetweenCirclesByDistance(circle1.r, circle2.r, getDistanceBetweenPoints(circle1, circle2));
  56. }
  57. return overlap;
  58. };
  59. /**
  60. * Calculates the difference between the desired overlap and the actual overlap
  61. * between two circles.
  62. * @private
  63. * @param {Dictionary<Highcharts.CircleObject>} mapOfIdToCircle
  64. * Map from id to circle.
  65. * @param {Array<Highcharts.VennRelationObject>} relations
  66. * List of relations to calculate the loss of.
  67. * @return {number}
  68. * Returns the loss between positions of the circles for the given relations.
  69. */
  70. var loss = function loss(mapOfIdToCircle, relations) {
  71. var precision = 10e10;
  72. // Iterate all the relations and calculate their individual loss.
  73. return relations.reduce(function (totalLoss, relation) {
  74. var loss = 0;
  75. if (relation.sets.length > 1) {
  76. var wantedOverlap = relation.value;
  77. // Calculate the actual overlap between the sets.
  78. var actualOverlap = getOverlapBetweenCircles(
  79. // Get the circles for the given sets.
  80. relation.sets.map(function (set) {
  81. return mapOfIdToCircle[set];
  82. }));
  83. var diff = wantedOverlap - actualOverlap;
  84. loss = Math.round((diff * diff) * precision) / precision;
  85. }
  86. // Add calculated loss to the sum.
  87. return totalLoss + loss;
  88. }, 0);
  89. };
  90. /**
  91. * Finds the root of a given function. The root is the input value needed for
  92. * a function to return 0.
  93. *
  94. * See https://en.wikipedia.org/wiki/Bisection_method#Algorithm
  95. *
  96. * TODO: Add unit tests.
  97. *
  98. * @param {Function} f
  99. * The function to find the root of.
  100. * @param {number} a
  101. * The lowest number in the search range.
  102. * @param {number} b
  103. * The highest number in the search range.
  104. * @param {number} [tolerance=1e-10]
  105. * The allowed difference between the returned value and root.
  106. * @param {number} [maxIterations=100]
  107. * The maximum iterations allowed.
  108. * @return {number}
  109. * Root number.
  110. */
  111. var bisect = function bisect(f, a, b, tolerance, maxIterations) {
  112. var fA = f(a), fB = f(b), nMax = maxIterations || 100, tol = tolerance || 1e-10, delta = b - a, n = 1, x, fX;
  113. if (a >= b) {
  114. throw new Error('a must be smaller than b.');
  115. }
  116. else if (fA * fB > 0) {
  117. throw new Error('f(a) and f(b) must have opposite signs.');
  118. }
  119. if (fA === 0) {
  120. x = a;
  121. }
  122. else if (fB === 0) {
  123. x = b;
  124. }
  125. else {
  126. while (n++ <= nMax && fX !== 0 && delta > tol) {
  127. delta = (b - a) / 2;
  128. x = a + delta;
  129. fX = f(x);
  130. // Update low and high for next search interval.
  131. if (fA * fX > 0) {
  132. a = x;
  133. }
  134. else {
  135. b = x;
  136. }
  137. }
  138. }
  139. return x;
  140. };
  141. /**
  142. * Uses the bisection method to make a best guess of the ideal distance between
  143. * two circles too get the desired overlap.
  144. * Currently there is no known formula to calculate the distance from the area
  145. * of overlap, which makes the bisection method preferred.
  146. * @private
  147. * @param {number} r1
  148. * Radius of the first circle.
  149. * @param {number} r2
  150. * Radiues of the second circle.
  151. * @param {number} overlap
  152. * The wanted overlap between the two circles.
  153. * @return {number}
  154. * Returns the distance needed to get the wanted overlap between the two
  155. * circles.
  156. */
  157. var getDistanceBetweenCirclesByOverlap = function getDistanceBetweenCirclesByOverlap(r1, r2, overlap) {
  158. var maxDistance = r1 + r2, distance;
  159. if (overlap <= 0) {
  160. // If overlap is below or equal to zero, then there is no overlap.
  161. distance = maxDistance;
  162. }
  163. else if (getAreaOfCircle(r1 < r2 ? r1 : r2) <= overlap) {
  164. // When area of overlap is larger than the area of the smallest circle,
  165. // then it is completely overlapping.
  166. distance = 0;
  167. }
  168. else {
  169. distance = bisect(function (x) {
  170. var actualOverlap = getOverlapBetweenCirclesByDistance(r1, r2, x);
  171. // Return the differance between wanted and actual overlap.
  172. return overlap - actualOverlap;
  173. }, 0, maxDistance);
  174. }
  175. return distance;
  176. };
  177. var isSet = function (x) {
  178. return isArray(x.sets) && x.sets.length === 1;
  179. };
  180. /**
  181. * Calculates a margin for a point based on the iternal and external circles.
  182. * The margin describes if the point is well placed within the internal circles,
  183. * and away from the external
  184. * @private
  185. * @todo add unit tests.
  186. * @param {Highcharts.PositionObject} point
  187. * The point to evaluate.
  188. * @param {Array<Highcharts.CircleObject>} internal
  189. * The internal circles.
  190. * @param {Array<Highcharts.CircleObject>} external
  191. * The external circles.
  192. * @return {number}
  193. * Returns the margin.
  194. */
  195. var getMarginFromCircles = function getMarginFromCircles(point, internal, external) {
  196. var margin = internal.reduce(function (margin, circle) {
  197. var m = circle.r - getDistanceBetweenPoints(point, circle);
  198. return (m <= margin) ? m : margin;
  199. }, Number.MAX_VALUE);
  200. margin = external.reduce(function (margin, circle) {
  201. var m = getDistanceBetweenPoints(point, circle) - circle.r;
  202. return (m <= margin) ? m : margin;
  203. }, margin);
  204. return margin;
  205. };
  206. /**
  207. * Finds the optimal label position by looking for a position that has a low
  208. * distance from the internal circles, and as large possible distane to the
  209. * external circles.
  210. * @private
  211. * @todo Optimize the intial position.
  212. * @todo Add unit tests.
  213. * @param {Array<Highcharts.CircleObject>} internal
  214. * Internal circles.
  215. * @param {Array<Highcharts.CircleObject>} external
  216. * External circles.
  217. * @return {Highcharts.PositionObject}
  218. * Returns the found position.
  219. */
  220. var getLabelPosition = function getLabelPosition(internal, external) {
  221. // Get the best label position within the internal circles.
  222. var best = internal.reduce(function (best, circle) {
  223. var d = circle.r / 2;
  224. // Give a set of points with the circle to evaluate as the best label
  225. // position.
  226. return [
  227. { x: circle.x, y: circle.y },
  228. { x: circle.x + d, y: circle.y },
  229. { x: circle.x - d, y: circle.y },
  230. { x: circle.x, y: circle.y + d },
  231. { x: circle.x, y: circle.y - d }
  232. ]
  233. // Iterate the given points and return the one with the largest
  234. // margin.
  235. .reduce(function (best, point) {
  236. var margin = getMarginFromCircles(point, internal, external);
  237. // If the margin better than the current best, then update best.
  238. if (best.margin < margin) {
  239. best.point = point;
  240. best.margin = margin;
  241. }
  242. return best;
  243. }, best);
  244. }, {
  245. point: void 0,
  246. margin: -Number.MAX_VALUE
  247. }).point;
  248. // Use nelder mead to optimize the initial label position.
  249. var optimal = nelderMead(function (p) {
  250. return -(getMarginFromCircles({ x: p[0], y: p[1] }, internal, external));
  251. }, [best.x, best.y]);
  252. // Update best to be the point which was found to have the best margin.
  253. best = {
  254. x: optimal[0],
  255. y: optimal[1]
  256. };
  257. if (!(isPointInsideAllCircles(best, internal) &&
  258. isPointOutsideAllCircles(best, external))) {
  259. // If point was either outside one of the internal, or inside one of the
  260. // external, then it was invalid and should use a fallback.
  261. if (internal.length > 1) {
  262. best = getCenterOfPoints(getCirclesIntersectionPolygon(internal));
  263. }
  264. else {
  265. best = {
  266. x: internal[0].x,
  267. y: internal[0].y
  268. };
  269. }
  270. }
  271. // Return the best point.
  272. return best;
  273. };
  274. /**
  275. * Finds the available width for a label, by taking the label position and
  276. * finding the largest distance, which is inside all internal circles, and
  277. * outside all external circles.
  278. *
  279. * @private
  280. * @param {Highcharts.PositionObject} pos
  281. * The x and y coordinate of the label.
  282. * @param {Array<Highcharts.CircleObject>} internal
  283. * Internal circles.
  284. * @param {Array<Highcharts.CircleObject>} external
  285. * External circles.
  286. * @return {number}
  287. * Returns available width for the label.
  288. */
  289. var getLabelWidth = function getLabelWidth(pos, internal, external) {
  290. var radius = internal.reduce(function (min, circle) {
  291. return Math.min(circle.r, min);
  292. }, Infinity),
  293. // Filter out external circles that are completely overlapping.
  294. filteredExternals = external.filter(function (circle) {
  295. return !isPointInsideCircle(pos, circle);
  296. });
  297. var findDistance = function (maxDistance, direction) {
  298. return bisect(function (x) {
  299. var testPos = {
  300. x: pos.x + (direction * x),
  301. y: pos.y
  302. }, isValid = (isPointInsideAllCircles(testPos, internal) &&
  303. isPointOutsideAllCircles(testPos, filteredExternals));
  304. // If the position is valid, then we want to move towards the max
  305. // distance. If not, then we want to away from the max distance.
  306. return -(maxDistance - x) + (isValid ? 0 : Number.MAX_VALUE);
  307. }, 0, maxDistance);
  308. };
  309. // Find the smallest distance of left and right.
  310. return Math.min(findDistance(radius, -1), findDistance(radius, 1)) * 2;
  311. };
  312. /**
  313. * Calulates data label values for a given relations object.
  314. *
  315. * @private
  316. * @todo add unit tests
  317. * @param {Highcharts.VennRelationObject} relation A relations object.
  318. * @param {Array<Highcharts.VennRelationObject>} setRelations The list of
  319. * relations that is a set.
  320. * @return {Highcharts.VennLabelValuesObject}
  321. * Returns an object containing position and width of the label.
  322. */
  323. function getLabelValues(relation, setRelations) {
  324. var sets = relation.sets;
  325. // Create a list of internal and external circles.
  326. var data = setRelations.reduce(function (data, set) {
  327. // If the set exists in this relation, then it is internal,
  328. // otherwise it will be external.
  329. var isInternal = sets.indexOf(set.sets[0]) > -1;
  330. var property = isInternal ? 'internal' : 'external';
  331. // Add the circle to the list.
  332. data[property].push(set.circle);
  333. return data;
  334. }, {
  335. internal: [],
  336. external: []
  337. });
  338. // Filter out external circles that are completely overlapping all internal
  339. data.external = data.external.filter(function (externalCircle) {
  340. return data.internal.some(function (internalCircle) {
  341. return !isCircle1CompletelyOverlappingCircle2(externalCircle, internalCircle);
  342. });
  343. });
  344. // Calulate the label position.
  345. var position = getLabelPosition(data.internal, data.external);
  346. // Calculate the label width
  347. var width = getLabelWidth(position, data.internal, data.external);
  348. return {
  349. position: position,
  350. width: width
  351. };
  352. }
  353. /**
  354. * Takes an array of relations and adds the properties `totalOverlap` and
  355. * `overlapping` to each set. The property `totalOverlap` is the sum of value
  356. * for each relation where this set is included. The property `overlapping` is
  357. * a map of how much this set is overlapping another set.
  358. * NOTE: This algorithm ignores relations consisting of more than 2 sets.
  359. * @private
  360. * @param {Array<Highcharts.VennRelationObject>} relations
  361. * The list of relations that should be sorted.
  362. * @return {Array<Highcharts.VennRelationObject>}
  363. * Returns the modified input relations with added properties `totalOverlap` and
  364. * `overlapping`.
  365. */
  366. var addOverlapToSets = function addOverlapToSets(relations) {
  367. // Calculate the amount of overlap per set.
  368. var mapOfIdToProps = relations
  369. // Filter out relations consisting of 2 sets.
  370. .filter(function (relation) {
  371. return relation.sets.length === 2;
  372. })
  373. // Sum up the amount of overlap for each set.
  374. .reduce(function (map, relation) {
  375. var sets = relation.sets;
  376. sets.forEach(function (set, i, arr) {
  377. if (!isObject(map[set])) {
  378. map[set] = {
  379. overlapping: {},
  380. totalOverlap: 0
  381. };
  382. }
  383. map[set].totalOverlap += relation.value;
  384. map[set].overlapping[arr[1 - i]] = relation.value;
  385. });
  386. return map;
  387. }, {});
  388. relations
  389. // Filter out single sets
  390. .filter(isSet)
  391. // Extend the set with the calculated properties.
  392. .forEach(function (set) {
  393. var properties = mapOfIdToProps[set.sets[0]];
  394. extend(set, properties);
  395. });
  396. // Returns the modified relations.
  397. return relations;
  398. };
  399. /**
  400. * Takes two sets and finds the one with the largest total overlap.
  401. * @private
  402. * @param {object} a The first set to compare.
  403. * @param {object} b The second set to compare.
  404. * @return {number} Returns 0 if a and b are equal, <0 if a is greater, >0 if b
  405. * is greater.
  406. */
  407. var sortByTotalOverlap = function sortByTotalOverlap(a, b) {
  408. return b.totalOverlap - a.totalOverlap;
  409. };
  410. /**
  411. * Uses a greedy approach to position all the sets. Works well with a small
  412. * number of sets, and are in these cases a good choice aesthetically.
  413. * @private
  414. * @param {Array<object>} relations List of the overlap between two or more
  415. * sets, or the size of a single set.
  416. * @return {Array<object>} List of circles and their calculated positions.
  417. */
  418. var layoutGreedyVenn = function layoutGreedyVenn(relations) {
  419. var positionedSets = [], mapOfIdToCircles = {};
  420. // Define a circle for each set.
  421. relations
  422. .filter(function (relation) {
  423. return relation.sets.length === 1;
  424. }).forEach(function (relation) {
  425. mapOfIdToCircles[relation.sets[0]] = relation.circle = {
  426. x: Number.MAX_VALUE,
  427. y: Number.MAX_VALUE,
  428. r: Math.sqrt(relation.value / Math.PI)
  429. };
  430. });
  431. /**
  432. * Takes a set and updates the position, and add the set to the list of
  433. * positioned sets.
  434. * @private
  435. * @param {object} set
  436. * The set to add to its final position.
  437. * @param {object} coordinates
  438. * The coordinates to position the set at.
  439. * @return {void}
  440. */
  441. var positionSet = function positionSet(set, coordinates) {
  442. var circle = set.circle;
  443. circle.x = coordinates.x;
  444. circle.y = coordinates.y;
  445. positionedSets.push(set);
  446. };
  447. // Find overlap between sets. Ignore relations with more then 2 sets.
  448. addOverlapToSets(relations);
  449. // Sort sets by the sum of their size from large to small.
  450. var sortedByOverlap = relations
  451. .filter(isSet)
  452. .sort(sortByTotalOverlap);
  453. // Position the most overlapped set at 0,0.
  454. positionSet(sortedByOverlap.shift(), { x: 0, y: 0 });
  455. var relationsWithTwoSets = relations.filter(function (x) {
  456. return x.sets.length === 2;
  457. });
  458. // Iterate and position the remaining sets.
  459. sortedByOverlap.forEach(function (set) {
  460. var circle = set.circle, radius = circle.r, overlapping = set.overlapping;
  461. var bestPosition = positionedSets
  462. .reduce(function (best, positionedSet, i) {
  463. var positionedCircle = positionedSet.circle, overlap = overlapping[positionedSet.sets[0]];
  464. // Calculate the distance between the sets to get the correct
  465. // overlap
  466. var distance = getDistanceBetweenCirclesByOverlap(radius, positionedCircle.r, overlap);
  467. // Create a list of possible coordinates calculated from
  468. // distance.
  469. var possibleCoordinates = [
  470. { x: positionedCircle.x + distance, y: positionedCircle.y },
  471. { x: positionedCircle.x - distance, y: positionedCircle.y },
  472. { x: positionedCircle.x, y: positionedCircle.y + distance },
  473. { x: positionedCircle.x, y: positionedCircle.y - distance }
  474. ];
  475. // If there are more circles overlapping, then add the
  476. // intersection points as possible positions.
  477. positionedSets.slice(i + 1).forEach(function (positionedSet2) {
  478. var positionedCircle2 = positionedSet2.circle, overlap2 = overlapping[positionedSet2.sets[0]], distance2 = getDistanceBetweenCirclesByOverlap(radius, positionedCircle2.r, overlap2);
  479. // Add intersections to list of coordinates.
  480. possibleCoordinates = possibleCoordinates.concat(getCircleCircleIntersection({
  481. x: positionedCircle.x,
  482. y: positionedCircle.y,
  483. r: distance
  484. }, {
  485. x: positionedCircle2.x,
  486. y: positionedCircle2.y,
  487. r: distance2
  488. }));
  489. });
  490. // Iterate all suggested coordinates and find the best one.
  491. possibleCoordinates.forEach(function (coordinates) {
  492. circle.x = coordinates.x;
  493. circle.y = coordinates.y;
  494. // Calculate loss for the suggested coordinates.
  495. var currentLoss = loss(mapOfIdToCircles, relationsWithTwoSets);
  496. // If the loss is better, then use these new coordinates.
  497. if (currentLoss < best.loss) {
  498. best.loss = currentLoss;
  499. best.coordinates = coordinates;
  500. }
  501. });
  502. // Return resulting coordinates.
  503. return best;
  504. }, {
  505. loss: Number.MAX_VALUE,
  506. coordinates: void 0
  507. });
  508. // Add the set to its final position.
  509. positionSet(set, bestPosition.coordinates);
  510. });
  511. // Return the positions of each set.
  512. return mapOfIdToCircles;
  513. };
  514. /**
  515. * Calculates the positions, and the label values of all the sets in the venn
  516. * diagram.
  517. *
  518. * @private
  519. * @todo Add support for constrained MDS.
  520. * @param {Array<Highchats.VennRelationObject>} relations
  521. * List of the overlap between two or more sets, or the size of a single set.
  522. * @return {Highcharts.Dictionary<*>}
  523. * List of circles and their calculated positions.
  524. */
  525. function layout(relations) {
  526. var mapOfIdToShape = {};
  527. var mapOfIdToLabelValues = {};
  528. // Calculate best initial positions by using greedy layout.
  529. if (relations.length > 0) {
  530. var mapOfIdToCircles_1 = layoutGreedyVenn(relations);
  531. var setRelations_1 = relations.filter(isSet);
  532. relations
  533. .forEach(function (relation) {
  534. var sets = relation.sets;
  535. var id = sets.join();
  536. // Get shape from map of circles, or calculate intersection.
  537. var shape = isSet(relation) ?
  538. mapOfIdToCircles_1[id] :
  539. getAreaOfIntersectionBetweenCircles(sets.map(function (set) {
  540. return mapOfIdToCircles_1[set];
  541. }));
  542. // Calculate label values if the set has a shape
  543. if (shape) {
  544. mapOfIdToShape[id] = shape;
  545. mapOfIdToLabelValues[id] = getLabelValues(relation, setRelations_1);
  546. }
  547. });
  548. }
  549. return { mapOfIdToShape: mapOfIdToShape, mapOfIdToLabelValues: mapOfIdToLabelValues };
  550. }
  551. var isValidRelation = function (x) {
  552. var map = {};
  553. return (isObject(x) &&
  554. (isNumber(x.value) && x.value > -1) &&
  555. (isArray(x.sets) && x.sets.length > 0) &&
  556. !x.sets.some(function (set) {
  557. var invalid = false;
  558. if (!map[set] && isString(set)) {
  559. map[set] = true;
  560. }
  561. else {
  562. invalid = true;
  563. }
  564. return invalid;
  565. }));
  566. };
  567. var isValidSet = function (x) {
  568. return (isValidRelation(x) && isSet(x) && x.value > 0);
  569. };
  570. /**
  571. * Prepares the venn data so that it is usable for the layout function. Filter
  572. * out sets, or intersections that includes sets, that are missing in the data
  573. * or has (value < 1). Adds missing relations between sets in the data as
  574. * value = 0.
  575. * @private
  576. * @param {Array<object>} data The raw input data.
  577. * @return {Array<object>} Returns an array of valid venn data.
  578. */
  579. var processVennData = function processVennData(data) {
  580. var d = isArray(data) ? data : [];
  581. var validSets = d
  582. .reduce(function (arr, x) {
  583. // Check if x is a valid set, and that it is not an duplicate.
  584. if (isValidSet(x) && arr.indexOf(x.sets[0]) === -1) {
  585. arr.push(x.sets[0]);
  586. }
  587. return arr;
  588. }, [])
  589. .sort();
  590. var mapOfIdToRelation = d.reduce(function (mapOfIdToRelation, relation) {
  591. if (isValidRelation(relation) &&
  592. !relation.sets.some(function (set) {
  593. return validSets.indexOf(set) === -1;
  594. })) {
  595. mapOfIdToRelation[relation.sets.sort().join()] =
  596. relation;
  597. }
  598. return mapOfIdToRelation;
  599. }, {});
  600. validSets.reduce(function (combinations, set, i, arr) {
  601. var remaining = arr.slice(i + 1);
  602. remaining.forEach(function (set2) {
  603. combinations.push(set + ',' + set2);
  604. });
  605. return combinations;
  606. }, []).forEach(function (combination) {
  607. if (!mapOfIdToRelation[combination]) {
  608. var obj = {
  609. sets: combination.split(','),
  610. value: 0
  611. };
  612. mapOfIdToRelation[combination] = obj;
  613. }
  614. });
  615. // Transform map into array.
  616. return objectValues(mapOfIdToRelation);
  617. };
  618. /**
  619. * Calculates the proper scale to fit the cloud inside the plotting area.
  620. * @private
  621. * @todo add unit test
  622. * @param {number} targetWidth
  623. * Width of target area.
  624. * @param {number} targetHeight
  625. * Height of target area.
  626. * @param {Highcharts.PolygonBoxObject} field
  627. * The playing field.
  628. * @return {Highcharts.Dictionary<number>}
  629. * Returns the value to scale the playing field up to the size of the target
  630. * area, and center of x and y.
  631. */
  632. var getScale = function getScale(targetWidth, targetHeight, field) {
  633. var height = field.bottom - field.top, // top is smaller than bottom
  634. width = field.right - field.left, scaleX = width > 0 ? 1 / width * targetWidth : 1, scaleY = height > 0 ? 1 / height * targetHeight : 1, adjustX = (field.right + field.left) / 2, adjustY = (field.top + field.bottom) / 2, scale = Math.min(scaleX, scaleY);
  635. return {
  636. scale: scale,
  637. centerX: targetWidth / 2 - adjustX * scale,
  638. centerY: targetHeight / 2 - adjustY * scale
  639. };
  640. };
  641. /**
  642. * If a circle is outside a give field, then the boundaries of the field is
  643. * adjusted accordingly. Modifies the field object which is passed as the first
  644. * parameter.
  645. * @private
  646. * @todo NOTE: Copied from wordcloud, can probably be unified.
  647. * @param {Highcharts.PolygonBoxObject} field
  648. * The bounding box of a playing field.
  649. * @param {Highcharts.CircleObject} circle
  650. * The bounding box for a placed point.
  651. * @return {Highcharts.PolygonBoxObject}
  652. * Returns a modified field object.
  653. */
  654. var updateFieldBoundaries = function updateFieldBoundaries(field, circle) {
  655. var left = circle.x - circle.r, right = circle.x + circle.r, bottom = circle.y + circle.r, top = circle.y - circle.r;
  656. // TODO improve type checking.
  657. if (!isNumber(field.left) || field.left > left) {
  658. field.left = left;
  659. }
  660. if (!isNumber(field.right) || field.right < right) {
  661. field.right = right;
  662. }
  663. if (!isNumber(field.top) || field.top > top) {
  664. field.top = top;
  665. }
  666. if (!isNumber(field.bottom) || field.bottom < bottom) {
  667. field.bottom = bottom;
  668. }
  669. return field;
  670. };
  671. /**
  672. * A Venn diagram displays all possible logical relations between a collection
  673. * of different sets. The sets are represented by circles, and the relation
  674. * between the sets are displayed by the overlap or lack of overlap between
  675. * them. The venn diagram is a special case of Euler diagrams, which can also
  676. * be displayed by this series type.
  677. *
  678. * @sample {highcharts} highcharts/demo/venn-diagram/
  679. * Venn diagram
  680. * @sample {highcharts} highcharts/demo/euler-diagram/
  681. * Euler diagram
  682. *
  683. * @extends plotOptions.scatter
  684. * @excluding connectEnds, connectNulls, cropThreshold, dragDrop,
  685. * findNearestPointBy, getExtremesFromAll, jitter, label, linecap,
  686. * lineWidth, linkedTo, marker, negativeColor, pointInterval,
  687. * pointIntervalUnit, pointPlacement, pointStart, softThreshold,
  688. * stacking, steps, threshold, xAxis, yAxis, zoneAxis, zones,
  689. * dataSorting, boostThreshold, boostBlending
  690. * @product highcharts
  691. * @requires modules/venn
  692. * @optionparent plotOptions.venn
  693. */
  694. var vennOptions = {
  695. borderColor: '#cccccc',
  696. borderDashStyle: 'solid',
  697. borderWidth: 1,
  698. brighten: 0,
  699. clip: false,
  700. colorByPoint: true,
  701. dataLabels: {
  702. enabled: true,
  703. verticalAlign: 'middle',
  704. formatter: function () {
  705. return this.point.name;
  706. }
  707. },
  708. /**
  709. * @ignore-option
  710. * @private
  711. */
  712. inactiveOtherPoints: true,
  713. marker: false,
  714. opacity: 0.75,
  715. showInLegend: false,
  716. states: {
  717. /**
  718. * @excluding halo
  719. */
  720. hover: {
  721. opacity: 1,
  722. borderColor: '#333333'
  723. },
  724. /**
  725. * @excluding halo
  726. */
  727. select: {
  728. color: '#cccccc',
  729. borderColor: '#000000',
  730. animation: false
  731. },
  732. inactive: {
  733. opacity: 0.075
  734. }
  735. },
  736. tooltip: {
  737. pointFormat: '{point.name}: {point.value}'
  738. }
  739. };
  740. var vennSeries = {
  741. isCartesian: false,
  742. axisTypes: [],
  743. directTouch: true,
  744. pointArrayMap: ['value'],
  745. init: function () {
  746. seriesTypes.scatter.prototype.init.apply(this, arguments);
  747. // Venn's opacity is a different option from other series
  748. delete this.opacity;
  749. },
  750. translate: function () {
  751. var chart = this.chart;
  752. this.processedXData = this.xData;
  753. this.generatePoints();
  754. // Process the data before passing it into the layout function.
  755. var relations = processVennData(this.options.data);
  756. // Calculate the positions of each circle.
  757. var _a = layout(relations), mapOfIdToShape = _a.mapOfIdToShape, mapOfIdToLabelValues = _a.mapOfIdToLabelValues;
  758. // Calculate the scale, and center of the plot area.
  759. var field = Object.keys(mapOfIdToShape)
  760. .filter(function (key) {
  761. var shape = mapOfIdToShape[key];
  762. return shape && isNumber(shape.r);
  763. })
  764. .reduce(function (field, key) {
  765. return updateFieldBoundaries(field, mapOfIdToShape[key]);
  766. }, { top: 0, bottom: 0, left: 0, right: 0 }), scaling = getScale(chart.plotWidth, chart.plotHeight, field), scale = scaling.scale, centerX = scaling.centerX, centerY = scaling.centerY;
  767. // Iterate all points and calculate and draw their graphics.
  768. this.points.forEach(function (point) {
  769. var sets = isArray(point.sets) ? point.sets : [], id = sets.join(), shape = mapOfIdToShape[id], shapeArgs, dataLabelValues = mapOfIdToLabelValues[id] || {}, dataLabelWidth = dataLabelValues.width, dataLabelPosition = dataLabelValues.position, dlOptions = point.options && point.options.dataLabels;
  770. if (shape) {
  771. if (shape.r) {
  772. shapeArgs = {
  773. x: centerX + shape.x * scale,
  774. y: centerY + shape.y * scale,
  775. r: shape.r * scale
  776. };
  777. }
  778. else if (shape.d) {
  779. var d = shape.d;
  780. d.forEach(function (seg) {
  781. if (seg[0] === 'M') {
  782. seg[1] = centerX + seg[1] * scale;
  783. seg[2] = centerY + seg[2] * scale;
  784. }
  785. else if (seg[0] === 'A') {
  786. seg[1] = seg[1] * scale;
  787. seg[2] = seg[2] * scale;
  788. seg[6] = centerX + seg[6] * scale;
  789. seg[7] = centerY + seg[7] * scale;
  790. }
  791. });
  792. shapeArgs = { d: d };
  793. }
  794. // Scale the position for the data label.
  795. if (dataLabelPosition) {
  796. dataLabelPosition.x = centerX + dataLabelPosition.x * scale;
  797. dataLabelPosition.y = centerY + dataLabelPosition.y * scale;
  798. }
  799. else {
  800. dataLabelPosition = {};
  801. }
  802. if (isNumber(dataLabelWidth)) {
  803. dataLabelWidth = Math.round(dataLabelWidth * scale);
  804. }
  805. }
  806. point.shapeArgs = shapeArgs;
  807. // Placement for the data labels
  808. if (dataLabelPosition && shapeArgs) {
  809. point.plotX = dataLabelPosition.x;
  810. point.plotY = dataLabelPosition.y;
  811. }
  812. // Add width for the data label
  813. if (dataLabelWidth && shapeArgs) {
  814. point.dlOptions = merge(true, {
  815. style: {
  816. width: dataLabelWidth
  817. }
  818. }, isObject(dlOptions) && dlOptions);
  819. }
  820. // Set name for usage in tooltip and in data label.
  821. point.name = point.options.name || sets.join('∩');
  822. });
  823. },
  824. /* eslint-disable valid-jsdoc */
  825. /**
  826. * Draw the graphics for each point.
  827. * @private
  828. */
  829. drawPoints: function () {
  830. var series = this,
  831. // Series properties
  832. chart = series.chart, group = series.group, points = series.points || [],
  833. // Chart properties
  834. renderer = chart.renderer;
  835. // Iterate all points and calculate and draw their graphics.
  836. points.forEach(function (point) {
  837. var attribs = {
  838. zIndex: isArray(point.sets) ? point.sets.length : 0
  839. }, shapeArgs = point.shapeArgs;
  840. // Add point attribs
  841. if (!chart.styledMode) {
  842. extend(attribs, series.pointAttribs(point, point.state));
  843. }
  844. // Draw the point graphic.
  845. point.draw({
  846. isNew: !point.graphic,
  847. animatableAttribs: shapeArgs,
  848. attribs: attribs,
  849. group: group,
  850. renderer: renderer,
  851. shapeType: shapeArgs && shapeArgs.d ? 'path' : 'circle'
  852. });
  853. });
  854. },
  855. /**
  856. * Calculates the style attributes for a point. The attributes can vary
  857. * depending on the state of the point.
  858. * @private
  859. * @param {Highcharts.Point} point
  860. * The point which will get the resulting attributes.
  861. * @param {string} [state]
  862. * The state of the point.
  863. * @return {Highcharts.SVGAttributes}
  864. * Returns the calculated attributes.
  865. */
  866. pointAttribs: function (point, state) {
  867. var series = this, seriesOptions = series.options || {}, pointOptions = point && point.options || {}, stateOptions = (state && seriesOptions.states[state]) || {}, options = merge(seriesOptions, { color: point && point.color }, pointOptions, stateOptions);
  868. // Return resulting values for the attributes.
  869. return {
  870. 'fill': color(options.color)
  871. .setOpacity(options.opacity)
  872. .brighten(options.brightness)
  873. .get(),
  874. 'stroke': options.borderColor,
  875. 'stroke-width': options.borderWidth,
  876. 'dashstyle': options.borderDashStyle
  877. };
  878. },
  879. /* eslint-enable valid-jsdoc */
  880. animate: function (init) {
  881. if (!init) {
  882. var series = this, animOptions = animObject(series.options.animation);
  883. series.points.forEach(function (point) {
  884. var args = point.shapeArgs;
  885. if (point.graphic && args) {
  886. var attr = {}, animate = {};
  887. if (args.d) {
  888. // If shape is a path, then animate opacity.
  889. attr.opacity = 0.001;
  890. }
  891. else {
  892. // If shape is a circle, then animate radius.
  893. attr.r = 0;
  894. animate.r = args.r;
  895. }
  896. point.graphic
  897. .attr(attr)
  898. .animate(animate, animOptions);
  899. // If shape is path, then fade it in after the circles
  900. // animation
  901. if (args.d) {
  902. setTimeout(function () {
  903. if (point && point.graphic) {
  904. point.graphic.animate({
  905. opacity: 1
  906. });
  907. }
  908. }, animOptions.duration);
  909. }
  910. }
  911. }, series);
  912. }
  913. },
  914. utils: {
  915. addOverlapToSets: addOverlapToSets,
  916. geometry: GeometryMixin,
  917. geometryCircles: GeometryCirclesModule,
  918. getLabelWidth: getLabelWidth,
  919. getMarginFromCircles: getMarginFromCircles,
  920. getDistanceBetweenCirclesByOverlap: getDistanceBetweenCirclesByOverlap,
  921. layoutGreedyVenn: layoutGreedyVenn,
  922. loss: loss,
  923. nelderMead: NelderMeadMixin,
  924. processVennData: processVennData,
  925. sortByTotalOverlap: sortByTotalOverlap
  926. }
  927. };
  928. var vennPoint = {
  929. draw: draw,
  930. shouldDraw: function () {
  931. var point = this;
  932. // Only draw points with single sets.
  933. return !!point.shapeArgs;
  934. },
  935. isValid: function () {
  936. return isNumber(this.value);
  937. }
  938. };
  939. /**
  940. * A `venn` series. If the [type](#series.venn.type) option is
  941. * not specified, it is inherited from [chart.type](#chart.type).
  942. *
  943. * @extends series,plotOptions.venn
  944. * @excluding connectEnds, connectNulls, cropThreshold, dataParser, dataURL,
  945. * findNearestPointBy, getExtremesFromAll, label, linecap, lineWidth,
  946. * linkedTo, marker, negativeColor, pointInterval, pointIntervalUnit,
  947. * pointPlacement, pointStart, softThreshold, stack, stacking, steps,
  948. * threshold, xAxis, yAxis, zoneAxis, zones, dataSorting,
  949. * boostThreshold, boostBlending
  950. * @product highcharts
  951. * @requires modules/venn
  952. * @apioption series.venn
  953. */
  954. /**
  955. * @type {Array<*>}
  956. * @extends series.scatter.data
  957. * @excluding marker, x, y
  958. * @product highcharts
  959. * @apioption series.venn.data
  960. */
  961. /**
  962. * The name of the point. Used in data labels and tooltip. If name is not
  963. * defined then it will default to the joined values in
  964. * [sets](#series.venn.sets).
  965. *
  966. * @sample {highcharts} highcharts/demo/venn-diagram/
  967. * Venn diagram
  968. * @sample {highcharts} highcharts/demo/euler-diagram/
  969. * Euler diagram
  970. *
  971. * @type {number}
  972. * @since 7.0.0
  973. * @product highcharts
  974. * @apioption series.venn.data.name
  975. */
  976. /**
  977. * The value of the point, resulting in a relative area of the circle, or area
  978. * of overlap between two sets in the venn or euler diagram.
  979. *
  980. * @sample {highcharts} highcharts/demo/venn-diagram/
  981. * Venn diagram
  982. * @sample {highcharts} highcharts/demo/euler-diagram/
  983. * Euler diagram
  984. *
  985. * @type {number}
  986. * @since 7.0.0
  987. * @product highcharts
  988. * @apioption series.venn.data.value
  989. */
  990. /**
  991. * The set or sets the options will be applied to. If a single entry is defined,
  992. * then it will create a new set. If more than one entry is defined, then it
  993. * will define the overlap between the sets in the array.
  994. *
  995. * @sample {highcharts} highcharts/demo/venn-diagram/
  996. * Venn diagram
  997. * @sample {highcharts} highcharts/demo/euler-diagram/
  998. * Euler diagram
  999. *
  1000. * @type {Array<string>}
  1001. * @since 7.0.0
  1002. * @product highcharts
  1003. * @apioption series.venn.data.sets
  1004. */
  1005. /**
  1006. * @excluding halo
  1007. * @apioption series.venn.states.hover
  1008. */
  1009. /**
  1010. * @excluding halo
  1011. * @apioption series.venn.states.select
  1012. */
  1013. ''; // detach doclets above
  1014. /**
  1015. * @private
  1016. * @class
  1017. * @name Highcharts.seriesTypes.venn
  1018. *
  1019. * @augments Highcharts.Series
  1020. */
  1021. BaseSeries.seriesType('venn', 'scatter', vennOptions, vennSeries, vennPoint);
  1022. /* eslint-disable no-invalid-this */
  1023. // Modify final series options.
  1024. addEvent(seriesTypes.venn, 'afterSetOptions', function (e) {
  1025. var options = e.options, states = options.states;
  1026. if (this.is('venn')) {
  1027. // Explicitly disable all halo options.
  1028. Object.keys(states).forEach(function (state) {
  1029. states[state].halo = false;
  1030. });
  1031. }
  1032. });