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 9 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
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.
56 changes: 56 additions & 0 deletions packages/turf-interpolate/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# @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
- `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 (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 = interpolate(points, 100, '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)>** grid of points with '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
```
37 changes: 37 additions & 0 deletions packages/turf-interpolate/bench.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
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
*
* points-random: 18.246ms
* points1: 12.013ms
* points-random x 607 ops/sec ±2.56% (76 runs sampled)
* points1 x 533 ops/sec ±2.13% (78 runs sampled)
*/
const suite = new Benchmark.Suite('turf-interpolate');
for (const {name, geojson} of fixtures) {
const {property, cellSize, units, weight} = geojson.properties;

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

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

import {Units, Points} from '@turf/helpers';

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

declare namespace interpolate { }
export = interpolate;
64 changes: 64 additions & 0 deletions packages/turf-interpolate/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
var meta = require('@turf/meta');
var bbox = require('@turf/bbox');
var poinGrid = require('@turf/point-grid');
var distance = require('@turf/distance');
var invariant = require('@turf/invariant');
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} [property='elevation'] the property name in `points` from which z-values will be pulled
* @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>} grid of points with '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 = interpolate(points, 100, 'solRad', 'miles');
*
* //addToMap
* var addToMap = grid
*/
module.exports = function (points, cellSize, 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';
weight = weight || 1;

// create the point grid
var grid = poinGrid(bbox(points), cellSize, units, true);

featureEach(grid, function (gridPoint) {
var zw = 0;
var sw = 0;
// calculate the distance from each input point to the grid points
featureEach(points, function (point) {
var d = distance(gridPoint, point, units);
var zValue = point.properties[property];
if (zValue === undefined) throw new Error('Specified property 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
gridPoint.properties[property] = zw / sw;
});

return grid;
};
49 changes: 49 additions & 0 deletions packages/turf-interpolate/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{
"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/meta": "^4.5.2",
"@turf/point-grid": "^4.5.2"
}
}
82 changes: 82 additions & 0 deletions packages/turf-interpolate/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
const fs = require('fs');
const test = require('tape');
const path = require('path');
const load = require('load-json-file');
const write = require('write-json-file');
const {round, featureCollection, point} = require('@turf/helpers');
const truncate = require('@turf/truncate');
const chromatism = require('chromatism');
const {featureEach, propEach} = require('@turf/meta');
const interpolate = require('./');

const directories = {
in: path.join(__dirname, 'test', 'in') + path.sep,
out: path.join(__dirname, 'test', 'out') + path.sep
};

const fixtures = fs.readdirSync(directories.in).map(filename => {
return {
filename,
name: path.parse(filename).name,
geojson: load.sync(directories.in + filename)
};
});

test('turf-interpolate', t => {
for (const {filename, name, geojson} of fixtures) {
let {property, cellSize, units, weight} = geojson.properties;
property = property || 'elevation';

// Truncate coordinates & elevation (property) to 6 precision
let grid = truncate(interpolate(geojson, cellSize, property, units, weight));
propEach(grid, props => { props[property] = round(props[property]); });
const result = colorize(grid, property);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added @turf/truncate to results (reduce coordinates to 6 decimals).

Node 7 & 8 were passing, but Node 6 was failing (0.0000001 of a difference).


if (process.env.REGEN) write.sync(directories.out + filename, result);
t.deepEquals(result, load.sync(directories.out + filename), name);
}
t.end();
});



test('turf-interpolate -- throws errors', t => {
const cellSize = 1;
const property = 'pressure';
const weight = 0.5;
const units = 'miles';
const points = featureCollection([
point([1, 2], {pressure: 2}),
point([2, 1], {pressure: 3}),
point([1.5, 1.5], {pressure: 4})
]);
interpolate(points, cellSize, property, units, weight);
t.throws(() => interpolate(points, undefined, property, units, weight), /cellSize is required/);
t.throws(() => interpolate(undefined, cellSize, property, units, weight), /points is required/);
t.throws(() => interpolate(points, cellSize, property, 'foo', weight), 'invalid units');
t.throws(() => interpolate(points, cellSize, property, units, 'foo'), /weight must be a number/);
t.end();
});


// style result
function colorize(grid, property) {
property = property || 'elevation';
let max = -Infinity;
let min = Infinity;
featureEach(grid, function (point) {
const value = point.properties[property];
if (value > max) max = value;
if (value < min) min = value;
});
const delta = (max - min) * 1.1; // extend range to enhance color shade

featureEach(grid, function (point) {
const value = point.properties[property];
const percent = round((value - min) / delta * 100);
const color = chromatism.brightness(percent, '#002c56').hex;
point.properties['marker-color'] = color;
});

return grid;
}
Loading