index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // index.ts
  2. import { distanceWeight as spatialWeight } from "@turf/distance-weight";
  3. import { featureEach } from "@turf/meta";
  4. function moranIndex(fc, options) {
  5. var _a, _b;
  6. const inputField = options.inputField;
  7. const threshold = options.threshold || 1e5;
  8. const p = options.p || 2;
  9. const binary = (_a = options.binary) != null ? _a : false;
  10. const alpha = options.alpha || -1;
  11. const standardization = (_b = options.standardization) != null ? _b : true;
  12. const weight = spatialWeight(fc, {
  13. alpha,
  14. binary,
  15. p,
  16. standardization,
  17. threshold
  18. });
  19. const y = [];
  20. featureEach(fc, (feature) => {
  21. const feaProperties = feature.properties || {};
  22. y.push(feaProperties[inputField]);
  23. });
  24. const yMean = mean(y);
  25. const yVar = variance(y);
  26. let weightSum = 0;
  27. let s0 = 0;
  28. let s1 = 0;
  29. let s2 = 0;
  30. const n = weight.length;
  31. for (let i = 0; i < n; i++) {
  32. let subS2 = 0;
  33. for (let j = 0; j < n; j++) {
  34. weightSum += weight[i][j] * (y[i] - yMean) * (y[j] - yMean);
  35. s0 += weight[i][j];
  36. s1 += Math.pow(weight[i][j] + weight[j][i], 2);
  37. subS2 += weight[i][j] + weight[j][i];
  38. }
  39. s2 += Math.pow(subS2, 2);
  40. }
  41. s1 = 0.5 * s1;
  42. const moranIndex2 = weightSum / s0 / yVar;
  43. const expectedMoranIndex = -1 / (n - 1);
  44. const vNum = n * n * s1 - n * s2 + 3 * (s0 * s0);
  45. const vDen = (n - 1) * (n + 1) * (s0 * s0);
  46. const vNorm = vNum / vDen - expectedMoranIndex * expectedMoranIndex;
  47. const stdNorm = Math.sqrt(vNorm);
  48. const zNorm = (moranIndex2 - expectedMoranIndex) / stdNorm;
  49. return {
  50. expectedMoranIndex,
  51. moranIndex: moranIndex2,
  52. stdNorm,
  53. zNorm
  54. };
  55. }
  56. function mean(y) {
  57. let sum = 0;
  58. for (const item of y) {
  59. sum += item;
  60. }
  61. return sum / y.length;
  62. }
  63. function variance(y) {
  64. const yMean = mean(y);
  65. let sum = 0;
  66. for (const item of y) {
  67. sum += Math.pow(item - yMean, 2);
  68. }
  69. return sum / y.length;
  70. }
  71. var turf_moran_index_default = moranIndex;
  72. export {
  73. turf_moran_index_default as default,
  74. moranIndex
  75. };
  76. //# sourceMappingURL=index.js.map