venn.src.js 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825
  1. /**
  2. * @license Highcharts JS v8.2.2 (2020-10-22)
  3. *
  4. * (c) 2017-2019 Highsoft AS
  5. * Authors: Jon Arild Nygard
  6. *
  7. * License: www.highcharts.com/license
  8. */
  9. 'use strict';
  10. (function (factory) {
  11. if (typeof module === 'object' && module.exports) {
  12. factory['default'] = factory;
  13. module.exports = factory;
  14. } else if (typeof define === 'function' && define.amd) {
  15. define('highcharts/modules/venn', ['highcharts'], function (Highcharts) {
  16. factory(Highcharts);
  17. factory.Highcharts = Highcharts;
  18. return factory;
  19. });
  20. } else {
  21. factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
  22. }
  23. }(function (Highcharts) {
  24. var _modules = Highcharts ? Highcharts._modules : {};
  25. function _registerModule(obj, path, args, fn) {
  26. if (!obj.hasOwnProperty(path)) {
  27. obj[path] = fn.apply(null, args);
  28. }
  29. }
  30. _registerModule(_modules, 'Mixins/DrawPoint.js', [], function () {
  31. /* *
  32. *
  33. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  34. *
  35. * */
  36. var isFn = function (x) {
  37. return typeof x === 'function';
  38. };
  39. /* eslint-disable no-invalid-this, valid-jsdoc */
  40. /**
  41. * Handles the drawing of a component.
  42. * Can be used for any type of component that reserves the graphic property, and
  43. * provides a shouldDraw on its context.
  44. *
  45. * @private
  46. * @function draw
  47. * @param {DrawPointParams} params
  48. * Parameters.
  49. *
  50. * @todo add type checking.
  51. * @todo export this function to enable usage
  52. */
  53. var draw = function draw(params) {
  54. var _a;
  55. var component = this,
  56. graphic = component.graphic,
  57. animatableAttribs = params.animatableAttribs,
  58. onComplete = params.onComplete,
  59. css = params.css,
  60. renderer = params.renderer,
  61. animation = (_a = component.series) === null || _a === void 0 ? void 0 : _a.options.animation;
  62. if (component.shouldDraw()) {
  63. if (!graphic) {
  64. component.graphic = graphic =
  65. renderer[params.shapeType](params.shapeArgs)
  66. .add(params.group);
  67. }
  68. graphic
  69. .css(css)
  70. .attr(params.attribs)
  71. .animate(animatableAttribs, params.isNew ? false : animation, onComplete);
  72. }
  73. else if (graphic) {
  74. var destroy = function () {
  75. component.graphic = graphic = graphic.destroy();
  76. if (isFn(onComplete)) {
  77. onComplete();
  78. }
  79. };
  80. // animate only runs complete callback if something was animated.
  81. if (Object.keys(animatableAttribs).length) {
  82. graphic.animate(animatableAttribs, void 0, function () {
  83. destroy();
  84. });
  85. }
  86. else {
  87. destroy();
  88. }
  89. }
  90. };
  91. /**
  92. * An extended version of draw customized for points.
  93. * It calls additional methods that is expected when rendering a point.
  94. * @private
  95. * @param {Highcharts.Dictionary<any>} params Parameters
  96. */
  97. var drawPoint = function drawPoint(params) {
  98. var point = this,
  99. attribs = params.attribs = params.attribs || {};
  100. // Assigning class in dot notation does go well in IE8
  101. // eslint-disable-next-line dot-notation
  102. attribs['class'] = point.getClassName();
  103. // Call draw to render component
  104. draw.call(point, params);
  105. };
  106. var drawPointModule = {
  107. draw: draw,
  108. drawPoint: drawPoint,
  109. isFn: isFn
  110. };
  111. return drawPointModule;
  112. });
  113. _registerModule(_modules, 'Mixins/Geometry.js', [], function () {
  114. /* *
  115. *
  116. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  117. *
  118. * */
  119. /**
  120. * Calculates the center between a list of points.
  121. * @private
  122. * @param {Array<Highcharts.PositionObject>} points
  123. * A list of points to calculate the center of.
  124. * @return {Highcharts.PositionObject}
  125. * Calculated center
  126. */
  127. var getCenterOfPoints = function getCenterOfPoints(points) {
  128. var sum = points.reduce(function (sum,
  129. point) {
  130. sum.x += point.x;
  131. sum.y += point.y;
  132. return sum;
  133. }, { x: 0, y: 0 });
  134. return {
  135. x: sum.x / points.length,
  136. y: sum.y / points.length
  137. };
  138. };
  139. /**
  140. * Calculates the distance between two points based on their x and y
  141. * coordinates.
  142. * @private
  143. * @param {Highcharts.PositionObject} p1
  144. * The x and y coordinates of the first point.
  145. * @param {Highcharts.PositionObject} p2
  146. * The x and y coordinates of the second point.
  147. * @return {number}
  148. * Returns the distance between the points.
  149. */
  150. var getDistanceBetweenPoints = function getDistanceBetweenPoints(p1,
  151. p2) {
  152. return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
  153. };
  154. /**
  155. * Calculates the angle between two points.
  156. * @todo add unit tests.
  157. * @private
  158. * @param {Highcharts.PositionObject} p1 The first point.
  159. * @param {Highcharts.PositionObject} p2 The second point.
  160. * @return {number} Returns the angle in radians.
  161. */
  162. var getAngleBetweenPoints = function getAngleBetweenPoints(p1,
  163. p2) {
  164. return Math.atan2(p2.x - p1.x,
  165. p2.y - p1.y);
  166. };
  167. var geometry = {
  168. getAngleBetweenPoints: getAngleBetweenPoints,
  169. getCenterOfPoints: getCenterOfPoints,
  170. getDistanceBetweenPoints: getDistanceBetweenPoints
  171. };
  172. return geometry;
  173. });
  174. _registerModule(_modules, 'Mixins/GeometryCircles.js', [_modules['Mixins/Geometry.js']], function (Geometry) {
  175. /* *
  176. *
  177. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  178. *
  179. * */
  180. var getAngleBetweenPoints = Geometry.getAngleBetweenPoints,
  181. getCenterOfPoints = Geometry.getCenterOfPoints,
  182. getDistanceBetweenPoints = Geometry.getDistanceBetweenPoints;
  183. /**
  184. * @private
  185. * @param {number} x
  186. * Number to round
  187. * @param {number} decimals
  188. * Number of decimals to round to
  189. * @return {number}
  190. * Rounded number
  191. */
  192. function round(x, decimals) {
  193. var a = Math.pow(10,
  194. decimals);
  195. return Math.round(x * a) / a;
  196. }
  197. /**
  198. * Calculates the area of a circle based on its radius.
  199. * @private
  200. * @param {number} r
  201. * The radius of the circle.
  202. * @return {number}
  203. * Returns the area of the circle.
  204. */
  205. function getAreaOfCircle(r) {
  206. if (r <= 0) {
  207. throw new Error('radius of circle must be a positive number.');
  208. }
  209. return Math.PI * r * r;
  210. }
  211. /**
  212. * Calculates the area of a circular segment based on the radius of the circle
  213. * and the height of the segment.
  214. * See http://mathworld.wolfram.com/CircularSegment.html
  215. * @private
  216. * @param {number} r
  217. * The radius of the circle.
  218. * @param {number} h
  219. * The height of the circular segment.
  220. * @return {number}
  221. * Returns the area of the circular segment.
  222. */
  223. function getCircularSegmentArea(r, h) {
  224. return r * r * Math.acos(1 - h / r) - (r - h) * Math.sqrt(h * (2 * r - h));
  225. }
  226. /**
  227. * Calculates the area of overlap between two circles based on their radiuses
  228. * and the distance between them.
  229. * See http://mathworld.wolfram.com/Circle-CircleIntersection.html
  230. * @private
  231. * @param {number} r1
  232. * Radius of the first circle.
  233. * @param {number} r2
  234. * Radius of the second circle.
  235. * @param {number} d
  236. * The distance between the two circles.
  237. * @return {number}
  238. * Returns the area of overlap between the two circles.
  239. */
  240. function getOverlapBetweenCircles(r1, r2, d) {
  241. var overlap = 0;
  242. // If the distance is larger than the sum of the radiuses then the circles
  243. // does not overlap.
  244. if (d < r1 + r2) {
  245. if (d <= Math.abs(r2 - r1)) {
  246. // If the circles are completely overlapping, then the overlap
  247. // equals the area of the smallest circle.
  248. overlap = getAreaOfCircle(r1 < r2 ? r1 : r2);
  249. }
  250. else {
  251. // Height of first triangle segment.
  252. var d1 = (r1 * r1 - r2 * r2 + d * d) / (2 * d),
  253. // Height of second triangle segment.
  254. d2 = d - d1;
  255. overlap = (getCircularSegmentArea(r1, r1 - d1) +
  256. getCircularSegmentArea(r2, r2 - d2));
  257. }
  258. // Round the result to two decimals.
  259. overlap = round(overlap, 14);
  260. }
  261. return overlap;
  262. }
  263. /**
  264. * Calculates the intersection points of two circles.
  265. *
  266. * NOTE: does not handle floating errors well.
  267. * @private
  268. * @param {Highcharts.CircleObject} c1
  269. * The first circle.
  270. * @param {Highcharts.CircleObject} c2
  271. * The second sircle.
  272. * @return {Array<Highcharts.PositionObject>}
  273. * Returns the resulting intersection points.
  274. */
  275. function getCircleCircleIntersection(c1, c2) {
  276. var d = getDistanceBetweenPoints(c1,
  277. c2),
  278. r1 = c1.r,
  279. r2 = c2.r;
  280. var points = [];
  281. if (d < r1 + r2 && d > Math.abs(r1 - r2)) {
  282. // If the circles are overlapping, but not completely overlapping, then
  283. // it exists intersecting points.
  284. var r1Square = r1 * r1,
  285. r2Square = r2 * r2,
  286. // d^2 - r^2 + R^2 / 2d
  287. x = (r1Square - r2Square + d * d) / (2 * d),
  288. // y^2 = R^2 - x^2
  289. y = Math.sqrt(r1Square - x * x),
  290. x1 = c1.x,
  291. x2 = c2.x,
  292. y1 = c1.y,
  293. y2 = c2.y,
  294. x0 = x1 + x * (x2 - x1) / d,
  295. y0 = y1 + x * (y2 - y1) / d,
  296. rx = -(y2 - y1) * (y / d),
  297. ry = -(x2 - x1) * (y / d);
  298. points = [
  299. { x: round(x0 + rx, 14), y: round(y0 - ry, 14) },
  300. { x: round(x0 - rx, 14), y: round(y0 + ry, 14) }
  301. ];
  302. }
  303. return points;
  304. }
  305. /**
  306. * Calculates all the intersection points for between a list of circles.
  307. * @private
  308. * @param {Array<Highcharts.CircleObject>} circles
  309. * The circles to calculate the points from.
  310. * @return {Array<Highcharts.GeometryObject>}
  311. * Returns a list of intersection points.
  312. */
  313. function getCirclesIntersectionPoints(circles) {
  314. return circles.reduce(function (points, c1, i, arr) {
  315. var additional = arr.slice(i + 1)
  316. .reduce(function (points,
  317. c2,
  318. j) {
  319. var indexes = [i,
  320. j + i + 1];
  321. return points.concat(getCircleCircleIntersection(c1, c2)
  322. .map(function (p) {
  323. p.indexes = indexes;
  324. return p;
  325. }));
  326. }, []);
  327. return points.concat(additional);
  328. }, []);
  329. }
  330. /**
  331. * Tests wether the first circle is completely overlapping the second circle.
  332. *
  333. * @private
  334. * @param {Highcharts.CircleObject} circle1 The first circle.
  335. * @param {Highcharts.CircleObject} circle2 The The second circle.
  336. * @return {boolean} Returns true if circle1 is completely overlapping circle2,
  337. * false if not.
  338. */
  339. function isCircle1CompletelyOverlappingCircle2(circle1, circle2) {
  340. return getDistanceBetweenPoints(circle1, circle2) + circle2.r <
  341. circle1.r + 1e-10;
  342. }
  343. /**
  344. * Tests wether a point lies within a given circle.
  345. * @private
  346. * @param {Highcharts.PositionObject} point
  347. * The point to test for.
  348. * @param {Highcharts.CircleObject} circle
  349. * The circle to test if the point is within.
  350. * @return {boolean}
  351. * Returns true if the point is inside, false if outside.
  352. */
  353. function isPointInsideCircle(point, circle) {
  354. return getDistanceBetweenPoints(point, circle) <= circle.r + 1e-10;
  355. }
  356. /**
  357. * Tests wether a point lies within a set of circles.
  358. * @private
  359. * @param {Highcharts.PositionObject} point
  360. * The point to test.
  361. * @param {Array<Highcharts.CircleObject>} circles
  362. * The list of circles to test against.
  363. * @return {boolean}
  364. * Returns true if the point is inside all the circles, false if not.
  365. */
  366. function isPointInsideAllCircles(point, circles) {
  367. return !circles.some(function (circle) {
  368. return !isPointInsideCircle(point, circle);
  369. });
  370. }
  371. /**
  372. * Tests wether a point lies outside a set of circles.
  373. *
  374. * TODO: add unit tests.
  375. * @private
  376. * @param {Highcharts.PositionObject} point
  377. * The point to test.
  378. * @param {Array<Highcharts.CircleObject>} circles
  379. * The list of circles to test against.
  380. * @return {boolean}
  381. * Returns true if the point is outside all the circles, false if not.
  382. */
  383. function isPointOutsideAllCircles(point, circles) {
  384. return !circles.some(function (circle) {
  385. return isPointInsideCircle(point, circle);
  386. });
  387. }
  388. /**
  389. * Calculates the points for the polygon of the intersection area between a set
  390. * of circles.
  391. *
  392. * @private
  393. * @param {Array<Highcharts.CircleObject>} circles
  394. * List of circles to calculate polygon of.
  395. * @return {Array<Highcharts.GeometryObject>} Return list of points in the
  396. * intersection polygon.
  397. */
  398. function getCirclesIntersectionPolygon(circles) {
  399. return getCirclesIntersectionPoints(circles)
  400. .filter(function (p) {
  401. return isPointInsideAllCircles(p, circles);
  402. });
  403. }
  404. /**
  405. * Calculate the path for the area of overlap between a set of circles.
  406. * @todo handle cases with only 1 or 0 arcs.
  407. * @private
  408. * @param {Array<Highcharts.CircleObject>} circles
  409. * List of circles to calculate area of.
  410. * @return {Highcharts.GeometryIntersectionObject|undefined}
  411. * Returns the path for the area of overlap. Returns an empty string if
  412. * there are no intersection between all the circles.
  413. */
  414. function getAreaOfIntersectionBetweenCircles(circles) {
  415. var intersectionPoints = getCirclesIntersectionPolygon(circles),
  416. result;
  417. if (intersectionPoints.length > 1) {
  418. // Calculate the center of the intersection points.
  419. var center_1 = getCenterOfPoints(intersectionPoints);
  420. intersectionPoints = intersectionPoints
  421. // Calculate the angle between the center and the points.
  422. .map(function (p) {
  423. p.angle = getAngleBetweenPoints(center_1, p);
  424. return p;
  425. })
  426. // Sort the points by the angle to the center.
  427. .sort(function (a, b) {
  428. return b.angle - a.angle;
  429. });
  430. var startPoint = intersectionPoints[intersectionPoints.length - 1];
  431. var arcs = intersectionPoints
  432. .reduce(function (data,
  433. p1) {
  434. var startPoint = data.startPoint,
  435. midPoint = getCenterOfPoints([startPoint,
  436. p1]);
  437. // Calculate the arc from the intersection points and their
  438. // circles.
  439. var arc = p1.indexes
  440. // Filter out circles that are not included in both
  441. // intersection points.
  442. .filter(function (index) {
  443. return startPoint.indexes.indexOf(index) > -1;
  444. })
  445. // Iterate the circles of the intersection points and
  446. // calculate arcs.
  447. .reduce(function (arc, index) {
  448. var circle = circles[index],
  449. angle1 = getAngleBetweenPoints(circle,
  450. p1),
  451. angle2 = getAngleBetweenPoints(circle,
  452. startPoint),
  453. angleDiff = angle2 - angle1 +
  454. (angle2 < angle1 ? 2 * Math.PI : 0),
  455. angle = angle2 - angleDiff / 2;
  456. var width = getDistanceBetweenPoints(midPoint, {
  457. x: circle.x + circle.r * Math.sin(angle),
  458. y: circle.y + circle.r * Math.cos(angle)
  459. });
  460. var r = circle.r;
  461. // Width can sometimes become to large due to floating
  462. // point errors
  463. if (width > r * 2) {
  464. width = r * 2;
  465. }
  466. // Get the arc with the smallest width.
  467. if (!arc || arc.width > width) {
  468. arc = {
  469. r: r,
  470. largeArc: width > r ? 1 : 0,
  471. width: width,
  472. x: p1.x,
  473. y: p1.y
  474. };
  475. }
  476. // Return the chosen arc.
  477. return arc;
  478. }, null);
  479. // If we find an arc then add it to the list and update p2.
  480. if (arc) {
  481. var r = arc.r;
  482. data.arcs.push(['A', r, r, 0, arc.largeArc, 1, arc.x, arc.y]);
  483. data.startPoint = p1;
  484. }
  485. return data;
  486. }, {
  487. startPoint: startPoint,
  488. arcs: []
  489. }).arcs;
  490. if (arcs.length === 0) {
  491. // empty
  492. }
  493. else if (arcs.length === 1) {
  494. // empty
  495. }
  496. else {
  497. arcs.unshift(['M', startPoint.x, startPoint.y]);
  498. result = {
  499. center: center_1,
  500. d: arcs
  501. };
  502. }
  503. }
  504. return result;
  505. }
  506. var geometryCircles = {
  507. getAreaOfCircle: getAreaOfCircle,
  508. getAreaOfIntersectionBetweenCircles: getAreaOfIntersectionBetweenCircles,
  509. getCircleCircleIntersection: getCircleCircleIntersection,
  510. getCirclesIntersectionPoints: getCirclesIntersectionPoints,
  511. getCirclesIntersectionPolygon: getCirclesIntersectionPolygon,
  512. getCircularSegmentArea: getCircularSegmentArea,
  513. getOverlapBetweenCircles: getOverlapBetweenCircles,
  514. isCircle1CompletelyOverlappingCircle2: isCircle1CompletelyOverlappingCircle2,
  515. isPointInsideCircle: isPointInsideCircle,
  516. isPointInsideAllCircles: isPointInsideAllCircles,
  517. isPointOutsideAllCircles: isPointOutsideAllCircles,
  518. round: round
  519. };
  520. return geometryCircles;
  521. });
  522. _registerModule(_modules, 'Mixins/NelderMead.js', [], function () {
  523. /* *
  524. *
  525. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  526. *
  527. * */
  528. /* eslint-disable valid-jsdoc */
  529. var getCentroid = function (simplex) {
  530. var arr = simplex.slice(0, -1),
  531. length = arr.length,
  532. result = [],
  533. sum = function (data,
  534. point) {
  535. data.sum += point[data.i];
  536. return data;
  537. };
  538. for (var i = 0; i < length; i++) {
  539. result[i] = arr.reduce(sum, { sum: 0, i: i }).sum / length;
  540. }
  541. return result;
  542. };
  543. /**
  544. * Finds an optimal position for a given point.
  545. * @todo add unit tests.
  546. * @todo add constraints to optimize the algorithm.
  547. * @private
  548. * @param {Highcharts.NelderMeadTestFunction} fn
  549. * The function to test a point.
  550. * @param {Highcharts.NelderMeadPointArray} initial
  551. * The initial point to optimize.
  552. * @return {Highcharts.NelderMeadPointArray}
  553. * Returns the opimized position of a point.
  554. */
  555. var nelderMead = function nelderMead(fn,
  556. initial) {
  557. var maxIterations = 100,
  558. sortByFx = function (a,
  559. b) {
  560. return a.fx - b.fx;
  561. }, pRef = 1, // Reflection parameter
  562. pExp = 2, // Expansion parameter
  563. pCon = -0.5, // Contraction parameter
  564. pOCon = pCon * pRef, // Outwards contraction parameter
  565. pShrink = 0.5; // Shrink parameter
  566. /**
  567. * @private
  568. */
  569. var weightedSum = function weightedSum(weight1,
  570. v1,
  571. weight2,
  572. v2) {
  573. return v1.map(function (x,
  574. i) {
  575. return weight1 * x + weight2 * v2[i];
  576. });
  577. };
  578. /**
  579. * @private
  580. */
  581. var getSimplex = function getSimplex(initial) {
  582. var n = initial.length,
  583. simplex = new Array(n + 1);
  584. // Initial point to the simplex.
  585. simplex[0] = initial;
  586. simplex[0].fx = fn(initial);
  587. // Create a set of extra points based on the initial.
  588. for (var i = 0; i < n; ++i) {
  589. var point = initial.slice();
  590. point[i] = point[i] ? point[i] * 1.05 : 0.001;
  591. point.fx = fn(point);
  592. simplex[i + 1] = point;
  593. }
  594. return simplex;
  595. };
  596. var updateSimplex = function (simplex,
  597. point) {
  598. point.fx = fn(point);
  599. simplex[simplex.length - 1] = point;
  600. return simplex;
  601. };
  602. var shrinkSimplex = function (simplex) {
  603. var best = simplex[0];
  604. return simplex.map(function (point) {
  605. var p = weightedSum(1 - pShrink,
  606. best,
  607. pShrink,
  608. point);
  609. p.fx = fn(p);
  610. return p;
  611. });
  612. };
  613. var getPoint = function (centroid,
  614. worst,
  615. a,
  616. b) {
  617. var point = weightedSum(a,
  618. centroid,
  619. b,
  620. worst);
  621. point.fx = fn(point);
  622. return point;
  623. };
  624. // Create a simplex
  625. var simplex = getSimplex(initial);
  626. // Iterate from 0 to max iterations
  627. for (var i = 0; i < maxIterations; i++) {
  628. // Sort the simplex
  629. simplex.sort(sortByFx);
  630. // Create a centroid from the simplex
  631. var worst = simplex[simplex.length - 1];
  632. var centroid = getCentroid(simplex);
  633. // Calculate the reflected point.
  634. var reflected = getPoint(centroid,
  635. worst, 1 + pRef, -pRef);
  636. if (reflected.fx < simplex[0].fx) {
  637. // If reflected point is the best, then possibly expand.
  638. var expanded = getPoint(centroid,
  639. worst, 1 + pExp, -pExp);
  640. simplex = updateSimplex(simplex, (expanded.fx < reflected.fx) ? expanded : reflected);
  641. }
  642. else if (reflected.fx >= simplex[simplex.length - 2].fx) {
  643. // If the reflected point is worse than the second worse, then
  644. // contract.
  645. var contracted;
  646. if (reflected.fx > worst.fx) {
  647. // If the reflected is worse than the worst point, do a
  648. // contraction
  649. contracted = getPoint(centroid, worst, 1 + pCon, -pCon);
  650. if (contracted.fx < worst.fx) {
  651. simplex = updateSimplex(simplex, contracted);
  652. }
  653. else {
  654. simplex = shrinkSimplex(simplex);
  655. }
  656. }
  657. else {
  658. // Otherwise do an outwards contraction
  659. contracted = getPoint(centroid, worst, 1 - pOCon, pOCon);
  660. if (contracted.fx < reflected.fx) {
  661. simplex = updateSimplex(simplex, contracted);
  662. }
  663. else {
  664. simplex = shrinkSimplex(simplex);
  665. }
  666. }
  667. }
  668. else {
  669. simplex = updateSimplex(simplex, reflected);
  670. }
  671. }
  672. return simplex[0];
  673. };
  674. var nelderMeadMixin = {
  675. getCentroid: getCentroid,
  676. nelderMead: nelderMead
  677. };
  678. return nelderMeadMixin;
  679. });
  680. _registerModule(_modules, 'Series/VennSeries.js', [_modules['Core/Animation/AnimationUtilities.js'], _modules['Core/Series/Series.js'], _modules['Core/Color/Color.js'], _modules['Mixins/DrawPoint.js'], _modules['Mixins/Geometry.js'], _modules['Mixins/GeometryCircles.js'], _modules['Mixins/NelderMead.js'], _modules['Core/Utilities.js']], function (A, BaseSeries, Color, DrawPointMixin, GeometryMixin, GeometryCirclesModule, NelderMeadMixin, U) {
  681. /* *
  682. *
  683. * Experimental Highcharts module which enables visualization of a Venn
  684. * diagram.
  685. *
  686. * (c) 2016-2020 Highsoft AS
  687. * Authors: Jon Arild Nygard
  688. *
  689. * Layout algorithm by Ben Frederickson:
  690. * https://www.benfrederickson.com/better-venn-diagrams/
  691. *
  692. * License: www.highcharts.com/license
  693. *
  694. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  695. *
  696. * */
  697. var animObject = A.animObject;
  698. var seriesTypes = BaseSeries.seriesTypes;
  699. var color = Color.parse;
  700. var draw = DrawPointMixin.draw;
  701. var getCenterOfPoints = GeometryMixin.getCenterOfPoints,
  702. getDistanceBetweenPoints = GeometryMixin.getDistanceBetweenPoints;
  703. var getAreaOfCircle = GeometryCirclesModule.getAreaOfCircle,
  704. getAreaOfIntersectionBetweenCircles = GeometryCirclesModule.getAreaOfIntersectionBetweenCircles,
  705. getCircleCircleIntersection = GeometryCirclesModule.getCircleCircleIntersection,
  706. getCirclesIntersectionPolygon = GeometryCirclesModule.getCirclesIntersectionPolygon,
  707. getOverlapBetweenCirclesByDistance = GeometryCirclesModule.getOverlapBetweenCircles,
  708. isCircle1CompletelyOverlappingCircle2 = GeometryCirclesModule.isCircle1CompletelyOverlappingCircle2,
  709. isPointInsideAllCircles = GeometryCirclesModule.isPointInsideAllCircles,
  710. isPointInsideCircle = GeometryCirclesModule.isPointInsideCircle,
  711. isPointOutsideAllCircles = GeometryCirclesModule.isPointOutsideAllCircles;
  712. var nelderMead = NelderMeadMixin.nelderMead;
  713. var addEvent = U.addEvent,
  714. extend = U.extend,
  715. isArray = U.isArray,
  716. isNumber = U.isNumber,
  717. isObject = U.isObject,
  718. isString = U.isString,
  719. merge = U.merge;
  720. var objectValues = function objectValues(obj) {
  721. return Object.keys(obj).map(function (x) {
  722. return obj[x];
  723. });
  724. };
  725. /**
  726. * Calculates the area of overlap between a list of circles.
  727. * @private
  728. * @todo add support for calculating overlap between more than 2 circles.
  729. * @param {Array<Highcharts.CircleObject>} circles
  730. * List of circles with their given positions.
  731. * @return {number}
  732. * Returns the area of overlap between all the circles.
  733. */
  734. var getOverlapBetweenCircles = function getOverlapBetweenCircles(circles) {
  735. var overlap = 0;
  736. // When there is only two circles we can find the overlap by using their
  737. // radiuses and the distance between them.
  738. if (circles.length === 2) {
  739. var circle1 = circles[0];
  740. var circle2 = circles[1];
  741. overlap = getOverlapBetweenCirclesByDistance(circle1.r, circle2.r, getDistanceBetweenPoints(circle1, circle2));
  742. }
  743. return overlap;
  744. };
  745. /**
  746. * Calculates the difference between the desired overlap and the actual overlap
  747. * between two circles.
  748. * @private
  749. * @param {Dictionary<Highcharts.CircleObject>} mapOfIdToCircle
  750. * Map from id to circle.
  751. * @param {Array<Highcharts.VennRelationObject>} relations
  752. * List of relations to calculate the loss of.
  753. * @return {number}
  754. * Returns the loss between positions of the circles for the given relations.
  755. */
  756. var loss = function loss(mapOfIdToCircle,
  757. relations) {
  758. var precision = 10e10;
  759. // Iterate all the relations and calculate their individual loss.
  760. return relations.reduce(function (totalLoss, relation) {
  761. var loss = 0;
  762. if (relation.sets.length > 1) {
  763. var wantedOverlap = relation.value;
  764. // Calculate the actual overlap between the sets.
  765. var actualOverlap = getOverlapBetweenCircles(
  766. // Get the circles for the given sets.
  767. relation.sets.map(function (set) {
  768. return mapOfIdToCircle[set];
  769. }));
  770. var diff = wantedOverlap - actualOverlap;
  771. loss = Math.round((diff * diff) * precision) / precision;
  772. }
  773. // Add calculated loss to the sum.
  774. return totalLoss + loss;
  775. }, 0);
  776. };
  777. /**
  778. * Finds the root of a given function. The root is the input value needed for
  779. * a function to return 0.
  780. *
  781. * See https://en.wikipedia.org/wiki/Bisection_method#Algorithm
  782. *
  783. * TODO: Add unit tests.
  784. *
  785. * @param {Function} f
  786. * The function to find the root of.
  787. * @param {number} a
  788. * The lowest number in the search range.
  789. * @param {number} b
  790. * The highest number in the search range.
  791. * @param {number} [tolerance=1e-10]
  792. * The allowed difference between the returned value and root.
  793. * @param {number} [maxIterations=100]
  794. * The maximum iterations allowed.
  795. * @return {number}
  796. * Root number.
  797. */
  798. var bisect = function bisect(f,
  799. a,
  800. b,
  801. tolerance,
  802. maxIterations) {
  803. var fA = f(a),
  804. fB = f(b),
  805. nMax = maxIterations || 100,
  806. tol = tolerance || 1e-10,
  807. delta = b - a,
  808. n = 1,
  809. x,
  810. fX;
  811. if (a >= b) {
  812. throw new Error('a must be smaller than b.');
  813. }
  814. else if (fA * fB > 0) {
  815. throw new Error('f(a) and f(b) must have opposite signs.');
  816. }
  817. if (fA === 0) {
  818. x = a;
  819. }
  820. else if (fB === 0) {
  821. x = b;
  822. }
  823. else {
  824. while (n++ <= nMax && fX !== 0 && delta > tol) {
  825. delta = (b - a) / 2;
  826. x = a + delta;
  827. fX = f(x);
  828. // Update low and high for next search interval.
  829. if (fA * fX > 0) {
  830. a = x;
  831. }
  832. else {
  833. b = x;
  834. }
  835. }
  836. }
  837. return x;
  838. };
  839. /**
  840. * Uses the bisection method to make a best guess of the ideal distance between
  841. * two circles too get the desired overlap.
  842. * Currently there is no known formula to calculate the distance from the area
  843. * of overlap, which makes the bisection method preferred.
  844. * @private
  845. * @param {number} r1
  846. * Radius of the first circle.
  847. * @param {number} r2
  848. * Radiues of the second circle.
  849. * @param {number} overlap
  850. * The wanted overlap between the two circles.
  851. * @return {number}
  852. * Returns the distance needed to get the wanted overlap between the two
  853. * circles.
  854. */
  855. var getDistanceBetweenCirclesByOverlap = function getDistanceBetweenCirclesByOverlap(r1,
  856. r2,
  857. overlap) {
  858. var maxDistance = r1 + r2,
  859. distance;
  860. if (overlap <= 0) {
  861. // If overlap is below or equal to zero, then there is no overlap.
  862. distance = maxDistance;
  863. }
  864. else if (getAreaOfCircle(r1 < r2 ? r1 : r2) <= overlap) {
  865. // When area of overlap is larger than the area of the smallest circle,
  866. // then it is completely overlapping.
  867. distance = 0;
  868. }
  869. else {
  870. distance = bisect(function (x) {
  871. var actualOverlap = getOverlapBetweenCirclesByDistance(r1,
  872. r2,
  873. x);
  874. // Return the differance between wanted and actual overlap.
  875. return overlap - actualOverlap;
  876. }, 0, maxDistance);
  877. }
  878. return distance;
  879. };
  880. var isSet = function (x) {
  881. return isArray(x.sets) && x.sets.length === 1;
  882. };
  883. /**
  884. * Calculates a margin for a point based on the iternal and external circles.
  885. * The margin describes if the point is well placed within the internal circles,
  886. * and away from the external
  887. * @private
  888. * @todo add unit tests.
  889. * @param {Highcharts.PositionObject} point
  890. * The point to evaluate.
  891. * @param {Array<Highcharts.CircleObject>} internal
  892. * The internal circles.
  893. * @param {Array<Highcharts.CircleObject>} external
  894. * The external circles.
  895. * @return {number}
  896. * Returns the margin.
  897. */
  898. var getMarginFromCircles = function getMarginFromCircles(point,
  899. internal,
  900. external) {
  901. var margin = internal.reduce(function (margin,
  902. circle) {
  903. var m = circle.r - getDistanceBetweenPoints(point,
  904. circle);
  905. return (m <= margin) ? m : margin;
  906. }, Number.MAX_VALUE);
  907. margin = external.reduce(function (margin, circle) {
  908. var m = getDistanceBetweenPoints(point,
  909. circle) - circle.r;
  910. return (m <= margin) ? m : margin;
  911. }, margin);
  912. return margin;
  913. };
  914. /**
  915. * Finds the optimal label position by looking for a position that has a low
  916. * distance from the internal circles, and as large possible distane to the
  917. * external circles.
  918. * @private
  919. * @todo Optimize the intial position.
  920. * @todo Add unit tests.
  921. * @param {Array<Highcharts.CircleObject>} internal
  922. * Internal circles.
  923. * @param {Array<Highcharts.CircleObject>} external
  924. * External circles.
  925. * @return {Highcharts.PositionObject}
  926. * Returns the found position.
  927. */
  928. var getLabelPosition = function getLabelPosition(internal,
  929. external) {
  930. // Get the best label position within the internal circles.
  931. var best = internal.reduce(function (best,
  932. circle) {
  933. var d = circle.r / 2;
  934. // Give a set of points with the circle to evaluate as the best label
  935. // position.
  936. return [
  937. { x: circle.x, y: circle.y },
  938. { x: circle.x + d, y: circle.y },
  939. { x: circle.x - d, y: circle.y },
  940. { x: circle.x, y: circle.y + d },
  941. { x: circle.x, y: circle.y - d }
  942. ]
  943. // Iterate the given points and return the one with the largest
  944. // margin.
  945. .reduce(function (best, point) {
  946. var margin = getMarginFromCircles(point,
  947. internal,
  948. external);
  949. // If the margin better than the current best, then update best.
  950. if (best.margin < margin) {
  951. best.point = point;
  952. best.margin = margin;
  953. }
  954. return best;
  955. }, best);
  956. }, {
  957. point: void 0,
  958. margin: -Number.MAX_VALUE
  959. }).point;
  960. // Use nelder mead to optimize the initial label position.
  961. var optimal = nelderMead(function (p) {
  962. return -(getMarginFromCircles({ x: p[0],
  963. y: p[1] },
  964. internal,
  965. external));
  966. }, [best.x, best.y]);
  967. // Update best to be the point which was found to have the best margin.
  968. best = {
  969. x: optimal[0],
  970. y: optimal[1]
  971. };
  972. if (!(isPointInsideAllCircles(best, internal) &&
  973. isPointOutsideAllCircles(best, external))) {
  974. // If point was either outside one of the internal, or inside one of the
  975. // external, then it was invalid and should use a fallback.
  976. if (internal.length > 1) {
  977. best = getCenterOfPoints(getCirclesIntersectionPolygon(internal));
  978. }
  979. else {
  980. best = {
  981. x: internal[0].x,
  982. y: internal[0].y
  983. };
  984. }
  985. }
  986. // Return the best point.
  987. return best;
  988. };
  989. /**
  990. * Finds the available width for a label, by taking the label position and
  991. * finding the largest distance, which is inside all internal circles, and
  992. * outside all external circles.
  993. *
  994. * @private
  995. * @param {Highcharts.PositionObject} pos
  996. * The x and y coordinate of the label.
  997. * @param {Array<Highcharts.CircleObject>} internal
  998. * Internal circles.
  999. * @param {Array<Highcharts.CircleObject>} external
  1000. * External circles.
  1001. * @return {number}
  1002. * Returns available width for the label.
  1003. */
  1004. var getLabelWidth = function getLabelWidth(pos,
  1005. internal,
  1006. external) {
  1007. var radius = internal.reduce(function (min,
  1008. circle) {
  1009. return Math.min(circle.r,
  1010. min);
  1011. }, Infinity),
  1012. // Filter out external circles that are completely overlapping.
  1013. filteredExternals = external.filter(function (circle) {
  1014. return !isPointInsideCircle(pos, circle);
  1015. });
  1016. var findDistance = function (maxDistance,
  1017. direction) {
  1018. return bisect(function (x) {
  1019. var testPos = {
  1020. x: pos.x + (direction * x),
  1021. y: pos.y
  1022. },
  1023. isValid = (isPointInsideAllCircles(testPos,
  1024. internal) &&
  1025. isPointOutsideAllCircles(testPos,
  1026. filteredExternals));
  1027. // If the position is valid, then we want to move towards the max
  1028. // distance. If not, then we want to away from the max distance.
  1029. return -(maxDistance - x) + (isValid ? 0 : Number.MAX_VALUE);
  1030. }, 0, maxDistance);
  1031. };
  1032. // Find the smallest distance of left and right.
  1033. return Math.min(findDistance(radius, -1), findDistance(radius, 1)) * 2;
  1034. };
  1035. /**
  1036. * Calulates data label values for a given relations object.
  1037. *
  1038. * @private
  1039. * @todo add unit tests
  1040. * @param {Highcharts.VennRelationObject} relation A relations object.
  1041. * @param {Array<Highcharts.VennRelationObject>} setRelations The list of
  1042. * relations that is a set.
  1043. * @return {Highcharts.VennLabelValuesObject}
  1044. * Returns an object containing position and width of the label.
  1045. */
  1046. function getLabelValues(relation, setRelations) {
  1047. var sets = relation.sets;
  1048. // Create a list of internal and external circles.
  1049. var data = setRelations.reduce(function (data,
  1050. set) {
  1051. // If the set exists in this relation, then it is internal,
  1052. // otherwise it will be external.
  1053. var isInternal = sets.indexOf(set.sets[0]) > -1;
  1054. var property = isInternal ? 'internal' : 'external';
  1055. // Add the circle to the list.
  1056. data[property].push(set.circle);
  1057. return data;
  1058. }, {
  1059. internal: [],
  1060. external: []
  1061. });
  1062. // Filter out external circles that are completely overlapping all internal
  1063. data.external = data.external.filter(function (externalCircle) {
  1064. return data.internal.some(function (internalCircle) {
  1065. return !isCircle1CompletelyOverlappingCircle2(externalCircle, internalCircle);
  1066. });
  1067. });
  1068. // Calulate the label position.
  1069. var position = getLabelPosition(data.internal,
  1070. data.external);
  1071. // Calculate the label width
  1072. var width = getLabelWidth(position,
  1073. data.internal,
  1074. data.external);
  1075. return {
  1076. position: position,
  1077. width: width
  1078. };
  1079. }
  1080. /**
  1081. * Takes an array of relations and adds the properties `totalOverlap` and
  1082. * `overlapping` to each set. The property `totalOverlap` is the sum of value
  1083. * for each relation where this set is included. The property `overlapping` is
  1084. * a map of how much this set is overlapping another set.
  1085. * NOTE: This algorithm ignores relations consisting of more than 2 sets.
  1086. * @private
  1087. * @param {Array<Highcharts.VennRelationObject>} relations
  1088. * The list of relations that should be sorted.
  1089. * @return {Array<Highcharts.VennRelationObject>}
  1090. * Returns the modified input relations with added properties `totalOverlap` and
  1091. * `overlapping`.
  1092. */
  1093. var addOverlapToSets = function addOverlapToSets(relations) {
  1094. // Calculate the amount of overlap per set.
  1095. var mapOfIdToProps = relations
  1096. // Filter out relations consisting of 2 sets.
  1097. .filter(function (relation) {
  1098. return relation.sets.length === 2;
  1099. })
  1100. // Sum up the amount of overlap for each set.
  1101. .reduce(function (map, relation) {
  1102. var sets = relation.sets;
  1103. sets.forEach(function (set, i, arr) {
  1104. if (!isObject(map[set])) {
  1105. map[set] = {
  1106. overlapping: {},
  1107. totalOverlap: 0
  1108. };
  1109. }
  1110. map[set].totalOverlap += relation.value;
  1111. map[set].overlapping[arr[1 - i]] = relation.value;
  1112. });
  1113. return map;
  1114. }, {});
  1115. relations
  1116. // Filter out single sets
  1117. .filter(isSet)
  1118. // Extend the set with the calculated properties.
  1119. .forEach(function (set) {
  1120. var properties = mapOfIdToProps[set.sets[0]];
  1121. extend(set, properties);
  1122. });
  1123. // Returns the modified relations.
  1124. return relations;
  1125. };
  1126. /**
  1127. * Takes two sets and finds the one with the largest total overlap.
  1128. * @private
  1129. * @param {object} a The first set to compare.
  1130. * @param {object} b The second set to compare.
  1131. * @return {number} Returns 0 if a and b are equal, <0 if a is greater, >0 if b
  1132. * is greater.
  1133. */
  1134. var sortByTotalOverlap = function sortByTotalOverlap(a,
  1135. b) {
  1136. return b.totalOverlap - a.totalOverlap;
  1137. };
  1138. /**
  1139. * Uses a greedy approach to position all the sets. Works well with a small
  1140. * number of sets, and are in these cases a good choice aesthetically.
  1141. * @private
  1142. * @param {Array<object>} relations List of the overlap between two or more
  1143. * sets, or the size of a single set.
  1144. * @return {Array<object>} List of circles and their calculated positions.
  1145. */
  1146. var layoutGreedyVenn = function layoutGreedyVenn(relations) {
  1147. var positionedSets = [],
  1148. mapOfIdToCircles = {};
  1149. // Define a circle for each set.
  1150. relations
  1151. .filter(function (relation) {
  1152. return relation.sets.length === 1;
  1153. }).forEach(function (relation) {
  1154. mapOfIdToCircles[relation.sets[0]] = relation.circle = {
  1155. x: Number.MAX_VALUE,
  1156. y: Number.MAX_VALUE,
  1157. r: Math.sqrt(relation.value / Math.PI)
  1158. };
  1159. });
  1160. /**
  1161. * Takes a set and updates the position, and add the set to the list of
  1162. * positioned sets.
  1163. * @private
  1164. * @param {object} set
  1165. * The set to add to its final position.
  1166. * @param {object} coordinates
  1167. * The coordinates to position the set at.
  1168. * @return {void}
  1169. */
  1170. var positionSet = function positionSet(set,
  1171. coordinates) {
  1172. var circle = set.circle;
  1173. circle.x = coordinates.x;
  1174. circle.y = coordinates.y;
  1175. positionedSets.push(set);
  1176. };
  1177. // Find overlap between sets. Ignore relations with more then 2 sets.
  1178. addOverlapToSets(relations);
  1179. // Sort sets by the sum of their size from large to small.
  1180. var sortedByOverlap = relations
  1181. .filter(isSet)
  1182. .sort(sortByTotalOverlap);
  1183. // Position the most overlapped set at 0,0.
  1184. positionSet(sortedByOverlap.shift(), { x: 0, y: 0 });
  1185. var relationsWithTwoSets = relations.filter(function (x) {
  1186. return x.sets.length === 2;
  1187. });
  1188. // Iterate and position the remaining sets.
  1189. sortedByOverlap.forEach(function (set) {
  1190. var circle = set.circle,
  1191. radius = circle.r,
  1192. overlapping = set.overlapping;
  1193. var bestPosition = positionedSets
  1194. .reduce(function (best,
  1195. positionedSet,
  1196. i) {
  1197. var positionedCircle = positionedSet.circle,
  1198. overlap = overlapping[positionedSet.sets[0]];
  1199. // Calculate the distance between the sets to get the correct
  1200. // overlap
  1201. var distance = getDistanceBetweenCirclesByOverlap(radius,
  1202. positionedCircle.r,
  1203. overlap);
  1204. // Create a list of possible coordinates calculated from
  1205. // distance.
  1206. var possibleCoordinates = [
  1207. { x: positionedCircle.x + distance,
  1208. y: positionedCircle.y },
  1209. { x: positionedCircle.x - distance,
  1210. y: positionedCircle.y },
  1211. { x: positionedCircle.x,
  1212. y: positionedCircle.y + distance },
  1213. { x: positionedCircle.x,
  1214. y: positionedCircle.y - distance }
  1215. ];
  1216. // If there are more circles overlapping, then add the
  1217. // intersection points as possible positions.
  1218. positionedSets.slice(i + 1).forEach(function (positionedSet2) {
  1219. var positionedCircle2 = positionedSet2.circle,
  1220. overlap2 = overlapping[positionedSet2.sets[0]],
  1221. distance2 = getDistanceBetweenCirclesByOverlap(radius,
  1222. positionedCircle2.r,
  1223. overlap2);
  1224. // Add intersections to list of coordinates.
  1225. possibleCoordinates = possibleCoordinates.concat(getCircleCircleIntersection({
  1226. x: positionedCircle.x,
  1227. y: positionedCircle.y,
  1228. r: distance
  1229. }, {
  1230. x: positionedCircle2.x,
  1231. y: positionedCircle2.y,
  1232. r: distance2
  1233. }));
  1234. });
  1235. // Iterate all suggested coordinates and find the best one.
  1236. possibleCoordinates.forEach(function (coordinates) {
  1237. circle.x = coordinates.x;
  1238. circle.y = coordinates.y;
  1239. // Calculate loss for the suggested coordinates.
  1240. var currentLoss = loss(mapOfIdToCircles,
  1241. relationsWithTwoSets);
  1242. // If the loss is better, then use these new coordinates.
  1243. if (currentLoss < best.loss) {
  1244. best.loss = currentLoss;
  1245. best.coordinates = coordinates;
  1246. }
  1247. });
  1248. // Return resulting coordinates.
  1249. return best;
  1250. }, {
  1251. loss: Number.MAX_VALUE,
  1252. coordinates: void 0
  1253. });
  1254. // Add the set to its final position.
  1255. positionSet(set, bestPosition.coordinates);
  1256. });
  1257. // Return the positions of each set.
  1258. return mapOfIdToCircles;
  1259. };
  1260. /**
  1261. * Calculates the positions, and the label values of all the sets in the venn
  1262. * diagram.
  1263. *
  1264. * @private
  1265. * @todo Add support for constrained MDS.
  1266. * @param {Array<Highchats.VennRelationObject>} relations
  1267. * List of the overlap between two or more sets, or the size of a single set.
  1268. * @return {Highcharts.Dictionary<*>}
  1269. * List of circles and their calculated positions.
  1270. */
  1271. function layout(relations) {
  1272. var mapOfIdToShape = {};
  1273. var mapOfIdToLabelValues = {};
  1274. // Calculate best initial positions by using greedy layout.
  1275. if (relations.length > 0) {
  1276. var mapOfIdToCircles_1 = layoutGreedyVenn(relations);
  1277. var setRelations_1 = relations.filter(isSet);
  1278. relations
  1279. .forEach(function (relation) {
  1280. var sets = relation.sets;
  1281. var id = sets.join();
  1282. // Get shape from map of circles, or calculate intersection.
  1283. var shape = isSet(relation) ?
  1284. mapOfIdToCircles_1[id] :
  1285. getAreaOfIntersectionBetweenCircles(sets.map(function (set) {
  1286. return mapOfIdToCircles_1[set];
  1287. }));
  1288. // Calculate label values if the set has a shape
  1289. if (shape) {
  1290. mapOfIdToShape[id] = shape;
  1291. mapOfIdToLabelValues[id] = getLabelValues(relation, setRelations_1);
  1292. }
  1293. });
  1294. }
  1295. return { mapOfIdToShape: mapOfIdToShape, mapOfIdToLabelValues: mapOfIdToLabelValues };
  1296. }
  1297. var isValidRelation = function (x) {
  1298. var map = {};
  1299. return (isObject(x) &&
  1300. (isNumber(x.value) && x.value > -1) &&
  1301. (isArray(x.sets) && x.sets.length > 0) &&
  1302. !x.sets.some(function (set) {
  1303. var invalid = false;
  1304. if (!map[set] && isString(set)) {
  1305. map[set] = true;
  1306. }
  1307. else {
  1308. invalid = true;
  1309. }
  1310. return invalid;
  1311. }));
  1312. };
  1313. var isValidSet = function (x) {
  1314. return (isValidRelation(x) && isSet(x) && x.value > 0);
  1315. };
  1316. /**
  1317. * Prepares the venn data so that it is usable for the layout function. Filter
  1318. * out sets, or intersections that includes sets, that are missing in the data
  1319. * or has (value < 1). Adds missing relations between sets in the data as
  1320. * value = 0.
  1321. * @private
  1322. * @param {Array<object>} data The raw input data.
  1323. * @return {Array<object>} Returns an array of valid venn data.
  1324. */
  1325. var processVennData = function processVennData(data) {
  1326. var d = isArray(data) ? data : [];
  1327. var validSets = d
  1328. .reduce(function (arr,
  1329. x) {
  1330. // Check if x is a valid set, and that it is not an duplicate.
  1331. if (isValidSet(x) && arr.indexOf(x.sets[0]) === -1) {
  1332. arr.push(x.sets[0]);
  1333. }
  1334. return arr;
  1335. }, [])
  1336. .sort();
  1337. var mapOfIdToRelation = d.reduce(function (mapOfIdToRelation,
  1338. relation) {
  1339. if (isValidRelation(relation) &&
  1340. !relation.sets.some(function (set) {
  1341. return validSets.indexOf(set) === -1;
  1342. })) {
  1343. mapOfIdToRelation[relation.sets.sort().join()] =
  1344. relation;
  1345. }
  1346. return mapOfIdToRelation;
  1347. }, {});
  1348. validSets.reduce(function (combinations, set, i, arr) {
  1349. var remaining = arr.slice(i + 1);
  1350. remaining.forEach(function (set2) {
  1351. combinations.push(set + ',' + set2);
  1352. });
  1353. return combinations;
  1354. }, []).forEach(function (combination) {
  1355. if (!mapOfIdToRelation[combination]) {
  1356. var obj = {
  1357. sets: combination.split(','),
  1358. value: 0
  1359. };
  1360. mapOfIdToRelation[combination] = obj;
  1361. }
  1362. });
  1363. // Transform map into array.
  1364. return objectValues(mapOfIdToRelation);
  1365. };
  1366. /**
  1367. * Calculates the proper scale to fit the cloud inside the plotting area.
  1368. * @private
  1369. * @todo add unit test
  1370. * @param {number} targetWidth
  1371. * Width of target area.
  1372. * @param {number} targetHeight
  1373. * Height of target area.
  1374. * @param {Highcharts.PolygonBoxObject} field
  1375. * The playing field.
  1376. * @return {Highcharts.Dictionary<number>}
  1377. * Returns the value to scale the playing field up to the size of the target
  1378. * area, and center of x and y.
  1379. */
  1380. var getScale = function getScale(targetWidth,
  1381. targetHeight,
  1382. field) {
  1383. var height = field.bottom - field.top, // top is smaller than bottom
  1384. width = field.right - field.left,
  1385. scaleX = width > 0 ? 1 / width * targetWidth : 1,
  1386. scaleY = height > 0 ? 1 / height * targetHeight : 1,
  1387. adjustX = (field.right + field.left) / 2,
  1388. adjustY = (field.top + field.bottom) / 2,
  1389. scale = Math.min(scaleX,
  1390. scaleY);
  1391. return {
  1392. scale: scale,
  1393. centerX: targetWidth / 2 - adjustX * scale,
  1394. centerY: targetHeight / 2 - adjustY * scale
  1395. };
  1396. };
  1397. /**
  1398. * If a circle is outside a give field, then the boundaries of the field is
  1399. * adjusted accordingly. Modifies the field object which is passed as the first
  1400. * parameter.
  1401. * @private
  1402. * @todo NOTE: Copied from wordcloud, can probably be unified.
  1403. * @param {Highcharts.PolygonBoxObject} field
  1404. * The bounding box of a playing field.
  1405. * @param {Highcharts.CircleObject} circle
  1406. * The bounding box for a placed point.
  1407. * @return {Highcharts.PolygonBoxObject}
  1408. * Returns a modified field object.
  1409. */
  1410. var updateFieldBoundaries = function updateFieldBoundaries(field,
  1411. circle) {
  1412. var left = circle.x - circle.r,
  1413. right = circle.x + circle.r,
  1414. bottom = circle.y + circle.r,
  1415. top = circle.y - circle.r;
  1416. // TODO improve type checking.
  1417. if (!isNumber(field.left) || field.left > left) {
  1418. field.left = left;
  1419. }
  1420. if (!isNumber(field.right) || field.right < right) {
  1421. field.right = right;
  1422. }
  1423. if (!isNumber(field.top) || field.top > top) {
  1424. field.top = top;
  1425. }
  1426. if (!isNumber(field.bottom) || field.bottom < bottom) {
  1427. field.bottom = bottom;
  1428. }
  1429. return field;
  1430. };
  1431. /**
  1432. * A Venn diagram displays all possible logical relations between a collection
  1433. * of different sets. The sets are represented by circles, and the relation
  1434. * between the sets are displayed by the overlap or lack of overlap between
  1435. * them. The venn diagram is a special case of Euler diagrams, which can also
  1436. * be displayed by this series type.
  1437. *
  1438. * @sample {highcharts} highcharts/demo/venn-diagram/
  1439. * Venn diagram
  1440. * @sample {highcharts} highcharts/demo/euler-diagram/
  1441. * Euler diagram
  1442. *
  1443. * @extends plotOptions.scatter
  1444. * @excluding connectEnds, connectNulls, cropThreshold, dragDrop,
  1445. * findNearestPointBy, getExtremesFromAll, jitter, label, linecap,
  1446. * lineWidth, linkedTo, marker, negativeColor, pointInterval,
  1447. * pointIntervalUnit, pointPlacement, pointStart, softThreshold,
  1448. * stacking, steps, threshold, xAxis, yAxis, zoneAxis, zones,
  1449. * dataSorting, boostThreshold, boostBlending
  1450. * @product highcharts
  1451. * @requires modules/venn
  1452. * @optionparent plotOptions.venn
  1453. */
  1454. var vennOptions = {
  1455. borderColor: '#cccccc',
  1456. borderDashStyle: 'solid',
  1457. borderWidth: 1,
  1458. brighten: 0,
  1459. clip: false,
  1460. colorByPoint: true,
  1461. dataLabels: {
  1462. enabled: true,
  1463. verticalAlign: 'middle',
  1464. formatter: function () {
  1465. return this.point.name;
  1466. }
  1467. },
  1468. /**
  1469. * @ignore-option
  1470. * @private
  1471. */
  1472. inactiveOtherPoints: true,
  1473. marker: false,
  1474. opacity: 0.75,
  1475. showInLegend: false,
  1476. states: {
  1477. /**
  1478. * @excluding halo
  1479. */
  1480. hover: {
  1481. opacity: 1,
  1482. borderColor: '#333333'
  1483. },
  1484. /**
  1485. * @excluding halo
  1486. */
  1487. select: {
  1488. color: '#cccccc',
  1489. borderColor: '#000000',
  1490. animation: false
  1491. },
  1492. inactive: {
  1493. opacity: 0.075
  1494. }
  1495. },
  1496. tooltip: {
  1497. pointFormat: '{point.name}: {point.value}'
  1498. }
  1499. };
  1500. var vennSeries = {
  1501. isCartesian: false,
  1502. axisTypes: [],
  1503. directTouch: true,
  1504. pointArrayMap: ['value'],
  1505. init: function () {
  1506. seriesTypes.scatter.prototype.init.apply(this,
  1507. arguments);
  1508. // Venn's opacity is a different option from other series
  1509. delete this.opacity;
  1510. },
  1511. translate: function () {
  1512. var chart = this.chart;
  1513. this.processedXData = this.xData;
  1514. this.generatePoints();
  1515. // Process the data before passing it into the layout function.
  1516. var relations = processVennData(this.options.data);
  1517. // Calculate the positions of each circle.
  1518. var _a = layout(relations),
  1519. mapOfIdToShape = _a.mapOfIdToShape,
  1520. mapOfIdToLabelValues = _a.mapOfIdToLabelValues;
  1521. // Calculate the scale, and center of the plot area.
  1522. var field = Object.keys(mapOfIdToShape)
  1523. .filter(function (key) {
  1524. var shape = mapOfIdToShape[key];
  1525. return shape && isNumber(shape.r);
  1526. })
  1527. .reduce(function (field, key) {
  1528. return updateFieldBoundaries(field, mapOfIdToShape[key]);
  1529. }, { top: 0, bottom: 0, left: 0, right: 0 }), scaling = getScale(chart.plotWidth, chart.plotHeight, field), scale = scaling.scale, centerX = scaling.centerX, centerY = scaling.centerY;
  1530. // Iterate all points and calculate and draw their graphics.
  1531. this.points.forEach(function (point) {
  1532. var sets = isArray(point.sets) ? point.sets : [],
  1533. id = sets.join(),
  1534. shape = mapOfIdToShape[id],
  1535. shapeArgs,
  1536. dataLabelValues = mapOfIdToLabelValues[id] || {},
  1537. dataLabelWidth = dataLabelValues.width,
  1538. dataLabelPosition = dataLabelValues.position,
  1539. dlOptions = point.options && point.options.dataLabels;
  1540. if (shape) {
  1541. if (shape.r) {
  1542. shapeArgs = {
  1543. x: centerX + shape.x * scale,
  1544. y: centerY + shape.y * scale,
  1545. r: shape.r * scale
  1546. };
  1547. }
  1548. else if (shape.d) {
  1549. var d = shape.d;
  1550. d.forEach(function (seg) {
  1551. if (seg[0] === 'M') {
  1552. seg[1] = centerX + seg[1] * scale;
  1553. seg[2] = centerY + seg[2] * scale;
  1554. }
  1555. else if (seg[0] === 'A') {
  1556. seg[1] = seg[1] * scale;
  1557. seg[2] = seg[2] * scale;
  1558. seg[6] = centerX + seg[6] * scale;
  1559. seg[7] = centerY + seg[7] * scale;
  1560. }
  1561. });
  1562. shapeArgs = { d: d };
  1563. }
  1564. // Scale the position for the data label.
  1565. if (dataLabelPosition) {
  1566. dataLabelPosition.x = centerX + dataLabelPosition.x * scale;
  1567. dataLabelPosition.y = centerY + dataLabelPosition.y * scale;
  1568. }
  1569. else {
  1570. dataLabelPosition = {};
  1571. }
  1572. if (isNumber(dataLabelWidth)) {
  1573. dataLabelWidth = Math.round(dataLabelWidth * scale);
  1574. }
  1575. }
  1576. point.shapeArgs = shapeArgs;
  1577. // Placement for the data labels
  1578. if (dataLabelPosition && shapeArgs) {
  1579. point.plotX = dataLabelPosition.x;
  1580. point.plotY = dataLabelPosition.y;
  1581. }
  1582. // Add width for the data label
  1583. if (dataLabelWidth && shapeArgs) {
  1584. point.dlOptions = merge(true, {
  1585. style: {
  1586. width: dataLabelWidth
  1587. }
  1588. }, isObject(dlOptions) && dlOptions);
  1589. }
  1590. // Set name for usage in tooltip and in data label.
  1591. point.name = point.options.name || sets.join('∩');
  1592. });
  1593. },
  1594. /* eslint-disable valid-jsdoc */
  1595. /**
  1596. * Draw the graphics for each point.
  1597. * @private
  1598. */
  1599. drawPoints: function () {
  1600. var series = this,
  1601. // Series properties
  1602. chart = series.chart,
  1603. group = series.group,
  1604. points = series.points || [],
  1605. // Chart properties
  1606. renderer = chart.renderer;
  1607. // Iterate all points and calculate and draw their graphics.
  1608. points.forEach(function (point) {
  1609. var attribs = {
  1610. zIndex: isArray(point.sets) ? point.sets.length : 0
  1611. },
  1612. shapeArgs = point.shapeArgs;
  1613. // Add point attribs
  1614. if (!chart.styledMode) {
  1615. extend(attribs, series.pointAttribs(point, point.state));
  1616. }
  1617. // Draw the point graphic.
  1618. point.draw({
  1619. isNew: !point.graphic,
  1620. animatableAttribs: shapeArgs,
  1621. attribs: attribs,
  1622. group: group,
  1623. renderer: renderer,
  1624. shapeType: shapeArgs && shapeArgs.d ? 'path' : 'circle'
  1625. });
  1626. });
  1627. },
  1628. /**
  1629. * Calculates the style attributes for a point. The attributes can vary
  1630. * depending on the state of the point.
  1631. * @private
  1632. * @param {Highcharts.Point} point
  1633. * The point which will get the resulting attributes.
  1634. * @param {string} [state]
  1635. * The state of the point.
  1636. * @return {Highcharts.SVGAttributes}
  1637. * Returns the calculated attributes.
  1638. */
  1639. pointAttribs: function (point, state) {
  1640. var series = this,
  1641. seriesOptions = series.options || {},
  1642. pointOptions = point && point.options || {},
  1643. stateOptions = (state && seriesOptions.states[state]) || {},
  1644. options = merge(seriesOptions, { color: point && point.color },
  1645. pointOptions,
  1646. stateOptions);
  1647. // Return resulting values for the attributes.
  1648. return {
  1649. 'fill': color(options.color)
  1650. .setOpacity(options.opacity)
  1651. .brighten(options.brightness)
  1652. .get(),
  1653. 'stroke': options.borderColor,
  1654. 'stroke-width': options.borderWidth,
  1655. 'dashstyle': options.borderDashStyle
  1656. };
  1657. },
  1658. /* eslint-enable valid-jsdoc */
  1659. animate: function (init) {
  1660. if (!init) {
  1661. var series = this,
  1662. animOptions = animObject(series.options.animation);
  1663. series.points.forEach(function (point) {
  1664. var args = point.shapeArgs;
  1665. if (point.graphic && args) {
  1666. var attr = {},
  1667. animate = {};
  1668. if (args.d) {
  1669. // If shape is a path, then animate opacity.
  1670. attr.opacity = 0.001;
  1671. }
  1672. else {
  1673. // If shape is a circle, then animate radius.
  1674. attr.r = 0;
  1675. animate.r = args.r;
  1676. }
  1677. point.graphic
  1678. .attr(attr)
  1679. .animate(animate, animOptions);
  1680. // If shape is path, then fade it in after the circles
  1681. // animation
  1682. if (args.d) {
  1683. setTimeout(function () {
  1684. if (point && point.graphic) {
  1685. point.graphic.animate({
  1686. opacity: 1
  1687. });
  1688. }
  1689. }, animOptions.duration);
  1690. }
  1691. }
  1692. }, series);
  1693. }
  1694. },
  1695. utils: {
  1696. addOverlapToSets: addOverlapToSets,
  1697. geometry: GeometryMixin,
  1698. geometryCircles: GeometryCirclesModule,
  1699. getLabelWidth: getLabelWidth,
  1700. getMarginFromCircles: getMarginFromCircles,
  1701. getDistanceBetweenCirclesByOverlap: getDistanceBetweenCirclesByOverlap,
  1702. layoutGreedyVenn: layoutGreedyVenn,
  1703. loss: loss,
  1704. nelderMead: NelderMeadMixin,
  1705. processVennData: processVennData,
  1706. sortByTotalOverlap: sortByTotalOverlap
  1707. }
  1708. };
  1709. var vennPoint = {
  1710. draw: draw,
  1711. shouldDraw: function () {
  1712. var point = this;
  1713. // Only draw points with single sets.
  1714. return !!point.shapeArgs;
  1715. },
  1716. isValid: function () {
  1717. return isNumber(this.value);
  1718. }
  1719. };
  1720. /**
  1721. * A `venn` series. If the [type](#series.venn.type) option is
  1722. * not specified, it is inherited from [chart.type](#chart.type).
  1723. *
  1724. * @extends series,plotOptions.venn
  1725. * @excluding connectEnds, connectNulls, cropThreshold, dataParser, dataURL,
  1726. * findNearestPointBy, getExtremesFromAll, label, linecap, lineWidth,
  1727. * linkedTo, marker, negativeColor, pointInterval, pointIntervalUnit,
  1728. * pointPlacement, pointStart, softThreshold, stack, stacking, steps,
  1729. * threshold, xAxis, yAxis, zoneAxis, zones, dataSorting,
  1730. * boostThreshold, boostBlending
  1731. * @product highcharts
  1732. * @requires modules/venn
  1733. * @apioption series.venn
  1734. */
  1735. /**
  1736. * @type {Array<*>}
  1737. * @extends series.scatter.data
  1738. * @excluding marker, x, y
  1739. * @product highcharts
  1740. * @apioption series.venn.data
  1741. */
  1742. /**
  1743. * The name of the point. Used in data labels and tooltip. If name is not
  1744. * defined then it will default to the joined values in
  1745. * [sets](#series.venn.sets).
  1746. *
  1747. * @sample {highcharts} highcharts/demo/venn-diagram/
  1748. * Venn diagram
  1749. * @sample {highcharts} highcharts/demo/euler-diagram/
  1750. * Euler diagram
  1751. *
  1752. * @type {number}
  1753. * @since 7.0.0
  1754. * @product highcharts
  1755. * @apioption series.venn.data.name
  1756. */
  1757. /**
  1758. * The value of the point, resulting in a relative area of the circle, or area
  1759. * of overlap between two sets in the venn or euler diagram.
  1760. *
  1761. * @sample {highcharts} highcharts/demo/venn-diagram/
  1762. * Venn diagram
  1763. * @sample {highcharts} highcharts/demo/euler-diagram/
  1764. * Euler diagram
  1765. *
  1766. * @type {number}
  1767. * @since 7.0.0
  1768. * @product highcharts
  1769. * @apioption series.venn.data.value
  1770. */
  1771. /**
  1772. * The set or sets the options will be applied to. If a single entry is defined,
  1773. * then it will create a new set. If more than one entry is defined, then it
  1774. * will define the overlap between the sets in the array.
  1775. *
  1776. * @sample {highcharts} highcharts/demo/venn-diagram/
  1777. * Venn diagram
  1778. * @sample {highcharts} highcharts/demo/euler-diagram/
  1779. * Euler diagram
  1780. *
  1781. * @type {Array<string>}
  1782. * @since 7.0.0
  1783. * @product highcharts
  1784. * @apioption series.venn.data.sets
  1785. */
  1786. /**
  1787. * @excluding halo
  1788. * @apioption series.venn.states.hover
  1789. */
  1790. /**
  1791. * @excluding halo
  1792. * @apioption series.venn.states.select
  1793. */
  1794. ''; // detach doclets above
  1795. /**
  1796. * @private
  1797. * @class
  1798. * @name Highcharts.seriesTypes.venn
  1799. *
  1800. * @augments Highcharts.Series
  1801. */
  1802. BaseSeries.seriesType('venn', 'scatter', vennOptions, vennSeries, vennPoint);
  1803. /* eslint-disable no-invalid-this */
  1804. // Modify final series options.
  1805. addEvent(seriesTypes.venn, 'afterSetOptions', function (e) {
  1806. var options = e.options,
  1807. states = options.states;
  1808. if (this.is('venn')) {
  1809. // Explicitly disable all halo options.
  1810. Object.keys(states).forEach(function (state) {
  1811. states[state].halo = false;
  1812. });
  1813. }
  1814. });
  1815. });
  1816. _registerModule(_modules, 'masters/modules/venn.src.js', [], function () {
  1817. });
  1818. }));