CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-turf--turf

A JavaScript library for performing geospatial operations with GeoJSON data

Pending
Overview
Eval results
Files

spatial-analysis.mddocs/

Spatial Analysis and Statistics

Advanced spatial analysis functions including clustering, interpolation, statistical analysis, and spatial autocorrelation. These functions provide sophisticated tools for analyzing spatial patterns and relationships.

Capabilities

Clustering Analysis

Group points based on spatial proximity and density.

/**
 * Takes a set of points and partition them into clusters using the DBSCAN algorithm.
 */
function clustersDbscan(
  points: FeatureCollection<Point>,
  maxDistance: number,
  options?: { units?: Units; minPoints?: number; mutate?: boolean }
): FeatureCollection<Point>;

/**
 * Takes a set of points and partition them into clusters according to KMEANS algorithm.
 */
function clustersKmeans<P>(
  points: FeatureCollection<Point, P>,
  options?: { numberOfClusters?: number; mutate?: boolean }
): FeatureCollection<Point, P>;

Usage Examples:

import { clustersDbscan, clustersKmeans, randomPoint } from "@turf/turf";

// Generate sample data
const points = randomPoint(100, { bbox: [-10, -10, 10, 10] });

// DBSCAN clustering - density-based
const dbscanClusters = clustersDbscan(points, 2, {
  units: 'kilometers',
  minPoints: 3
});

// K-means clustering - centroid-based
const kmeansClusters = clustersKmeans(points, {
  numberOfClusters: 5
});

// Count clusters
const dbscanClusterCount = new Set(
  dbscanClusters.features.map(f => f.properties.cluster)
).size;

console.log(`DBSCAN found ${dbscanClusterCount} clusters`);
console.log(`K-means created 5 clusters`);

Spatial Interpolation

Estimate values at unmeasured locations based on measured sample points.

/**
 * Takes a set of sample points with known values and creates a grid of interpolated values.
 */
function interpolate(
  points: FeatureCollection<Point>,
  cellSize: number,
  options?: { 
    gridType?: 'point' | 'square' | 'hex' | 'triangle';
    property?: string;
    units?: Units;
    weight?: number;
  }
): FeatureCollection<Point>;

Usage Examples:

import { interpolate, randomPoint } from "@turf/turf";

// Create sample points with temperature data
const samplePoints = randomPoint(50, { bbox: [-5, -5, 5, 5] });
samplePoints.features.forEach((point, i) => {
  point.properties = { temperature: Math.random() * 30 + 10 }; // 10-40°C
});

// Interpolate temperature values across grid
const interpolatedGrid = interpolate(samplePoints, 0.5, {
  gridType: 'square',
  property: 'temperature',
  units: 'kilometers',
  weight: 1
});

console.log(`Interpolated ${interpolatedGrid.features.length} grid cells`);
console.log('Sample interpolated value:', interpolatedGrid.features[0].properties);

Contour Analysis

Generate contour lines and filled contours from point data.

/**
 * Takes a grid FeatureCollection of Point features with z-values and an array of value breaks
 * and generates filled contour polygons.
 */
function isobands(
  pointGrid: FeatureCollection<Point>,
  breaks: number[],
  options?: { 
    zProperty?: string;
    commonProperties?: GeoJsonProperties;
    breaksProperties?: GeoJsonProperties[];
  }
): FeatureCollection<Polygon>;

/**
 * Takes a grid FeatureCollection of Point features with z-values and an array of value breaks
 * and generates contour line features.
 */
function isolines(
  pointGrid: FeatureCollection<Point>,
  breaks: number[],
  options?: {
    zProperty?: string;
    commonProperties?: GeoJsonProperties;
    breaksProperties?: GeoJsonProperties[];
  }
): FeatureCollection<LineString>;

Usage Examples:

import { isobands, isolines, pointGrid } from "@turf/turf";

// Create elevation grid
const bbox = [-5, -5, 5, 5];
const grid = pointGrid(bbox, 0.5, { units: 'kilometers' });

// Add elevation data
grid.features.forEach(point => {
  const [x, y] = point.geometry.coordinates;
  point.properties.elevation = Math.sin(x) * Math.cos(y) * 1000 + 500;
});

// Define elevation breaks
const breaks = [0, 200, 400, 600, 800, 1000, 1200];

// Generate filled contours (isobands)
const contourPolygons = isobands(grid, breaks, {
  zProperty: 'elevation',
  commonProperties: { type: 'elevation_zone' }
});

// Generate contour lines (isolines)
const contourLines = isolines(grid, breaks, {
  zProperty: 'elevation',
  commonProperties: { type: 'elevation_contour' }
});

console.log(`Generated ${contourPolygons.features.length} contour polygons`);
console.log(`Generated ${contourLines.features.length} contour lines`);

Statistical Analysis

Perform spatial statistical tests and calculations.

/**
 * Calculates Moran's I spatial autocorrelation.
 */
function moranIndex(
  geojson: FeatureCollection<any>,
  options?: { 
    inputField?: string;
    threshold?: number;
    p?: number;
    binary?: boolean;
    alpha?: number;
    standardization?: string;
  }
): { moranI: number; expectedI: number; varianceI: number; zNorm: number };

