heatmap_data_converter.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. import _ from 'lodash';
  2. let VALUE_INDEX = 0;
  3. let TIME_INDEX = 1;
  4. interface XBucket {
  5. x: number;
  6. buckets: any;
  7. }
  8. interface YBucket {
  9. y: number;
  10. values: number[];
  11. }
  12. /**
  13. * Convert histogram represented by the list of series to heatmap object.
  14. * @param seriesList List of time series
  15. */
  16. function histogramToHeatmap(seriesList) {
  17. let heatmap = {};
  18. for (let i = 0; i < seriesList.length; i++) {
  19. let series = seriesList[i];
  20. let bound = i;
  21. if (isNaN(bound)) {
  22. return heatmap;
  23. }
  24. for (let point of series.datapoints) {
  25. let count = point[VALUE_INDEX];
  26. let time = point[TIME_INDEX];
  27. if (!_.isNumber(count)) {
  28. continue;
  29. }
  30. let bucket = heatmap[time];
  31. if (!bucket) {
  32. bucket = heatmap[time] = { x: time, buckets: {} };
  33. }
  34. bucket.buckets[bound] = {
  35. y: bound,
  36. count: count,
  37. bounds: {
  38. top: null,
  39. bottom: bound,
  40. },
  41. values: [],
  42. points: [],
  43. };
  44. }
  45. }
  46. return heatmap;
  47. }
  48. /**
  49. * Sort series representing histogram by label value.
  50. */
  51. function sortSeriesByLabel(s1, s2) {
  52. let label1, label2;
  53. try {
  54. // fail if not integer. might happen with bad queries
  55. label1 = parseHistogramLabel(s1.label);
  56. label2 = parseHistogramLabel(s2.label);
  57. } catch (err) {
  58. console.log(err.message || err);
  59. return 0;
  60. }
  61. if (label1 > label2) {
  62. return 1;
  63. }
  64. if (label1 < label2) {
  65. return -1;
  66. }
  67. return 0;
  68. }
  69. function parseHistogramLabel(label: string): number {
  70. if (label === '+Inf' || label === 'inf') {
  71. return +Infinity;
  72. }
  73. const value = Number(label);
  74. if (isNaN(value)) {
  75. throw new Error(`Error parsing histogram label: ${label} is not a number`);
  76. }
  77. return value;
  78. }
  79. /**
  80. * Convert buckets into linear array of "cards" - objects, represented heatmap elements.
  81. * @param {Object} buckets
  82. * @return {Array} Array of "card" objects
  83. */
  84. function convertToCards(buckets) {
  85. let min = 0,
  86. max = 0;
  87. let cards = [];
  88. _.forEach(buckets, xBucket => {
  89. _.forEach(xBucket.buckets, yBucket => {
  90. let card = {
  91. x: xBucket.x,
  92. y: yBucket.y,
  93. yBounds: yBucket.bounds,
  94. values: yBucket.values,
  95. count: yBucket.count,
  96. };
  97. cards.push(card);
  98. if (cards.length === 1) {
  99. min = yBucket.count;
  100. max = yBucket.count;
  101. }
  102. min = yBucket.count < min ? yBucket.count : min;
  103. max = yBucket.count > max ? yBucket.count : max;
  104. });
  105. });
  106. let cardStats = { min, max };
  107. return { cards, cardStats };
  108. }
  109. /**
  110. * Special method for log scales. When series converted into buckets with log scale,
  111. * for simplification, 0 values are converted into 0, not into -Infinity. On the other hand, we mean
  112. * that all values less than series minimum, is 0 values, and we create special "minimum" bucket for
  113. * that values (actually, there're no values less than minimum, so this bucket is empty).
  114. * 8-16| | ** | | * | **|
  115. * 4-8| * |* *|* |** *| * |
  116. * 2-4| * *| | ***| |* |
  117. * 1-2|* | | | | | This bucket contains minimum series value
  118. * 0.5-1|____|____|____|____|____| This bucket should be displayed as 0 on graph
  119. * 0|____|____|____|____|____| This bucket is for 0 values (should actually be -Infinity)
  120. * So we should merge two bottom buckets into one (0-value bucket).
  121. *
  122. * @param {Object} buckets Heatmap buckets
  123. * @param {Number} minValue Minimum series value
  124. * @return {Object} Transformed buckets
  125. */
  126. function mergeZeroBuckets(buckets, minValue) {
  127. _.forEach(buckets, xBucket => {
  128. let yBuckets = xBucket.buckets;
  129. let emptyBucket = {
  130. bounds: { bottom: 0, top: 0 },
  131. values: [],
  132. points: [],
  133. count: 0,
  134. };
  135. let nullBucket = yBuckets[0] || emptyBucket;
  136. let minBucket = yBuckets[minValue] || emptyBucket;
  137. let newBucket = {
  138. y: 0,
  139. bounds: { bottom: minValue, top: minBucket.bounds.top || minValue },
  140. values: [],
  141. points: [],
  142. count: 0,
  143. };
  144. newBucket.points = nullBucket.points.concat(minBucket.points);
  145. newBucket.values = nullBucket.values.concat(minBucket.values);
  146. newBucket.count = newBucket.values.length;
  147. if (newBucket.count === 0) {
  148. return;
  149. }
  150. delete yBuckets[minValue];
  151. yBuckets[0] = newBucket;
  152. });
  153. return buckets;
  154. }
  155. /**
  156. * Convert set of time series into heatmap buckets
  157. * @return {Object} Heatmap object:
  158. * {
  159. * xBucketBound_1: {
  160. * x: xBucketBound_1,
  161. * buckets: {
  162. * yBucketBound_1: {
  163. * y: yBucketBound_1,
  164. * bounds: {bottom, top}
  165. * values: [val_1, val_2, ..., val_K],
  166. * points: [[val_Y, val_X, series_name], ..., [...]],
  167. * seriesStat: {seriesName_1: val_1, seriesName_2: val_2}
  168. * },
  169. * ...
  170. * yBucketBound_M: {}
  171. * },
  172. * values: [val_1, val_2, ..., val_K],
  173. * points: [
  174. * [val_Y, val_X, series_name], (point_1)
  175. * ...
  176. * [...] (point_K)
  177. * ]
  178. * },
  179. * xBucketBound_2: {},
  180. * ...
  181. * xBucketBound_N: {}
  182. * }
  183. */
  184. function convertToHeatMap(seriesList, yBucketSize, xBucketSize, logBase = 1) {
  185. let heatmap = {};
  186. for (let series of seriesList) {
  187. let datapoints = series.datapoints;
  188. let seriesName = series.label;
  189. // Slice series into X axis buckets
  190. // | | ** | | * | **|
  191. // | * |* *|* |** *| * |
  192. // |** *| | ***| |* |
  193. // |____|____|____|____|____|_
  194. //
  195. _.forEach(datapoints, point => {
  196. let bucketBound = getBucketBound(point[TIME_INDEX], xBucketSize);
  197. pushToXBuckets(heatmap, point, bucketBound, seriesName);
  198. });
  199. }
  200. // Slice X axis buckets into Y (value) buckets
  201. // | **| |2|,
  202. // | * | --\ |1|,
  203. // |* | --/ |1|,
  204. // |____| |0|
  205. //
  206. _.forEach(heatmap, xBucket => {
  207. if (logBase !== 1) {
  208. xBucket.buckets = convertToLogScaleValueBuckets(xBucket, yBucketSize, logBase);
  209. } else {
  210. xBucket.buckets = convertToValueBuckets(xBucket, yBucketSize);
  211. }
  212. });
  213. return heatmap;
  214. }
  215. function pushToXBuckets(buckets, point, bucketNum, seriesName) {
  216. let value = point[VALUE_INDEX];
  217. if (value === null || value === undefined || isNaN(value)) {
  218. return;
  219. }
  220. // Add series name to point for future identification
  221. let point_ext = _.concat(point, seriesName);
  222. if (buckets[bucketNum] && buckets[bucketNum].values) {
  223. buckets[bucketNum].values.push(value);
  224. buckets[bucketNum].points.push(point_ext);
  225. } else {
  226. buckets[bucketNum] = {
  227. x: bucketNum,
  228. values: [value],
  229. points: [point_ext],
  230. };
  231. }
  232. }
  233. function pushToYBuckets(buckets, bucketNum, value, point, bounds) {
  234. var count = 1;
  235. // Use the 3rd argument as scale/count
  236. if (point.length > 3) {
  237. count = parseInt(point[2]);
  238. }
  239. if (buckets[bucketNum]) {
  240. buckets[bucketNum].values.push(value);
  241. buckets[bucketNum].points.push(point);
  242. buckets[bucketNum].count += count;
  243. } else {
  244. buckets[bucketNum] = {
  245. y: bucketNum,
  246. bounds: bounds,
  247. values: [value],
  248. points: [point],
  249. count: count,
  250. };
  251. }
  252. }
  253. function getValueBucketBound(value, yBucketSize, logBase) {
  254. if (logBase === 1) {
  255. return getBucketBound(value, yBucketSize);
  256. } else {
  257. return getLogScaleBucketBound(value, yBucketSize, logBase);
  258. }
  259. }
  260. /**
  261. * Find bucket for given value (for linear scale)
  262. */
  263. function getBucketBounds(value, bucketSize) {
  264. let bottom, top;
  265. bottom = Math.floor(value / bucketSize) * bucketSize;
  266. top = (Math.floor(value / bucketSize) + 1) * bucketSize;
  267. return { bottom, top };
  268. }
  269. function getBucketBound(value, bucketSize) {
  270. let bounds = getBucketBounds(value, bucketSize);
  271. return bounds.bottom;
  272. }
  273. function convertToValueBuckets(xBucket, bucketSize) {
  274. let values = xBucket.values;
  275. let points = xBucket.points;
  276. let buckets = {};
  277. _.forEach(values, (val, index) => {
  278. let bounds = getBucketBounds(val, bucketSize);
  279. let bucketNum = bounds.bottom;
  280. pushToYBuckets(buckets, bucketNum, val, points[index], bounds);
  281. });
  282. return buckets;
  283. }
  284. /**
  285. * Find bucket for given value (for log scales)
  286. */
  287. function getLogScaleBucketBounds(value, yBucketSplitFactor, logBase) {
  288. let top, bottom;
  289. if (value === 0) {
  290. return { bottom: 0, top: 0 };
  291. }
  292. let value_log = logp(value, logBase);
  293. let pow, powTop;
  294. if (yBucketSplitFactor === 1 || !yBucketSplitFactor) {
  295. pow = Math.floor(value_log);
  296. powTop = pow + 1;
  297. } else {
  298. let additional_bucket_size = 1 / yBucketSplitFactor;
  299. let additional_log = value_log - Math.floor(value_log);
  300. additional_log = Math.floor(additional_log / additional_bucket_size) * additional_bucket_size;
  301. pow = Math.floor(value_log) + additional_log;
  302. powTop = pow + additional_bucket_size;
  303. }
  304. bottom = Math.pow(logBase, pow);
  305. top = Math.pow(logBase, powTop);
  306. return { bottom, top };
  307. }
  308. function getLogScaleBucketBound(value, yBucketSplitFactor, logBase) {
  309. let bounds = getLogScaleBucketBounds(value, yBucketSplitFactor, logBase);
  310. return bounds.bottom;
  311. }
  312. function convertToLogScaleValueBuckets(xBucket, yBucketSplitFactor, logBase) {
  313. let values = xBucket.values;
  314. let points = xBucket.points;
  315. let buckets = {};
  316. _.forEach(values, (val, index) => {
  317. let bounds = getLogScaleBucketBounds(val, yBucketSplitFactor, logBase);
  318. let bucketNum = bounds.bottom;
  319. pushToYBuckets(buckets, bucketNum, val, points[index], bounds);
  320. });
  321. return buckets;
  322. }
  323. /**
  324. * Logarithm for custom base
  325. * @param value
  326. * @param base logarithm base
  327. */
  328. function logp(value, base) {
  329. return Math.log(value) / Math.log(base);
  330. }
  331. /**
  332. * Calculate size of Y bucket from given buckets bounds.
  333. * @param bounds Array of Y buckets bounds
  334. * @param logBase Logarithm base
  335. */
  336. function calculateBucketSize(bounds: number[], logBase = 1): number {
  337. let bucketSize = Infinity;
  338. if (bounds.length === 0) {
  339. return 0;
  340. } else if (bounds.length === 1) {
  341. return bounds[0];
  342. } else {
  343. bounds = _.sortBy(bounds);
  344. for (let i = 1; i < bounds.length; i++) {
  345. let distance = getDistance(bounds[i], bounds[i - 1], logBase);
  346. bucketSize = distance < bucketSize ? distance : bucketSize;
  347. }
  348. }
  349. return bucketSize;
  350. }
  351. /**
  352. * Calculate distance between two numbers in given scale (linear or logarithmic).
  353. * @param a
  354. * @param b
  355. * @param logBase
  356. */
  357. function getDistance(a: number, b: number, logBase = 1): number {
  358. if (logBase === 1) {
  359. // Linear distance
  360. return Math.abs(b - a);
  361. } else {
  362. // logarithmic distance
  363. let ratio = Math.max(a, b) / Math.min(a, b);
  364. return logp(ratio, logBase);
  365. }
  366. }
  367. /**
  368. * Compare two heatmap data objects
  369. * @param objA
  370. * @param objB
  371. */
  372. function isHeatmapDataEqual(objA: any, objB: any): boolean {
  373. let is_eql = !emptyXOR(objA, objB);
  374. _.forEach(objA, (xBucket: XBucket, x) => {
  375. if (objB[x]) {
  376. if (emptyXOR(xBucket.buckets, objB[x].buckets)) {
  377. is_eql = false;
  378. return false;
  379. }
  380. _.forEach(xBucket.buckets, (yBucket: YBucket, y) => {
  381. if (objB[x].buckets && objB[x].buckets[y]) {
  382. if (objB[x].buckets[y].values) {
  383. is_eql = _.isEqual(_.sortBy(yBucket.values), _.sortBy(objB[x].buckets[y].values));
  384. if (!is_eql) {
  385. return false;
  386. } else {
  387. return true;
  388. }
  389. } else {
  390. is_eql = false;
  391. return false;
  392. }
  393. } else {
  394. is_eql = false;
  395. return false;
  396. }
  397. });
  398. if (!is_eql) {
  399. return false;
  400. } else {
  401. return true;
  402. }
  403. } else {
  404. is_eql = false;
  405. return false;
  406. }
  407. });
  408. return is_eql;
  409. }
  410. function emptyXOR(foo: any, bar: any): boolean {
  411. return (_.isEmpty(foo) || _.isEmpty(bar)) && !(_.isEmpty(foo) && _.isEmpty(bar));
  412. }
  413. export {
  414. convertToHeatMap,
  415. histogramToHeatmap,
  416. convertToCards,
  417. mergeZeroBuckets,
  418. getValueBucketBound,
  419. isHeatmapDataEqual,
  420. calculateBucketSize,
  421. sortSeriesByLabel,
  422. };