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 @turf-isobands module with MarchingSquares #619

Merged
merged 31 commits into from
May 9, 2017
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
dcb39ca
added isobands module
stebogit Jan 29, 2017
fa32920
updated to latest version of @turf and MarchingSquaresJS
stebogit Jan 29, 2017
def67a5
integrated module.export to MS-isobands, added sandbox
stebogit Feb 28, 2017
c42f537
updated marchingsquare library
stebogit Mar 15, 2017
3341cd4
removed sandbox
stebogit Mar 15, 2017
2093242
modified version and license
stebogit Mar 15, 2017
7a40684
made suggested corrections
stebogit Mar 16, 2017
c96d13e
replaced minified marchingsquare
stebogit Mar 16, 2017
bdbb1a8
Refactoring turf-isobands
DenisCarriere Mar 16, 2017
fb6cce8
Merge branch 'master' into isobands
DenisCarriere Mar 16, 2017
6017a04
Merge branch 'master' into isobands
DenisCarriere Mar 16, 2017
3f13aa4
Add z coordinate fixture
DenisCarriere Mar 19, 2017
49cc2e8
Merge branch 'isobands' of https://github.com/stebogit/turf into isob…
DenisCarriere Mar 19, 2017
bac2c75
Separate isobands into methods
DenisCarriere Mar 19, 2017
950d14c
Add isolines test fixture
DenisCarriere Mar 19, 2017
fc7591e
added methods to accept random points as input
stebogit Mar 27, 2017
b80512d
corrected linting issues
stebogit Mar 27, 2017
b0fa745
corrected linting issues
stebogit Mar 27, 2017
6cfae0c
rinamed function dividePointsByLatitude
stebogit Apr 7, 2017
440bae6
Merge branch 'master' into isobands
stebogit Apr 7, 2017
2933158
Update test/out fixtures
DenisCarriere Apr 16, 2017
6650f73
Merge remote-tracking branch 'upstream/master' into isobands
stebogit Apr 18, 2017
a0b7c78
Merge remote-tracking branch 'upstream/master' into isobands
stebogit Apr 22, 2017
6998178
reordered methods
stebogit Apr 22, 2017
0030a2b
- removed random points tests;
stebogit Apr 24, 2017
0b63cd7
Merge remote-tracking branch 'upstream/master' into isobands
stebogit Apr 25, 2017
e9fb0a8
adds matrix outer frame;
stebogit Apr 25, 2017
b1127ec
simplified code
stebogit Apr 27, 2017
42469e9
Merge remote-tracking branch 'upstream/master' into isobands
stebogit May 1, 2017
0b36635
set matrix json as valid test input
stebogit May 1, 2017
2ea0902
fixed output;
stebogit May 8, 2017
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
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ test.js
bench.js
packages/turf/turf.js
packages/turf/turf.min.js
marchingsquares-isobands.js
rollup.config.js
simplepolygon.js
21 changes: 21 additions & 0 deletions packages/turf-isobands/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 turf

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-isobands/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# turf-isobands

# isobands