/**
 * Calculates the standard deviational ellipse for a set of points, 
 * returning a feature representing the ellipse.
 */
function standardDeviationalEllipse(
  points: FeatureCollection<Point>,
  options?: { 
    weight?: string;
    steps?: number;
    properties?: GeoJsonProperties;
  }
): Feature<Polygon>;

Usage Examples:

import { moranIndex, standardDeviationalEllipse, randomPoint } from "@turf/turf";

// Generate clustered points
const points = randomPoint(100, { bbox: [-10, -10, 10, 10] });

// Add correlated values
points.features.forEach(point => {
  const [x, y] = point.geometry.coordinates;
  point.properties.value = x * y + Math.random() * 10;
});

// Calculate Moran's I for spatial autocorrelation
const moran = moranIndex(points, {
  inputField: 'value',
  threshold: 5,
  binary: false
});

// Calculate standard deviational ellipse
const ellipse = standardDeviationalEllipse(points, {
  steps: 64,
  properties: { analysis: 'std_ellipse' }
});

console.log(`Moran's I: ${moran.moranI} (expected: ${moran.expectedI})`);
console.log(`Z-score: ${moran.zNorm}`);
console.log('Standard deviational ellipse:', ellipse);

Spatial Pattern Analysis

Analyze point patterns for clustering, dispersion, or randomness.

/**
 * Performs quadrat analysis to determine if points are clustered, dispersed, or random.
 */
function quadratAnalysis(
  pointFeatureSet: FeatureCollection<Point>,
  options?: {
    studyBbox?: [number, number, number, number];
    confidenceLevel?: 20 | 15 | 10 | 5 | 2 | 1;
  }
): {
  criticalValue: number;
  maxAbsoluteDifference: number;
  isRandom: boolean;
  observedDistribution: number[];
};

/**
 * Calculates nearest neighbor analysis with z-score to determine clustering/dispersion.
 */
function nearestNeighborAnalysis(
  dataset: FeatureCollection<any>,
  options?: {
    studyArea?: Feature<Polygon>;
    units?: Units;
    properties?: GeoJsonProperties;
  }
): Feature<Polygon> & {
  properties: {
    nearestNeighborAnalysis: {
      units: string;
      arealUnits: string;
      observedMeanDistance: number;
      expectedMeanDistance: number;
      numberOfPoints: number;
      zScore: number;
    };
  };
};

Usage Examples:

import { quadratAnalysis, nearestNeighborAnalysis, randomPoint, polygon } from "@turf/turf";

// Generate test points
const points = randomPoint(50, { bbox: [-5, -5, 5, 5] });

// Quadrat analysis
const quadratResult = quadratAnalysis(points, {
  studyBbox: [-5, -5, 5, 5],
  confidenceLevel: 5
});

// Nearest neighbor analysis
const studyArea = polygon([[[-5, -5], [-5, 5], [5, 5], [5, -5], [-5, -5]]]);
const nnResult = nearestNeighborAnalysis(points, {
  studyArea: studyArea,
  units: 'kilometers'
});

console.log(`Quadrat analysis: ${quadratResult.isRandom ? 'Random' : 'Non-random'} pattern`);
console.log(`Critical value: ${quadratResult.criticalValue}`);
console.log(`Nearest neighbor z-score: ${nnResult.properties.nearestNeighborAnalysis.zScore}`);

Spatial Sampling and Weighting

Perform spatial sampling and calculate distance-based weights.

/**
 * Uses reservoir sampling to take a sample from a FeatureCollection.
 */
function sample<G>(
  featurecollection: FeatureCollection<G>,
  num: number
): FeatureCollection<G>;

/**
 * Calculates inverse distance weighting for a set of points.
 */
function distanceWeight(
  points: FeatureCollection<Point>,
  options?: { 
    threshold?: number;
    p?: number;
    binary?: boolean;
    alpha?: number;
    standardization?: string;
  }
): FeatureCollection<Point>;

Usage Examples:

import { sample, distanceWeight, randomPoint } from "@turf/turf";

// Generate large dataset
const allPoints = randomPoint(1000, { bbox: [-10, -10, 10, 10] });

// Take random sample
const samplePoints = sample(allPoints, 50);

// Add sample values
samplePoints.features.forEach(point => {
  point.properties.value = Math.random() * 100;
});

// Calculate distance weights
const weightedPoints = distanceWeight(samplePoints, {
  threshold: 5,
  p: 2, // inverse distance squared
  binary: false
});

console.log(`Sampled ${samplePoints.features.length} from ${allPoints.features.length} points`);
console.log('Weighted points:', weightedPoints.features[0].properties);

Install with Tessl CLI

npx tessl i tessl/npm-turf--turf

docs

advanced-analysis.md

boolean-operations.md

coordinate-operations.md

data-generation.md

data-utilities.md

geometric-operations.md

helpers.md

index.md

invariant.md

line-processing.md

measurement.md

meta.md

spatial-analysis.md

tile.json