histogram.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import _ from 'lodash';
  2. import TimeSeries from 'app/core/time_series2';
  3. /**
  4. * Convert series into array of series values.
  5. * @param data Array of series
  6. */
  7. export function getSeriesValues(dataList: TimeSeries[]): number[] {
  8. const VALUE_INDEX = 0;
  9. const values = [];
  10. // Count histogam stats
  11. for (let i = 0; i < dataList.length; i++) {
  12. const series = dataList[i];
  13. const datapoints = series.datapoints;
  14. for (let j = 0; j < datapoints.length; j++) {
  15. if (datapoints[j][VALUE_INDEX] !== null) {
  16. values.push(datapoints[j][VALUE_INDEX]);
  17. }
  18. }
  19. }
  20. return values;
  21. }
  22. /**
  23. * Convert array of values into timeseries-like histogram:
  24. * [[val_1, count_1], [val_2, count_2], ..., [val_n, count_n]]
  25. * @param values
  26. * @param bucketSize
  27. */
  28. export function convertValuesToHistogram(values: number[], bucketSize: number, min: number, max: number): any[] {
  29. const histogram = {};
  30. const minBound = getBucketBound(min, bucketSize);
  31. const maxBound = getBucketBound(max, bucketSize);
  32. let bound = minBound;
  33. let n = 0;
  34. while (bound <= maxBound) {
  35. histogram[bound] = 0;
  36. bound = minBound + bucketSize * n;
  37. n++;
  38. }
  39. for (let i = 0; i < values.length; i++) {
  40. const bound = getBucketBound(values[i], bucketSize);
  41. histogram[bound] = histogram[bound] + 1;
  42. }
  43. const histogamSeries = _.map(histogram, (count, bound) => {
  44. return [Number(bound), count];
  45. });
  46. // Sort by Y axis values
  47. return _.sortBy(histogamSeries, point => point[0]);
  48. }
  49. /**
  50. * Convert series into array of histogram data.
  51. * @param data Array of series
  52. * @param bucketSize
  53. */
  54. export function convertToHistogramData(
  55. data: any,
  56. bucketSize: number,
  57. hiddenSeries: any,
  58. min: number,
  59. max: number
  60. ): any[] {
  61. return data.map(series => {
  62. const values = getSeriesValues([series]);
  63. series.histogram = true;
  64. if (!hiddenSeries[series.alias]) {
  65. const histogram = convertValuesToHistogram(values, bucketSize, min, max);
  66. series.data = histogram;
  67. } else {
  68. series.data = [];
  69. }
  70. return series;
  71. });
  72. }
  73. function getBucketBound(value: number, bucketSize: number): number {
  74. return Math.floor(value / bucketSize) * bucketSize;
  75. }