0
# Spatial Analysis and Statistics
1
2
Advanced spatial analysis functions including clustering, interpolation, statistical analysis, and spatial autocorrelation. These functions provide sophisticated tools for analyzing spatial patterns and relationships.
3
4
## Capabilities
5
6
### Clustering Analysis
7
8
Group points based on spatial proximity and density.
9
10
```typescript { .api }
11
/**
12
* Takes a set of points and partition them into clusters using the DBSCAN algorithm.
13
*/
14
function clustersDbscan(
15
points: FeatureCollection<Point>,
16
maxDistance: number,
17
options?: { units?: Units; minPoints?: number; mutate?: boolean }
18
): FeatureCollection<Point>;
19
20
/**
21
* Takes a set of points and partition them into clusters according to KMEANS algorithm.
22
*/
23
function clustersKmeans<P>(
24
points: FeatureCollection<Point, P>,
25
options?: { numberOfClusters?: number; mutate?: boolean }
26
): FeatureCollection<Point, P>;
27
```
28
29
**Usage Examples:**
30
31
```typescript
32
import { clustersDbscan, clustersKmeans, randomPoint } from "@turf/turf";
33
34
// Generate sample data
35
const points = randomPoint(100, { bbox: [-10, -10, 10, 10] });
36
37
// DBSCAN clustering - density-based
38
const dbscanClusters = clustersDbscan(points, 2, {
39
units: 'kilometers',
40
minPoints: 3
41
});
42
43
// K-means clustering - centroid-based
44
const kmeansClusters = clustersKmeans(points, {
45
numberOfClusters: 5
46
});
47
48
// Count clusters
49
const dbscanClusterCount = new Set(
50
dbscanClusters.features.map(f => f.properties.cluster)
51
).size;
52
53
console.log(`DBSCAN found ${dbscanClusterCount} clusters`);
54
console.log(`K-means created 5 clusters`);
55
```
56
57
### Spatial Interpolation
58
59
Estimate values at unmeasured locations based on measured sample points.
60
61
```typescript { .api }
62
/**
63
* Takes a set of sample points with known values and creates a grid of interpolated values.
64
*/
65
function interpolate(
66
points: FeatureCollection<Point>,
67
cellSize: number,
68
options?: {
69
gridType?: 'point' | 'square' | 'hex' | 'triangle';
70
property?: string;
71
units?: Units;
72
weight?: number;
73
}
74
): FeatureCollection<Point>;
75
```
76
77
**Usage Examples:**
78
79
```typescript
80
import { interpolate, randomPoint } from "@turf/turf";
81
82
// Create sample points with temperature data
83
const samplePoints = randomPoint(50, { bbox: [-5, -5, 5, 5] });
84
samplePoints.features.forEach((point, i) => {
85
point.properties = { temperature: Math.random() * 30 + 10 }; // 10-40°C
86
});
87
88
// Interpolate temperature values across grid
89
const interpolatedGrid = interpolate(samplePoints, 0.5, {
90
gridType: 'square',
91
property: 'temperature',
92
units: 'kilometers',
93
weight: 1
94
});
95
96
console.log(`Interpolated ${interpolatedGrid.features.length} grid cells`);
97
console.log('Sample interpolated value:', interpolatedGrid.features[0].properties);
98
```
99
100
### Contour Analysis
101
102
Generate contour lines and filled contours from point data.
103
104
```typescript { .api }
105
/**
106
* Takes a grid FeatureCollection of Point features with z-values and an array of value breaks
107
* and generates filled contour polygons.
108
*/
109
function isobands(
110
pointGrid: FeatureCollection<Point>,
111
breaks: number[],
112
options?: {
113
zProperty?: string;
114
commonProperties?: GeoJsonProperties;
115
breaksProperties?: GeoJsonProperties[];
116
}
117
): FeatureCollection<Polygon>;
118
119
/**
120
* Takes a grid FeatureCollection of Point features with z-values and an array of value breaks
121
* and generates contour line features.
122
*/
123
function isolines(
124
pointGrid: FeatureCollection<Point>,
125
breaks: number[],
126
options?: {
127
zProperty?: string;
128
commonProperties?: GeoJsonProperties;
129
breaksProperties?: GeoJsonProperties[];
130
}
131
): FeatureCollection<LineString>;
132
```
133
134
**Usage Examples:**
135
136
```typescript
137
import { isobands, isolines, pointGrid } from "@turf/turf";
138
139
// Create elevation grid
140
const bbox = [-5, -5, 5, 5];
141
const grid = pointGrid(bbox, 0.5, { units: 'kilometers' });
142
143
// Add elevation data
144
grid.features.forEach(point => {
145
const [x, y] = point.geometry.coordinates;
146
point.properties.elevation = Math.sin(x) * Math.cos(y) * 1000 + 500;
147
});
148
149
// Define elevation breaks
150
const breaks = [0, 200, 400, 600, 800, 1000, 1200];
151
152
// Generate filled contours (isobands)
153
const contourPolygons = isobands(grid, breaks, {
154
zProperty: 'elevation',
155
commonProperties: { type: 'elevation_zone' }
156
});
157
158
// Generate contour lines (isolines)
159
const contourLines = isolines(grid, breaks, {
160
zProperty: 'elevation',
161
commonProperties: { type: 'elevation_contour' }
162
});
163
164
console.log(`Generated ${contourPolygons.features.length} contour polygons`);
165
console.log(`Generated ${contourLines.features.length} contour lines`);
166
```
167
168
### Statistical Analysis
169
170
Perform spatial statistical tests and calculations.
171
172
```typescript { .api }
173
/**
174
* Calculates Moran's I spatial autocorrelation.
175
*/
176
function moranIndex(
177
geojson: FeatureCollection<any>,
178
options?: {
179
inputField?: string;
180
threshold?: number;
181
p?: number;
182
binary?: boolean;
183
alpha?: number;
184
standardization?: string;
185
}
186
): { moranI: number; expectedI: number; varianceI: number; zNorm: number };
187
188
/**
189
* Calculates the standard deviational ellipse for a set of points,
190
* returning a feature representing the ellipse.
191
*/
192
function standardDeviationalEllipse(
193
points: FeatureCollection<Point>,
194
options?: {
195
weight?: string;
196
steps?: number;
197
properties?: GeoJsonProperties;
198
}
199
): Feature<Polygon>;
200
```
201
202
**Usage Examples:**
203
204
```typescript
205
import { moranIndex, standardDeviationalEllipse, randomPoint } from "@turf/turf";
206
207
// Generate clustered points
208
const points = randomPoint(100, { bbox: [-10, -10, 10, 10] });
209
210
// Add correlated values
211
points.features.forEach(point => {
212
const [x, y] = point.geometry.coordinates;
213
point.properties.value = x * y + Math.random() * 10;
214
});
215
216
// Calculate Moran's I for spatial autocorrelation
217
const moran = moranIndex(points, {
218
inputField: 'value',
219
threshold: 5,
220
binary: false
221
});
222
223
// Calculate standard deviational ellipse
224
const ellipse = standardDeviationalEllipse(points, {
225
steps: 64,
226
properties: { analysis: 'std_ellipse' }
227
});
228
229
console.log(`Moran's I: ${moran.moranI} (expected: ${moran.expectedI})`);
230
console.log(`Z-score: ${moran.zNorm}`);
231
console.log('Standard deviational ellipse:', ellipse);
232
```
233
234
### Spatial Pattern Analysis
235
236
Analyze point patterns for clustering, dispersion, or randomness.
237
238
```typescript { .api }
239
/**
240
* Performs quadrat analysis to determine if points are clustered, dispersed, or random.
241
*/
242
function quadratAnalysis(
243
pointFeatureSet: FeatureCollection<Point>,
244
options?: {
245
studyBbox?: [number, number, number, number];
246
confidenceLevel?: 20 | 15 | 10 | 5 | 2 | 1;
247
}
248
): {
249
criticalValue: number;
250
maxAbsoluteDifference: number;
251
isRandom: boolean;
252
observedDistribution: number[];
253
};
254
255
/**
256
* Calculates nearest neighbor analysis with z-score to determine clustering/dispersion.
257
*/
258
function nearestNeighborAnalysis(
259
dataset: FeatureCollection<any>,
260
options?: {
261
studyArea?: Feature<Polygon>;
262
units?: Units;
263
properties?: GeoJsonProperties;
264
}
265
): Feature<Polygon> & {
266
properties: {
267
nearestNeighborAnalysis: {
268
units: string;
269
arealUnits: string;
270
observedMeanDistance: number;
271
expectedMeanDistance: number;
272
numberOfPoints: number;
273
zScore: number;
274
};
275
};
276
};
277
```
278
279
**Usage Examples:**
280
281
```typescript
282
import { quadratAnalysis, nearestNeighborAnalysis, randomPoint, polygon } from "@turf/turf";
283
284
// Generate test points
285
const points = randomPoint(50, { bbox: [-5, -5, 5, 5] });
286
287
// Quadrat analysis
288
const quadratResult = quadratAnalysis(points, {
289
studyBbox: [-5, -5, 5, 5],
290
confidenceLevel: 5
291
});
292
293
// Nearest neighbor analysis
294
const studyArea = polygon([[[-5, -5], [-5, 5], [5, 5], [5, -5], [-5, -5]]]);
295
const nnResult = nearestNeighborAnalysis(points, {
296
studyArea: studyArea,
297
units: 'kilometers'
298
});
299
300
console.log(`Quadrat analysis: ${quadratResult.isRandom ? 'Random' : 'Non-random'} pattern`);
301
console.log(`Critical value: ${quadratResult.criticalValue}`);
302
console.log(`Nearest neighbor z-score: ${nnResult.properties.nearestNeighborAnalysis.zScore}`);
303
```
304
305
### Spatial Sampling and Weighting
306
307
Perform spatial sampling and calculate distance-based weights.
308
309
```typescript { .api }
310
/**
311
* Uses reservoir sampling to take a sample from a FeatureCollection.
312
*/
313
function sample<G>(
314
featurecollection: FeatureCollection<G>,
315
num: number
316
): FeatureCollection<G>;
317
318
/**
319
* Calculates inverse distance weighting for a set of points.
320
*/
321
function distanceWeight(
322
points: FeatureCollection<Point>,
323
options?: {
324
threshold?: number;
325
p?: number;
326
binary?: boolean;
327
alpha?: number;
328
standardization?: string;
329
}
330
): FeatureCollection<Point>;
331
```
332
333
**Usage Examples:**
334
335
```typescript
336
import { sample, distanceWeight, randomPoint } from "@turf/turf";
337
338
// Generate large dataset
339
const allPoints = randomPoint(1000, { bbox: [-10, -10, 10, 10] });
340
341
// Take random sample
342
const samplePoints = sample(allPoints, 50);
343
344
// Add sample values
345
samplePoints.features.forEach(point => {
346
point.properties.value = Math.random() * 100;
347
});
348
349
// Calculate distance weights
350
const weightedPoints = distanceWeight(samplePoints, {
351
threshold: 5,
352
p: 2, // inverse distance squared
353
binary: false
354
});
355
356
console.log(`Sampled ${samplePoints.features.length} from ${allPoints.features.length} points`);
357
console.log('Weighted points:', weightedPoints.features[0].properties);
358
```