kde.js 1.1 KB

123456789101112131415161718192021222324252627282930
  1. import pdf from 'pdfast';
  2. import { group } from 'd3-array';
  3. export function defined(d) {
  4. return d !== undefined && d !== null && !Number.isNaN(d);
  5. }
  6. /**
  7. * Kernel Density Estimation base on [pdfast](https://www.npmjs.com/package/pdfast),
  8. * generating probability density function (pdf) using triangular kernel,
  9. * optimized to run in O(N + K).
  10. */
  11. export const KDE = (options) => {
  12. const { field, groupBy, as = ['y', 'size'], min, max, size = 10, width, } = options;
  13. const [yField, sizeField] = as;
  14. return (data) => {
  15. const gs = Array.from(group(data, (d) => groupBy.map((gb) => d[gb]).join('-')).values());
  16. return gs.map((g) => {
  17. const pdfResult = pdf.create(g.map((i) => i[field]), {
  18. min,
  19. max,
  20. size,
  21. width,
  22. });
  23. const _y = pdfResult.map((result) => result.x);
  24. const _size = pdfResult.map((result) => result.y);
  25. return Object.assign(Object.assign({}, g[0]), { [yField]: _y, [sizeField]: _size });
  26. });
  27. };
  28. };
  29. KDE.props = {};
  30. //# sourceMappingURL=kde.js.map