@turf/isolines 7.0.0-alpha.2 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/es/index.js DELETED
@@ -1,119 +0,0 @@
1
- import bbox from "@turf/bbox";
2
- import { coordEach } from "@turf/meta";
3
- import { collectionOf } from "@turf/invariant";
4
- import { multiLineString, featureCollection, isObject } from "@turf/helpers";
5
- import isoContours from "./lib/marchingsquares-isocontours.js";
6
- import gridToMatrix from "./lib/grid-to-matrix.js";
7
- /**
8
- * Takes a grid {@link FeatureCollection} of {@link Point} features with z-values and an array of
9
- * value breaks and generates [isolines](https://en.wikipedia.org/wiki/Contour_line).
10
- *
11
- * @name isolines
12
- * @param {FeatureCollection<Point>} pointGrid input points
13
- * @param {Array<number>} breaks values of `zProperty` where to draw isolines
14
- * @param {Object} [options={}] Optional parameters
15
- * @param {string} [options.zProperty='elevation'] the property name in `points` from which z-values will be pulled
16
- * @param {Object} [options.commonProperties={}] GeoJSON properties passed to ALL isolines
17
- * @param {Array<Object>} [options.breaksProperties=[]] GeoJSON properties passed, in order, to the correspondent isoline;
18
- * the breaks array will define the order in which the isolines are created
19
- * @returns {FeatureCollection<MultiLineString>} a FeatureCollection of {@link MultiLineString} features representing isolines
20
- * @example
21
- * // create a grid of points with random z-values in their properties
22
- * var extent = [0, 30, 20, 50];
23
- * var cellWidth = 100;
24
- * var pointGrid = turf.pointGrid(extent, cellWidth, {units: 'miles'});
25
- *
26
- * for (var i = 0; i < pointGrid.features.length; i++) {
27
- * pointGrid.features[i].properties.temperature = Math.random() * 10;
28
- * }
29
- * var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
30
- *
31
- * var lines = turf.isolines(pointGrid, breaks, {zProperty: 'temperature'});
32
- *
33
- * //addToMap
34
- * var addToMap = [lines];
35
- */
36
- function isolines(pointGrid, breaks, options) {
37
- // Optional parameters
38
- options = options || {};
39
- if (!isObject(options))
40
- throw new Error("options is invalid");
41
- const zProperty = options.zProperty || "elevation";
42
- const commonProperties = options.commonProperties || {};
43
- const breaksProperties = options.breaksProperties || [];
44
- // Input validation
45
- collectionOf(pointGrid, "Point", "Input must contain Points");
46
- if (!breaks)
47
- throw new Error("breaks is required");
48
- if (!Array.isArray(breaks))
49
- throw new Error("breaks must be an Array");
50
- if (!isObject(commonProperties))
51
- throw new Error("commonProperties must be an Object");
52
- if (!Array.isArray(breaksProperties))
53
- throw new Error("breaksProperties must be an Array");
54
- // Isoline methods
55
- const matrix = gridToMatrix(pointGrid, { zProperty: zProperty, flip: true });
56
- const createdIsoLines = createIsoLines(matrix, breaks, zProperty, commonProperties, breaksProperties);
57
- const scaledIsolines = rescaleIsolines(createdIsoLines, matrix, pointGrid);
58
- return featureCollection(scaledIsolines);
59
- }
60
- /**
61
- * Creates the isolines lines (featuresCollection of MultiLineString features) from the 2D data grid
62
- *
63
- * Marchingsquares process the grid data as a 3D representation of a function on a 2D plane, therefore it
64
- * assumes the points (x-y coordinates) are one 'unit' distance. The result of the isolines function needs to be
65
- * rescaled, with turfjs, to the original area and proportions on the map
66
- *
67
- * @private
68
- * @param {Array<Array<number>>} matrix Grid Data
69
- * @param {Array<number>} breaks BreakProps
70
- * @param {string} zProperty name of the z-values property
71
- * @param {Object} [commonProperties={}] GeoJSON properties passed to ALL isolines
72
- * @param {Object} [breaksProperties=[]] GeoJSON properties passed to the correspondent isoline
73
- * @returns {Array<MultiLineString>} isolines
74
- */
75
- function createIsoLines(matrix, breaks, zProperty, commonProperties, breaksProperties) {
76
- const results = [];
77
- for (let i = 1; i < breaks.length; i++) {
78
- const threshold = +breaks[i]; // make sure it's a number
79
- const properties = Object.assign(Object.assign({}, commonProperties), breaksProperties[i]);
80
- properties[zProperty] = threshold;
81
- const isoline = multiLineString(isoContours(matrix, threshold), properties);
82
- results.push(isoline);
83
- }
84
- return results;
85
- }
86
- /**
87
- * Translates and scales isolines
88
- *
89
- * @private
90
- * @param {Array<MultiLineString>} createdIsoLines to be rescaled
91
- * @param {Array<Array<number>>} matrix Grid Data
92
- * @param {Object} points Points by Latitude
93
- * @returns {Array<MultiLineString>} isolines
94
- */
95
- function rescaleIsolines(createdIsoLines, matrix, points) {
96
- // get dimensions (on the map) of the original grid
97
- const gridBbox = bbox(points); // [ minX, minY, maxX, maxY ]
98
- const originalWidth = gridBbox[2] - gridBbox[0];
99
- const originalHeigth = gridBbox[3] - gridBbox[1];
100
- // get origin, which is the first point of the last row on the rectangular data on the map
101
- const x0 = gridBbox[0];
102
- const y0 = gridBbox[1];
103
- // get number of cells per side
104
- const matrixWidth = matrix[0].length - 1;
105
- const matrixHeight = matrix.length - 1;
106
- // calculate the scaling factor between matrix and rectangular grid on the map
107
- const scaleX = originalWidth / matrixWidth;
108
- const scaleY = originalHeigth / matrixHeight;
109
- const resize = (point) => {
110
- point[0] = point[0] * scaleX + x0;
111
- point[1] = point[1] * scaleY + y0;
112
- };
113
- // resize and shift each point/line of the createdIsoLines
114
- createdIsoLines.forEach((isoline) => {
115
- coordEach(isoline, resize);
116
- });
117
- return createdIsoLines;
118
- }
119
- export default isolines;
@@ -1,101 +0,0 @@
1
- import { getCoords, collectionOf } from "@turf/invariant";
2
- import { featureEach } from "@turf/meta";
3
- import { isObject } from "@turf/helpers";
4
- /**
5
- * Takes a {@link Point} grid and returns a correspondent matrix {Array<Array<number>>}
6
- * of the 'property' values
7
- *
8
- * @name gridToMatrix
9
- * @param {FeatureCollection<Point>} grid of points
10
- * @param {Object} [options={}] Optional parameters
11
- * @param {string} [options.zProperty='elevation'] the property name in `points` from which z-values will be pulled
12
- * @param {boolean} [options.flip=false] returns the matrix upside-down
13
- * @param {boolean} [options.flags=false] flags, adding a `matrixPosition` array field ([row, column]) to its properties,
14
- * the grid points with coordinates on the matrix
15
- * @returns {Array<Array<number>>} matrix of property values
16
- * @example
17
- * var extent = [-70.823364, -33.553984, -70.473175, -33.302986];
18
- * var cellSize = 3;
19
- * var grid = turf.pointGrid(extent, cellSize);
20
- * // add a random property to each point between 0 and 60
21
- * for (var i = 0; i < grid.features.length; i++) {
22
- * grid.features[i].properties.elevation = (Math.random() * 60);
23
- * }
24
- * gridToMatrix(grid);
25
- * //= [
26
- * [ 1, 13, 10, 9, 10, 13, 18],
27
- * [34, 8, 5, 4, 5, 8, 13],
28
- * [10, 5, 2, 1, 2, 5, 4],
29
- * [ 0, 4, 56, 19, 1, 4, 9],
30
- * [10, 5, 2, 1, 2, 5, 10],
31
- * [57, 8, 5, 4, 5, 0, 57],
32
- * [ 3, 13, 10, 9, 5, 13, 18],
33
- * [18, 13, 10, 9, 78, 13, 18]
34
- * ]
35
- */
36
- export default function gridToMatrix(grid, options) {
37
- // Optional parameters
38
- options = options || {};
39
- if (!isObject(options))
40
- throw new Error("options is invalid");
41
- var zProperty = options.zProperty || "elevation";
42
- var flip = options.flip;
43
- var flags = options.flags;
44
- // validation
45
- collectionOf(grid, "Point", "input must contain Points");
46
- var pointsMatrix = sortPointsByLatLng(grid, flip);
47
- var matrix = [];
48
- // create property matrix from sorted points
49
- // looping order matters here
50
- for (var r = 0; r < pointsMatrix.length; r++) {
51
- var pointRow = pointsMatrix[r];
52
- var row = [];
53
- for (var c = 0; c < pointRow.length; c++) {
54
- var point = pointRow[c];
55
- // Check if zProperty exist
56
- if (point.properties[zProperty])
57
- row.push(point.properties[zProperty]);
58
- else
59
- row.push(0);
60
- // add flags
61
- if (flags === true)
62
- point.properties.matrixPosition = [r, c];
63
- }
64
- matrix.push(row);
65
- }
66
- return matrix;
67
- }
68
- /**
69
- * Sorts points by latitude and longitude, creating a 2-dimensional array of points
70
- *
71
- * @private
72
- * @param {FeatureCollection<Point>} points GeoJSON Point features
73
- * @param {boolean} [flip=false] returns the matrix upside-down
74
- * @returns {Array<Array<Point>>} points ordered by latitude and longitude
75
- */
76
- function sortPointsByLatLng(points, flip) {
77
- var pointsByLatitude = {};
78
- // divide points by rows with the same latitude
79
- featureEach(points, function (point) {
80
- var lat = getCoords(point)[1];
81
- if (!pointsByLatitude[lat])
82
- pointsByLatitude[lat] = [];
83
- pointsByLatitude[lat].push(point);
84
- });
85
- // sort points (with the same latitude) by longitude
86
- var orderedRowsByLatitude = Object.keys(pointsByLatitude).map(function (lat) {
87
- var row = pointsByLatitude[lat];
88
- var rowOrderedByLongitude = row.sort(function (a, b) {
89
- return getCoords(a)[0] - getCoords(b)[0];
90
- });
91
- return rowOrderedByLongitude;
92
- });
93
- // sort rows (of points with the same latitude) by latitude
94
- var pointMatrix = orderedRowsByLatitude.sort(function (a, b) {
95
- if (flip)
96
- return getCoords(a[0])[1] - getCoords(b[0])[1];
97
- else
98
- return getCoords(b[0])[1] - getCoords(a[0])[1];
99
- });
100
- return pointMatrix;
101
- }
@@ -1,385 +0,0 @@
1
- /**
2
- * @license GNU Affero General Public License.
3
- * Copyright (c) 2015, 2015 Ronny Lorenz <ronny@tbi.univie.ac.at>
4
- * v. 1.2.0
5
- * https://github.com/RaumZeit/MarchingSquares.js
6
- *
7
- * MarchingSquaresJS is free software: you can redistribute it and/or modify
8
- * it under the terms of the GNU Affero General Public License as published by
9
- * the Free Software Foundation, either version 3 of the License, or
10
- * (at your option) any later version.
11
- *
12
- * MarchingSquaresJS is distributed in the hope that it will be useful,
13
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
- * GNU Affero General Public License for more details.
16
- *
17
- * As additional permission under GNU Affero General Public License version 3
18
- * section 7, third-party projects (personal or commercial) may distribute,
19
- * include, or link against UNMODIFIED VERSIONS of MarchingSquaresJS without the
20
- * requirement that said third-party project for that reason alone becomes
21
- * subject to any requirement of the GNU Affero General Public License version 3.
22
- * Any modifications to MarchingSquaresJS, however, must be shared with the public
23
- * and made available.
24
- *
25
- * In summary this:
26
- * - allows you to use MarchingSquaresJS at no cost
27
- * - allows you to use MarchingSquaresJS for both personal and commercial purposes
28
- * - allows you to distribute UNMODIFIED VERSIONS of MarchingSquaresJS under any
29
- * license as long as this license notice is included
30
- * - enables you to keep the source code of your program that uses MarchingSquaresJS
31
- * undisclosed
32
- * - forces you to share any modifications you have made to MarchingSquaresJS,
33
- * e.g. bug-fixes
34
- *
35
- * You should have received a copy of the GNU Affero General Public License
36
- * along with MarchingSquaresJS. If not, see <http://www.gnu.org/licenses/>.
37
- */
38
- /**
39
- * Compute the isocontour(s) of a scalar 2D field given
40
- * a certain threshold by applying the Marching Squares
41
- * Algorithm. The function returns a list of path coordinates
42
- */
43
- var defaultSettings = {
44
- successCallback: null,
45
- verbose: false,
46
- };
47
- var settings = {};
48
- export default function isoContours(data, threshold, options) {
49
- /* process options */
50
- options = options ? options : {};
51
- var optionKeys = Object.keys(defaultSettings);
52
- for (var i = 0; i < optionKeys.length; i++) {
53
- var key = optionKeys[i];
54
- var val = options[key];
55
- val =
56
- typeof val !== "undefined" && val !== null ? val : defaultSettings[key];
57
- settings[key] = val;
58
- }
59
- if (settings.verbose)
60
- console.log("MarchingSquaresJS-isoContours: computing isocontour for " + threshold);
61
- var ret = contourGrid2Paths(computeContourGrid(data, threshold));
62
- if (typeof settings.successCallback === "function")
63
- settings.successCallback(ret);
64
- return ret;
65
- }
66
- /*
67
- Thats all for the public interface, below follows the actual
68
- implementation
69
- */
70
- /*
71
- ################################
72
- Isocontour implementation below
73
- ################################
74
- */
75
- /* assume that x1 == 1 && x0 == 0 */
76
- function interpolateX(y, y0, y1) {
77
- return (y - y0) / (y1 - y0);
78
- }
79
- /* compute the isocontour 4-bit grid */
80
- function computeContourGrid(data, threshold) {
81
- var rows = data.length - 1;
82
- var cols = data[0].length - 1;
83
- var ContourGrid = { rows: rows, cols: cols, cells: [] };
84
- for (var j = 0; j < rows; ++j) {
85
- ContourGrid.cells[j] = [];
86
- for (var i = 0; i < cols; ++i) {
87
- /* compose the 4-bit corner representation */
88
- var cval = 0;
89
- var tl = data[j + 1][i];
90
- var tr = data[j + 1][i + 1];
91
- var br = data[j][i + 1];
92
- var bl = data[j][i];
93
- if (isNaN(tl) || isNaN(tr) || isNaN(br) || isNaN(bl)) {
94
- continue;
95
- }
96
- cval |= tl >= threshold ? 8 : 0;
97
- cval |= tr >= threshold ? 4 : 0;
98
- cval |= br >= threshold ? 2 : 0;
99
- cval |= bl >= threshold ? 1 : 0;
100
- /* resolve ambiguity for cval == 5 || 10 via averaging */
101
- var flipped = false;
102
- if (cval === 5 || cval === 10) {
103
- var average = (tl + tr + br + bl) / 4;
104
- if (cval === 5 && average < threshold) {
105
- cval = 10;
106
- flipped = true;
107
- }
108
- else if (cval === 10 && average < threshold) {
109
- cval = 5;
110
- flipped = true;
111
- }
112
- }
113
- /* add cell to ContourGrid if it contains edges */
114
- if (cval !== 0 && cval !== 15) {
115
- var top, bottom, left, right;
116
- top = bottom = left = right = 0.5;
117
- /* interpolate edges of cell */
118
- if (cval === 1) {
119
- left = 1 - interpolateX(threshold, tl, bl);
120
- bottom = 1 - interpolateX(threshold, br, bl);
121
- }
122
- else if (cval === 2) {
123
- bottom = interpolateX(threshold, bl, br);
124
- right = 1 - interpolateX(threshold, tr, br);
125
- }
126
- else if (cval === 3) {
127
- left = 1 - interpolateX(threshold, tl, bl);
128
- right = 1 - interpolateX(threshold, tr, br);
129
- }
130
- else if (cval === 4) {
131
- top = interpolateX(threshold, tl, tr);
132
- right = interpolateX(threshold, br, tr);
133
- }
134
- else if (cval === 5) {
135
- top = interpolateX(threshold, tl, tr);
136
- right = interpolateX(threshold, br, tr);
137
- bottom = 1 - interpolateX(threshold, br, bl);
138
- left = 1 - interpolateX(threshold, tl, bl);
139
- }
140
- else if (cval === 6) {
141
- bottom = interpolateX(threshold, bl, br);
142
- top = interpolateX(threshold, tl, tr);
143
- }
144
- else if (cval === 7) {
145
- left = 1 - interpolateX(threshold, tl, bl);
146
- top = interpolateX(threshold, tl, tr);
147
- }
148
- else if (cval === 8) {
149
- left = interpolateX(threshold, bl, tl);
150
- top = 1 - interpolateX(threshold, tr, tl);
151
- }
152
- else if (cval === 9) {
153
- bottom = 1 - interpolateX(threshold, br, bl);
154
- top = 1 - interpolateX(threshold, tr, tl);
155
- }
156
- else if (cval === 10) {
157
- top = 1 - interpolateX(threshold, tr, tl);
158
- right = 1 - interpolateX(threshold, tr, br);
159
- bottom = interpolateX(threshold, bl, br);
160
- left = interpolateX(threshold, bl, tl);
161
- }
162
- else if (cval === 11) {
163
- top = 1 - interpolateX(threshold, tr, tl);
164
- right = 1 - interpolateX(threshold, tr, br);
165
- }
166
- else if (cval === 12) {
167
- left = interpolateX(threshold, bl, tl);
168
- right = interpolateX(threshold, br, tr);
169
- }
170
- else if (cval === 13) {
171
- bottom = 1 - interpolateX(threshold, br, bl);
172
- right = interpolateX(threshold, br, tr);
173
- }
174
- else if (cval === 14) {
175
- left = interpolateX(threshold, bl, tl);
176
- bottom = interpolateX(threshold, bl, br);
177
- }
178
- else {
179
- console.log("MarchingSquaresJS-isoContours: Illegal cval detected: " + cval);
180
- }
181
- ContourGrid.cells[j][i] = {
182
- cval: cval,
183
- flipped: flipped,
184
- top: top,
185
- right: right,
186
- bottom: bottom,
187
- left: left,
188
- };
189
- }
190
- }
191
- }
192
- return ContourGrid;
193
- }
194
- function isSaddle(cell) {
195
- return cell.cval === 5 || cell.cval === 10;
196
- }
197
- function isTrivial(cell) {
198
- return cell.cval === 0 || cell.cval === 15;
199
- }
200
- function clearCell(cell) {
201
- if (!isTrivial(cell) && cell.cval !== 5 && cell.cval !== 10) {
202
- cell.cval = 15;
203
- }
204
- }
205
- function getXY(cell, edge) {
206
- if (edge === "top") {
207
- return [cell.top, 1.0];
208
- }
209
- else if (edge === "bottom") {
210
- return [cell.bottom, 0.0];
211
- }
212
- else if (edge === "right") {
213
- return [1.0, cell.right];
214
- }
215
- else if (edge === "left") {
216
- return [0.0, cell.left];
217
- }
218
- }
219
- function contourGrid2Paths(grid) {
220
- var paths = [];
221
- var path_idx = 0;
222
- var epsilon = 1e-7;
223
- grid.cells.forEach(function (g, j) {
224
- g.forEach(function (gg, i) {
225
- if (typeof gg !== "undefined" && !isSaddle(gg) && !isTrivial(gg)) {
226
- var p = tracePath(grid.cells, j, i);
227
- var merged = false;
228
- /* we may try to merge paths at this point */
229
- if (p.info === "mergeable") {
230
- /*
231
- search backwards through the path array to find an entry
232
- that starts with where the current path ends...
233
- */
234
- var x = p.path[p.path.length - 1][0], y = p.path[p.path.length - 1][1];
235
- for (var k = path_idx - 1; k >= 0; k--) {
236
- if (Math.abs(paths[k][0][0] - x) <= epsilon &&
237
- Math.abs(paths[k][0][1] - y) <= epsilon) {
238
- for (var l = p.path.length - 2; l >= 0; --l) {
239
- paths[k].unshift(p.path[l]);
240
- }
241
- merged = true;
242
- break;
243
- }
244
- }
245
- }
246
- if (!merged)
247
- paths[path_idx++] = p.path;
248
- }
249
- });
250
- });
251
- return paths;
252
- }
253
- /*
254
- construct consecutive line segments from starting cell by
255
- walking arround the enclosed area clock-wise
256
- */
257
- function tracePath(grid, j, i) {
258
- var maxj = grid.length;
259
- var p = [];
260
- var dxContour = [0, 0, 1, 1, 0, 0, 0, 0, -1, 0, 1, 1, -1, 0, -1, 0];
261
- var dyContour = [0, -1, 0, 0, 1, 1, 1, 1, 0, -1, 0, 0, 0, -1, 0, 0];
262
- var dx, dy;
263
- var startEdge = [
264
- "none",
265
- "left",
266
- "bottom",
267
- "left",
268
- "right",
269
- "none",
270
- "bottom",
271
- "left",
272
- "top",
273
- "top",
274
- "none",
275
- "top",
276
- "right",
277
- "right",
278
- "bottom",
279
- "none",
280
- ];
281
- var nextEdge = [
282
- "none",
283
- "bottom",
284
- "right",
285
- "right",
286
- "top",
287
- "top",
288
- "top",
289
- "top",
290
- "left",
291
- "bottom",
292
- "right",
293
- "right",
294
- "left",
295
- "bottom",
296
- "left",
297
- "none",
298
- ];
299
- var edge;
300
- var currentCell = grid[j][i];
301
- var cval = currentCell.cval;
302
- var edge = startEdge[cval];
303
- var pt = getXY(currentCell, edge);
304
- /* push initial segment */
305
- p.push([i + pt[0], j + pt[1]]);
306
- edge = nextEdge[cval];
307
- pt = getXY(currentCell, edge);
308
- p.push([i + pt[0], j + pt[1]]);
309
- clearCell(currentCell);
310
- /* now walk arround the enclosed area in clockwise-direction */
311
- var k = i + dxContour[cval];
312
- var l = j + dyContour[cval];
313
- var prev_cval = cval;
314
- while (k >= 0 && l >= 0 && l < maxj && (k != i || l != j)) {
315
- currentCell = grid[l][k];
316
- if (typeof currentCell === "undefined") {
317
- /* path ends here */
318
- //console.log(k + " " + l + " is undefined, stopping path!");
319
- break;
320
- }
321
- cval = currentCell.cval;
322
- if (cval === 0 || cval === 15) {
323
- return { path: p, info: "mergeable" };
324
- }
325
- edge = nextEdge[cval];
326
- dx = dxContour[cval];
327
- dy = dyContour[cval];
328
- if (cval === 5 || cval === 10) {
329
- /* select upper or lower band, depending on previous cells cval */
330
- if (cval === 5) {
331
- if (currentCell.flipped) {
332
- /* this is actually a flipped case 10 */
333
- if (dyContour[prev_cval] === -1) {
334
- edge = "left";
335
- dx = -1;
336
- dy = 0;
337
- }
338
- else {
339
- edge = "right";
340
- dx = 1;
341
- dy = 0;
342
- }
343
- }
344
- else {
345
- /* real case 5 */
346
- if (dxContour[prev_cval] === -1) {
347
- edge = "bottom";
348
- dx = 0;
349
- dy = -1;
350
- }
351
- }
352
- }
353
- else if (cval === 10) {
354
- if (currentCell.flipped) {
355
- /* this is actually a flipped case 5 */
356
- if (dxContour[prev_cval] === -1) {
357
- edge = "top";
358
- dx = 0;
359
- dy = 1;
360
- }
361
- else {
362
- edge = "bottom";
363
- dx = 0;
364
- dy = -1;
365
- }
366
- }
367
- else {
368
- /* real case 10 */
369
- if (dyContour[prev_cval] === 1) {
370
- edge = "left";
371
- dx = -1;
372
- dy = 0;
373
- }
374
- }
375
- }
376
- }
377
- pt = getXY(currentCell, edge);
378
- p.push([k + pt[0], l + pt[1]]);
379
- clearCell(currentCell);
380
- k += dx;
381
- l += dy;
382
- prev_cval = cval;
383
- }
384
- return { path: p, info: "closed" };
385
- }
@@ -1 +0,0 @@
1
- {"type":"module"}