Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New module @turf/interpolate (proposal) #832

Merged
merged 19 commits into from
Jul 11, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
"progress": "^2.0.0",
"tap": "^10.3.2",
"tape": "^4.6.3",
"typescript": "^2.2.1",
"typescript": "^2.4.1",
"uglify-js": "~2.4.16"
}
}
6 changes: 4 additions & 2 deletions packages/turf-clone/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

# clone

Returns a cloned copy of the passed Object. By default it duplicates only the [standard GeoJSON fields](https://tools.ietf.org/html/rfc7946#section-3) of the object; if `cloneAll` is set to `true` all fields of the Object, thus including ['Foreign Members'](https://tools.ietf.org/html/rfc7946#section-6), will be cloned (3-20x slower).
Returns a cloned copy of the passed GeoJSON Object.
By default it duplicates only the standard GeoJSON fields of the object; if `cloneAll` is set to `true` all
fields of the Object, thus including 'Foreign Members', will be cloned (3-20x slower).

**Parameters**

- `geojson` **[GeoJSON](http://geojson.org/geojson-spec.html#geojson-objects)** GeoJSON Object
- `cloneAll` **\[[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)]** clones entire GeoJSON object (optional, default `false`)
- `cloneAll` **\[[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)]** clones entire GeoJSON object, using JSON.parse(JSON.stringify(geojson)) (optional, default `false`)

**Examples**

Expand Down
20 changes: 20 additions & 0 deletions packages/turf-interpolate/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2017 TurfJS

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
57 changes: 57 additions & 0 deletions packages/turf-interpolate/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# @turf/interpolate

# interpolate

Takes a set of points and estimates their 'property' values on a grid using the Inverse Distance Weighting (IDW) method.](<https://en.wikipedia.org/wiki/Inverse_distance_weighting>.

**Parameters**

- `points` **[FeatureCollection](http://geojson.org/geojson-spec.html#feature-collection-objects)&lt;[Point](http://geojson.org/geojson-spec.html#point)>** with known value
- `cellSize` **[number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)** the distance across each grid point
- `gridType` **\[[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)]** defines if the output will be a `squareGrid` (`outputType`='squares'), a `pointGrid` (`outputType`='points'), a `haxGrid` (`outputType`='hex') or a `triangleGrid` (`outputType`='triangle').
- `property` **\[[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)]** the property name in `points` from which z-values will be pulled, zValue fallbacks to 3rd coordinate if no property exists. (optional, default `'elevation'`)
- `units` **\[[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)]** used in calculating cellSize, can be degrees, radians, miles, or kilometers (optional, default `kilometers`)
- `weight` **\[[number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)]** exponent regulating the distance-decay weighting (optional, default `1`)

**Examples**

```javascript
var points = turf.random('points', 30, {
bbox: [50, 30, 70, 50]
});
// add a random property to each point
turf.featureEach(points, function(point) {
point.properties.solRad = Math.random() * 50;
});
var grid = turf.interpolate(points, 100, 'points', 'solRad', 'miles');

//addToMap
var addToMap = grid
```

Returns **[FeatureCollection](http://geojson.org/geojson-spec.html#feature-collection-objects)&lt;[Point](http://geojson.org/geojson-spec.html#point)|[Polygon](http://geojson.org/geojson-spec.html#polygon)>** grid of points or polygons with interpolated 'property'

<!-- This file is automatically generated. Please don't edit it directly:
if you find an error, edit the source file (likely index.js), and re-run
./scripts/generate-readmes in the turf project. -->

---

This module is part of the [Turfjs project](http://turfjs.org/), an open source
module collection dedicated to geographic algorithms. It is maintained in the
[Turfjs/turf](https://github.com/Turfjs/turf) repository, where you can create
PRs and issues.

### Installation

Install this module individually:

```sh
$ npm install @turf/interpolate
```

Or install the Turf module that includes it as a function:

```sh
$ npm install @turf/turf
```
49 changes: 49 additions & 0 deletions packages/turf-interpolate/bench.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const Benchmark = require('benchmark');
const path = require('path');
const fs = require('fs');
const load = require('load-json-file');
const interpolate = require('./');

// Define Fixtures
const directory = path.join(__dirname, 'test', 'in') + path.sep;
const fixtures = fs.readdirSync(directory).map(filename => {
return {
name: path.parse(filename).name,
geojson: load.sync(directory + filename)
};
});

/**
* Benchmark Results
*
* data-1km: 15.042ms
* data-500m: 14.286ms
* data-weight-2: 0.408ms
* hex-zValue: 1.778ms
* points-random: 20.676ms
* points1-weight-3: 5.569ms
* points1: 4.254ms
* triangle-zValue: 3.519ms
* data-1km x 1,585 ops/sec ±2.77% (80 runs sampled)
* data-500m x 351 ops/sec ±2.59% (76 runs sampled)
* data-weight-2 x 3,730 ops/sec ±1.55% (82 runs sampled)
* hex-zValue x 2,854 ops/sec ±4.45% (72 runs sampled)
* points-random x 265 ops/sec ±1.67% (75 runs sampled)
* points1-weight-3 x 381 ops/sec ±2.06% (76 runs sampled)
* points1 x 356 ops/sec ±1.83% (70 runs sampled)
* triangle-zValue x 570 ops/sec ±1.69% (81 runs sampled)
*/
const suite = new Benchmark.Suite('turf-interpolate');
for (const {name, geojson} of fixtures) {
const {property, cellSize, outputType, units, weight} = geojson.properties;

console.time(name);
interpolate(geojson, cellSize, outputType, property, units, weight);
console.timeEnd(name);
suite.add(name, () => interpolate(geojson, cellSize, outputType, property, units, weight));
}

suite
.on('cycle', e => console.log(String(e.target)))
.on('complete', () => {})
.run();
21 changes: 21 additions & 0 deletions packages/turf-interpolate/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/// <reference types="geojson" />

import * as helpers from '@turf/helpers';

/**
* http://turfjs.org/docs/#interpolate
*/
declare function interpolate(
points: interpolate.Points,
cellSize: number,
outputType: interpolate.OutputTypes,
property?: string,
units?: interpolate.Units,
weight?: number): interpolate.Points;

declare namespace interpolate {
type OutputTypes = 'point' | 'square' | 'hex' | 'triangle';
type Points = helpers.Points;
type Units = helpers.Units;
}
export = interpolate;
90 changes: 90 additions & 0 deletions packages/turf-interpolate/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
var meta = require('@turf/meta');
var bbox = require('@turf/bbox');
var hexGrid = require('@turf/hex-grid');
var poinGrid = require('@turf/point-grid');
var distance = require('@turf/distance');
var centroid = require('@turf/centroid');
var invariant = require('@turf/invariant');
var squareGrid = require('@turf/square-grid');
var triangleGrid = require('@turf/triangle-grid');
var featureEach = meta.featureEach;
var collectionOf = invariant.collectionOf;

/**
* Takes a set of points and estimates their 'property' values on a grid using the [Inverse Distance Weighting (IDW) method](https://en.wikipedia.org/wiki/Inverse_distance_weighting).
*
* @name interpolate
* @param {FeatureCollection<Point>} points with known value
* @param {number} cellSize the distance across each grid point
* @param {string} [gridType='square'] defines the output format based on a Grid Type (options: 'square' | 'point' | 'hex' | 'triangle')
* @param {string} [property='elevation'] the property name in `points` from which z-values will be pulled, zValue fallbacks to 3rd coordinate if no property exists.
* @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers
* @param {number} [weight=1] exponent regulating the distance-decay weighting
* @returns {FeatureCollection<Point|Polygon>} grid of points or polygons with interpolated 'property'
* @example
* var points = turf.random('points', 30, {
* bbox: [50, 30, 70, 50]
* });
* // add a random property to each point
* turf.featureEach(points, function(point) {
* point.properties.solRad = Math.random() * 50;
* });
* var grid = turf.interpolate(points, 100, 'points', 'solRad', 'miles');
*
* //addToMap
* var addToMap = grid
*/
module.exports = function (points, cellSize, gridType, property, units, weight) {
// validation
if (!points) throw new Error('points is required');
collectionOf(points, 'Point', 'input must contain Points');
if (!cellSize) throw new Error('cellSize is required');
if (weight !== undefined && typeof weight !== 'number') throw new Error('weight must be a number');

// default values
property = property || 'elevation';
gridType = gridType || 'square';
weight = weight || 1;

var box = bbox(points);
var grid;
switch (gridType) {
case 'point':
grid = poinGrid(box, cellSize, units, true);
break;
case 'square':
grid = squareGrid(box, cellSize, units);
break;
case 'hex':
grid = hexGrid(box, cellSize, units);
break;
case 'triangle':
grid = triangleGrid(box, cellSize, units);
break;
default:
throw new Error('invalid gridType');
}

featureEach(grid, function (gridFeature) {
var zw = 0;
var sw = 0;
// calculate the distance from each input point to the grid points
featureEach(points, function (point) {
var gridPoint = (gridType === 'point') ? gridFeature : centroid(gridFeature);
var d = distance(gridPoint, point, units);
var zValue;
// property has priority for zValue, fallbacks to 3rd coordinate from geometry
if (property !== undefined) zValue = point.properties[property];
if (zValue === undefined) zValue = point.geometry.coordinates[2];
if (zValue === undefined) throw new Error('zValue is missing');
if (d === 0) zw = zValue;
var w = 1.0 / Math.pow(d, weight);
sw += w;
zw += w * zValue;
});
// write interpolated value for each grid point
gridFeature.properties[property] = zw / sw;
});

return grid;
};
53 changes: 53 additions & 0 deletions packages/turf-interpolate/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"name": "@turf/interpolate",
"version": "4.5.0",
"description": "turf interpolate module",
"main": "index.js",
"types": "index.d.ts",
"files": [
"index.js",
"index.d.ts"
],
"scripts": {
"test": "node test.js",
"bench": "node bench.js"
},
"repository": {
"type": "git",
"url": "git://github.com/Turfjs/turf.git"
},
"keywords": [
"turf",
"idw",
"interpolate"
],
"author": "Turf Authors",
"contributors": [
"Stefano Borghi <@stebogit>"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/Turfjs/turf/issues"
},
"homepage": "https://github.com/Turfjs/turf",
"devDependencies": {
"@turf/truncate": "^4.5.2",
"benchmark": "^2.1.4",
"chromatism": "2.6.0",
"load-json-file": "^2.0.0",
"tape": "^4.6.3",
"write-json-file": "^2.0.0"
},
"dependencies": {
"@turf/bbox": "^4.5.2",
"@turf/distance": "^4.5.2",
"@turf/helpers": "^4.5.2",
"@turf/invariant": "^4.5.2",
"@turf/centroid": "^4.5.2",
"@turf/square-grid": "^4.5.2",
"@turf/triangle-grid": "^4.5.2",
"@turf/hex-grid": "^4.5.2",
"@turf/meta": "^4.5.2",
"@turf/point-grid": "^4.5.2"
}
}
Loading