venn.src.js 38 KB

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