Takes a grid ([FeatureCollection](http://geojson.org/geojson-spec.html#feature-collection-objects)) of [Point](http://geojson.org/geojson-spec.html#point) features with z-values and an array of
value breaks and generates filled contour isobands.

**Parameters**

- `pointGrid` **[FeatureCollection](http://geojson.org/geojson-spec.html#feature-collection-objects)<[Point](http://geojson.org/geojson-spec.html#point)>** a FeatureCollection of [Point](http://geojson.org/geojson-spec.html#point) features
- `z` **[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
- `breaks` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)>** where to draw contours

**Examples**

```javascript
// create random points with random
// z-values in their properties
var extent = [-70.823364, -33.553984, -69.823364, -32.553984];
var cellWidth = 5;
var units = 'miles';
var pointGrid = turf.pointGrid(extent, cellWidth, units);
for (var i = 0; i < pointGrid.features.length; i++) {
pointGrid.features[i].properties.elevation = Math.random() * 10;
}
var breaks = [0, 5, 8.5];
var isobands = turf.isobands(pointGrid, 'z', breaks);
//=isobands
```

Returns **[FeatureCollection](http://geojson.org/geojson-spec.html#feature-collection-objects)&lt;[MultiPolygon](http://geojson.org/geojson-spec.html#multipolygon)>** a FeatureCollection of [MultiPolygon](http://geojson.org/geojson-spec.html#multipolygon) features representing isobands

<!-- 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-isobands
```

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

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

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

/**
* Benchmark Results
*
* points1 x 2,301 ops/sec ±15.73% (77 runs sampled)
*/
const suite = new Benchmark.Suite('turf-isobands');
for (const {name, geojson} of fixtures) {
isobands(geojson, 'elevation', [5, 45, 55, 65, 85, 95, 105, 120, 180]);
suite.add(name, () => isobands(geojson, 'elevation', [5, 45, 55, 65, 85, 95, 105, 120, 180]));
}
suite
.on('cycle', e => console.log(String(e.target)))
.on('complete', () => {})
.run();
8 changes: 8 additions & 0 deletions packages/turf-isobands/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import {Points, MultiPolygons} from '@turf/helpers'

/**
* http://turfjs.org/docs/#isobands
*/
declare function isobands(pointGrid: Points, z: string, breaks: Array<number>): MultiPolygons;
declare namespace isobands { }
export = isobands;
267 changes: 267 additions & 0 deletions packages/turf-isobands/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
// https://github.com/RaumZeit/MarchingSquares.js
var MarchingSquaresJS = require('./marchingsquares-isobands');
var helpers = require('@turf/helpers');
var featureCollection = helpers.featureCollection;
var polygon = helpers.polygon;
var multiPolygon = helpers.multiPolygon;
var explode = require('@turf/explode');
var inside = require('@turf/inside');
var area = require('@turf/area');

/**
* Takes a grid ({@link FeatureCollection}) of {@link Point} features with z-values and an array of
* value breaks and generates filled contour isobands.
*
*
* @name isobands
* @param {FeatureCollection<Point>} pointGrid a FeatureCollection of {@link Point} features
* @param {string} z the property name in `points` from which z-values will be pulled
* @param {Array<number>} breaks where to draw contours
* @returns {FeatureCollection<MultiPolygon>} a FeatureCollection of {@link MultiPolygon} features representing isobands
* @example
* // create random points with random
Copy link
Member

Choose a reason for hiding this comment

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

Explicitly define your examples since the JSDocs @example is actually being tested and will throw an error in the turf-www build.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Could you please elaborate a bit on this? First time I see this feature 😄
What is missing? I just copied the JSDoc from the original version of the module

* // z-values in their properties
* var extent = [-70.823364, -33.553984, -69.823364, -32.553984];
* var cellWidth = 5;
* var units = 'miles';
* var pointGrid = turf.pointGrid(extent, cellWidth, units);
* for (var i = 0; i < pointGrid.features.length; i++) {
* pointGrid.features[i].properties.elevation = Math.random() * 10;
* }
* var breaks = [0, 5, 8.5];
* var isobands = turf.isobands(pointGrid, 'z', breaks);
* //=isobands
*/
module.exports = function (pointGrid, z, breaks) {

var points = pointGrid.features;

/*####################################
divide points in pointGrid by latitude, creating a 2-dimensional data grid
####################################*/
var pointsByLatitude = {};
for (var j = 0; j < points.length; j++) {
Copy link
Member

Choose a reason for hiding this comment

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

Try using one of the @turf/meta functions, coordEach() or featureEach()

if (!pointsByLatitude[getLatitude(points[j])]) {
pointsByLatitude[getLatitude(points[j])] = [];
}
// group obj by Lat value
pointsByLatitude[getLatitude(points[j])].push(points[j]);
}
// create an array of arrays of points, each array representing a row (i.e. Latitude) of the 2D grid
pointsByLatitude = Object.keys(pointsByLatitude).map(function (key) {
return pointsByLatitude[key];
});

/*
* pointsByLatitude is a matrix of points on the map; NOTE the position of the ORIGIN for MarchingSquaresJS
*
* pointsByLatitude = [
* [ {point}, {point}, {point}, ... {point} ],
* [ {point}, {point}, {point}, ... {point} ],
* ...
* [ {ORIGIN}, {point}, {point}, ... {point} ]
* ]
*
**/

// creates a 2D grid with the z-value of all point on the map
var gridData = [];
pointsByLatitude.forEach(function (pointArr) {
var row = [];
pointArr.forEach(function (point) {
row.push(point.properties[z]);
});
gridData.push(row);
});

/* example
* gridData = [
* [ 1, 13, 10, 9, 10, 13, 18],
* [34, 8, 5, 4, 5, 8, 13],
* [10, 5, 2, 1, 2, 5, 4],
* [ 0, 4, 56, 19, 1, 4, 9],
* [10, 5, 2, 1, 2, 5, 10],
* [57, 8, 5, 4, 5, 25, 57],
* [ 3, 13, 10, 9, 5, 13, 18],
* [18, 13, 10, 9, 78, 13, 18]
* ]
*/


/*####################################
getting references of the original grid of points (on the map)
####################################*/
var lastC = pointsByLatitude[0].length - 1; // last colum of the data grid
// get the distance (on the map) between the first and the last point on a row of the grid
var originalWidth = getLongitude(pointsByLatitude[0][lastC]) - getLongitude(pointsByLatitude[0][0]);
var lastR = pointsByLatitude.length - 1; // last row of the data grid
// get the distance (on the map) between the first and the last point on a column of the grid
var originalHeigth = getLatitude(pointsByLatitude[lastR][0]) - getLatitude(pointsByLatitude[0][0]);

// get origin, which is the first point of the last row on the rectangular data on the map
var x0 = getLongitude(pointsByLatitude[0][0]);
var y0 = getLatitude(pointsByLatitude[0][0]);
// get pointGrid dimensions
var gridWidth = gridData[0].length;
var gridHeigth = gridData.length;
// calculate the scaling factor between the unitary grid to the rectangle on the map
var scaleX = originalWidth / gridWidth;
var scaleY = originalHeigth / gridHeigth;

var rescale = function (point) {
point[0] = point[0] * scaleX + x0; // rescaled x
point[1] = point[1] * scaleY + y0; // rescaled y
};


/*####################################
creates the contours lines (featuresCollection of polygon features) from the 2D data grid

MarchingSquaresJS process the grid data as a 3D representation of a function on a 2D plane, therefore it
assumes the points (x-y coordinates) are one 'unit' distance. The result of the IsoBands function needs to be
rescaled, with turfjs, to the original area and proportions on the google map
####################################*/

// based on the provided breaks
var contours = [];
for (var i = 1; i < breaks.length; i++) {
var lowerBand = +breaks[i - 1]; // make sure the breaks value is a number
var upperBand = +breaks[i];
/*eslint-disable*/
var isobands = MarchingSquaresJS.IsoBands(gridData, lowerBand, upperBand - lowerBand);
/*eslint-enable*/
// as per GeoJson rules for creating a polygon, make sure the first element
// in the array of linearRings represents the exterior ring (i.e. biggest area),
// and any subsequent elements represent interior rings (i.e. smaller area);
// this avoids rendering issues of the multipolygons on the map
var nestedRings = orderByArea(isobands);
var contourSet = groupNestedRings(nestedRings);
var obj = {};
obj['contourSet'] = contourSet;
obj[z] = +breaks[i]; // make sure it's a number
contours.push(obj);

}

/*####################################
transform isobands of 2D grid to polygons for the map
####################################*/
// rescale and shift each point/line of the isobands
contours.forEach(function (contour) {
contour.contourSet.forEach(function (lineRingSet) {
lineRingSet.forEach(function (lineRing) {
lineRing.forEach(rescale);
});
});
});

// creates GEOJson MultiPolygons from the contours
var multipolygons = contours.map(function (contour) {
var obj = {};
obj[z] = contour[z];
return multiPolygon(contour.contourSet, obj);

});

// return a GEOJson FeatureCollection of MultiPolygons
return featureCollection(multipolygons);

};

/**********************************************
* utility functions
*********************************************/

// returns an array of coordinates (of LinearRings) in descending order by area
function orderByArea(linearRings) {
var linearRingsWithArea = [];
var areas = [];
linearRings.forEach(function (points) {
var poly = polygon([points]);
var calculatedArea = area(poly);
// create an array of areas value
areas.push(calculatedArea);
// associate each lineRing with its area
linearRingsWithArea.push({lineRing: points, area: calculatedArea});
});
areas.sort(function (a, b) { // bigger --> smaller
return b - a;
});
// create a new array of linearRings ordered by their area
var orderedByArea = [];
for (var i = 0; i < areas.length; i++) {
for (var lr = 0; lr < linearRingsWithArea.length; lr++) {
if (linearRingsWithArea[lr].area === areas[i]) {
orderedByArea.push(linearRingsWithArea[lr].lineRing);
linearRingsWithArea.splice(lr, 1);
break;
}
}
}
return orderedByArea;
}

// returns an array of arrays of coordinates, each representing
// a set of (coordinates of) nested LinearRings,
// i.e. the first ring contains all the others
// it expects an array of coordinates (of LinearRings) in descending order by area
function groupNestedRings(orderedLinearRings) {
// create a list of the (coordinates of) LinearRings
var lrList = orderedLinearRings.map(function (lr) {
return {lrCoordinates: lr, grouped: false};
});
var groupedLinearRings = [];
while (!allGrouped(lrList)) {
for (var i = 0; i < lrList.length; i++) {
if (!lrList[i].grouped) {
// create new group starting with the larger not already grouped ring
var group = [];
group.push(lrList[i].lrCoordinates);
lrList[i].grouped = true;
var outerMostPoly = polygon([lrList[i].lrCoordinates]);
// group all the rings contained by the outermost ring
for (var j = i + 1; j < lrList.length; j++) {
if (!lrList[j].grouped) {
var lrPoly = polygon([lrList[j].lrCoordinates]);
if (isInside(lrPoly, outerMostPoly)) {
group.push(lrList[j].lrCoordinates);
lrList[j].grouped = true;
}
}
}
// insert the new group
groupedLinearRings.push(group);
}
}
}
return groupedLinearRings;
}

// returns if test-Polygon is inside target-Polygon
function isInside(testPolygon, targetPolygon) {
var points = explode(testPolygon);
for (var i = 0; i < points.features.length; i++) {
if (!inside(points.features[i], targetPolygon)) {
return false;
}
}
return true;
}

// returns if all the LinearRings are marked as grouped
function allGrouped(list) {
for (var i = 0; i < list.length; i++) {
if (list[i].grouped === false) {
return false;
}
}
return true;
}

function getLatitude(point) {
return point.geometry.coordinates[1];
}

function getLongitude(point) {
return point.geometry.coordinates[0];
}
Loading