histogram.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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: any = {};
  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. // filter out values outside the min and max boundaries
  41. if (values[i] < min || values[i] > max) {
  42. continue;
  43. }
  44. const bound = getBucketBound(values[i], bucketSize);
  45. histogram[bound] = histogram[bound] + 1;
  46. }
  47. const histogamSeries = _.map(histogram, (count, bound) => {
  48. return [Number(bound), count];
  49. });
  50. // Sort by Y axis values
  51. return _.sortBy(histogamSeries, point => point[0]);
  52. }
  53. /**
  54. * Convert series into array of histogram data.
  55. * @param data Array of series
  56. * @param bucketSize
  57. */
  58. export function convertToHistogramData(
  59. data: any,
  60. bucketSize: number,
  61. hiddenSeries: any,
  62. min: number,
  63. max: number
  64. ): any[] {
  65. return data.map((series: any) => {
  66. const values = getSeriesValues([series]);
  67. series.histogram = true;
  68. if (!hiddenSeries[series.alias]) {
  69. const histogram = convertValuesToHistogram(values, bucketSize, min, max);
  70. series.data = histogram;
  71. } else {
  72. series.data = [];
  73. }
  74. return series;
  75. });
  76. }
  77. function getBucketBound(value: number, bucketSize: number): number {
  78. return Math.floor(value / bucketSize) * bucketSize;
  79. }