index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // index.ts
  2. import { centroid } from "@turf/centroid";
  3. import { getCoord } from "@turf/invariant";
  4. import { featureEach } from "@turf/meta";
  5. function pNormDistance(feature1, feature2, p = 2) {
  6. const coordinate1 = getCoord(feature1);
  7. const coordinate2 = getCoord(feature2);
  8. const xDiff = coordinate1[0] - coordinate2[0];
  9. const yDiff = coordinate1[1] - coordinate2[1];
  10. if (p === 1) {
  11. return Math.abs(xDiff) + Math.abs(yDiff);
  12. }
  13. return Math.pow(Math.pow(xDiff, p) + Math.pow(yDiff, p), 1 / p);
  14. }
  15. function distanceWeight(fc, options) {
  16. var _a, _b;
  17. options = options || {};
  18. const threshold = options.threshold || 1e4;
  19. const p = options.p || 2;
  20. const binary = (_a = options.binary) != null ? _a : false;
  21. const alpha = options.alpha || -1;
  22. const rowTransform = (_b = options.standardization) != null ? _b : false;
  23. const features = [];
  24. featureEach(fc, (feature) => {
  25. features.push(centroid(feature));
  26. });
  27. const weights = [];
  28. for (let i = 0; i < features.length; i++) {
  29. weights[i] = [];
  30. }
  31. for (let i = 0; i < features.length; i++) {
  32. for (let j = i; j < features.length; j++) {
  33. if (i === j) {
  34. weights[i][j] = 0;
  35. }
  36. const dis = pNormDistance(features[i], features[j], p);
  37. weights[i][j] = dis;
  38. weights[j][i] = dis;
  39. }
  40. }
  41. for (let i = 0; i < features.length; i++) {
  42. for (let j = 0; j < features.length; j++) {
  43. const dis = weights[i][j];
  44. if (dis === 0) {
  45. continue;
  46. }
  47. if (binary) {
  48. if (dis <= threshold) {
  49. weights[i][j] = 1;
  50. } else {
  51. weights[i][j] = 0;
  52. }
  53. } else {
  54. if (dis <= threshold) {
  55. weights[i][j] = Math.pow(dis, alpha);
  56. } else {
  57. weights[i][j] = 0;
  58. }
  59. }
  60. }
  61. }
  62. if (rowTransform) {
  63. for (let i = 0; i < features.length; i++) {
  64. const rowSum = weights[i].reduce((sum, currentVal) => {
  65. return sum + currentVal;
  66. }, 0);
  67. for (let j = 0; j < features.length; j++) {
  68. weights[i][j] = weights[i][j] / rowSum;
  69. }
  70. }
  71. }
  72. return weights;
  73. }
  74. var turf_distance_weight_default = distanceWeight;
  75. export {
  76. turf_distance_weight_default as default,
  77. distanceWeight,
  78. pNormDistance
  79. };
  80. //# sourceMappingURL=index.js.map