histogram.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { histogram } from 'd3';
  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 minBound = getBucketBound(min, bucketSize);
  30. const maxBound = getBucketBound(max, bucketSize);
  31. const histGenerator = histogram()
  32. .domain([minBound, maxBound])
  33. .thresholds(Math.round(max - min) / bucketSize);
  34. return histGenerator(values).map((bin) => {
  35. return [bin.x0, bin.length];
  36. });
  37. }
  38. /**
  39. * Convert series into array of histogram data.
  40. * @param data Array of series
  41. * @param bucketSize
  42. */
  43. export function convertToHistogramData(
  44. data: any,
  45. bucketSize: number,
  46. hiddenSeries: any,
  47. min: number,
  48. max: number
  49. ): any[] {
  50. return data.map((series: any) => {
  51. const values = getSeriesValues([series]);
  52. series.histogram = true;
  53. if (!hiddenSeries[series.alias]) {
  54. const histogram = convertValuesToHistogram(values, bucketSize, min, max);
  55. series.data = histogram;
  56. } else {
  57. series.data = [];
  58. }
  59. return series;
  60. });
  61. }
  62. function getBucketBound(value: number, bucketSize: number): number {
  63. return Math.floor(value / bucketSize) * bucketSize;
  64. }