@turf/shortest-path 7.0.0-alpha.2 → 7.1.0-alpha.7

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,589 +0,0 @@
1
- import bbox from '@turf/bbox';
2
- import booleanPointInPolygon from '@turf/boolean-point-in-polygon';
3
- import distance from '@turf/distance';
4
- import scale from '@turf/transform-scale';
5
- import cleanCoords from '@turf/clean-coords';
6
- import bboxPolygon from '@turf/bbox-polygon';
7
- import { getCoord, getType, getGeom } from '@turf/invariant';
8
- import { isObject, featureCollection, isNumber, point, feature, lineString } from '@turf/helpers';
9
-
10
- // javascript-astar 0.4.1
11
- // http://github.com/bgrins/javascript-astar
12
- // Freely distributable under the MIT License.
13
- // Implements the astar search algorithm in javascript using a Binary Heap.
14
- // Includes Binary Heap (with modifications) from Marijn Haverbeke.
15
- // http://eloquentjavascript.net/appendix2.html
16
-
17
- function pathTo(node) {
18
- var curr = node,
19
- path = [];
20
- while (curr.parent) {
21
- path.unshift(curr);
22
- curr = curr.parent;
23
- }
24
- return path;
25
- }
26
-
27
- function getHeap() {
28
- return new BinaryHeap(function (node) {
29
- return node.f;
30
- });
31
- }
32
-
33
- /**
34
- * Astar
35
- * @private
36
- */
37
- var astar = {
38
- /**
39
- * Perform an A* Search on a graph given a start and end node.
40
- *
41
- * @private
42
- * @memberof astar
43
- * @param {Graph} graph Graph
44
- * @param {GridNode} start Start
45
- * @param {GridNode} end End
46
- * @param {Object} [options] Options
47
- * @param {bool} [options.closest] Specifies whether to return the path to the closest node if the target is unreachable.
48
- * @param {Function} [options.heuristic] Heuristic function (see astar.heuristics).
49
- * @returns {Object} Search
50
- */
51
- search: function (graph, start, end, options) {
52
- graph.cleanDirty();
53
- options = options || {};
54
- var heuristic = options.heuristic || astar.heuristics.manhattan,
55
- closest = options.closest || false;
56
-
57
- var openHeap = getHeap(),
58
- closestNode = start; // set the start node to be the closest if required
59
-
60
- start.h = heuristic(start, end);
61
-
62
- openHeap.push(start);
63
-
64
- while (openHeap.size() > 0) {
65
- // Grab the lowest f(x) to process next. Heap keeps this sorted for us.
66
- var currentNode = openHeap.pop();
67
-
68
- // End case -- result has been found, return the traced path.
69
- if (currentNode === end) {
70
- return pathTo(currentNode);
71
- }
72
-
73
- // Normal case -- move currentNode from open to closed, process each of its neighbors.
74
- currentNode.closed = true;
75
-
76
- // Find all neighbors for the current node.
77
- var neighbors = graph.neighbors(currentNode);
78
-
79
- for (var i = 0, il = neighbors.length; i < il; ++i) {
80
- var neighbor = neighbors[i];
81
-
82
- if (neighbor.closed || neighbor.isWall()) {
83
- // Not a valid node to process, skip to next neighbor.
84
- continue;
85
- }
86
-
87
- // The g score is the shortest distance from start to current node.
88
- // We need to check if the path we have arrived at this neighbor is the shortest one we have seen yet.
89
- var gScore = currentNode.g + neighbor.getCost(currentNode),
90
- beenVisited = neighbor.visited;
91
-
92
- if (!beenVisited || gScore < neighbor.g) {
93
- // Found an optimal (so far) path to this node. Take score for node to see how good it is.
94
- neighbor.visited = true;
95
- neighbor.parent = currentNode;
96
- neighbor.h = neighbor.h || heuristic(neighbor, end);
97
- neighbor.g = gScore;
98
- neighbor.f = neighbor.g + neighbor.h;
99
- graph.markDirty(neighbor);
100
- if (closest) {
101
- // If the neighbour is closer than the current closestNode or if it's equally close but has
102
- // a cheaper path than the current closest node then it becomes the closest node
103
- if (
104
- neighbor.h < closestNode.h ||
105
- (neighbor.h === closestNode.h && neighbor.g < closestNode.g)
106
- ) {
107
- closestNode = neighbor;
108
- }
109
- }
110
-
111
- if (!beenVisited) {
112
- // Pushing to heap will put it in proper place based on the 'f' value.
113
- openHeap.push(neighbor);
114
- } else {
115
- // Already seen the node, but since it has been rescored we need to reorder it in the heap
116
- openHeap.rescoreElement(neighbor);
117
- }
118
- }
119
- }
120
- }
121
-
122
- if (closest) {
123
- return pathTo(closestNode);
124
- }
125
-
126
- // No result was found - empty array signifies failure to find path.
127
- return [];
128
- },
129
- // See list of heuristics: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
130
- heuristics: {
131
- manhattan: function (pos0, pos1) {
132
- var d1 = Math.abs(pos1.x - pos0.x);
133
- var d2 = Math.abs(pos1.y - pos0.y);
134
- return d1 + d2;
135
- },
136
- diagonal: function (pos0, pos1) {
137
- var D = 1;
138
- var D2 = Math.sqrt(2);
139
- var d1 = Math.abs(pos1.x - pos0.x);
140
- var d2 = Math.abs(pos1.y - pos0.y);
141
- return D * (d1 + d2) + (D2 - 2 * D) * Math.min(d1, d2);
142
- },
143
- },
144
- cleanNode: function (node) {
145
- node.f = 0;
146
- node.g = 0;
147
- node.h = 0;
148
- node.visited = false;
149
- node.closed = false;
150
- node.parent = null;
151
- },
152
- };
153
-
154
- /**
155
- * A graph memory structure
156
- *
157
- * @private
158
- * @param {Array} gridIn 2D array of input weights
159
- * @param {Object} [options] Options
160
- * @param {boolean} [options.diagonal] Specifies whether diagonal moves are allowed
161
- * @returns {void} Graph
162
- */
163
- function Graph(gridIn, options) {
164
- options = options || {};
165
- this.nodes = [];
166
- this.diagonal = !!options.diagonal;
167
- this.grid = [];
168
- for (var x = 0; x < gridIn.length; x++) {
169
- this.grid[x] = [];
170
-
171
- for (var y = 0, row = gridIn[x]; y < row.length; y++) {
172
- var node = new GridNode(x, y, row[y]);
173
- this.grid[x][y] = node;
174
- this.nodes.push(node);
175
- }
176
- }
177
- this.init();
178
- }
179
-
180
- Graph.prototype.init = function () {
181
- this.dirtyNodes = [];
182
- for (var i = 0; i < this.nodes.length; i++) {
183
- astar.cleanNode(this.nodes[i]);
184
- }
185
- };
186
-
187
- Graph.prototype.cleanDirty = function () {
188
- for (var i = 0; i < this.dirtyNodes.length; i++) {
189
- astar.cleanNode(this.dirtyNodes[i]);
190
- }
191
- this.dirtyNodes = [];
192
- };
193
-
194
- Graph.prototype.markDirty = function (node) {
195
- this.dirtyNodes.push(node);
196
- };
197
-
198
- Graph.prototype.neighbors = function (node) {
199
- var ret = [],
200
- x = node.x,
201
- y = node.y,
202
- grid = this.grid;
203
-
204
- // West
205
- if (grid[x - 1] && grid[x - 1][y]) {
206
- ret.push(grid[x - 1][y]);
207
- }
208
-
209
- // East
210
- if (grid[x + 1] && grid[x + 1][y]) {
211
- ret.push(grid[x + 1][y]);
212
- }
213
-
214
- // South
215
- if (grid[x] && grid[x][y - 1]) {
216
- ret.push(grid[x][y - 1]);
217
- }
218
-
219
- // North
220
- if (grid[x] && grid[x][y + 1]) {
221
- ret.push(grid[x][y + 1]);
222
- }
223
-
224
- if (this.diagonal) {
225
- // Southwest
226
- if (grid[x - 1] && grid[x - 1][y - 1]) {
227
- ret.push(grid[x - 1][y - 1]);
228
- }
229
-
230
- // Southeast
231
- if (grid[x + 1] && grid[x + 1][y - 1]) {
232
- ret.push(grid[x + 1][y - 1]);
233
- }
234
-
235
- // Northwest
236
- if (grid[x - 1] && grid[x - 1][y + 1]) {
237
- ret.push(grid[x - 1][y + 1]);
238
- }
239
-
240
- // Northeast
241
- if (grid[x + 1] && grid[x + 1][y + 1]) {
242
- ret.push(grid[x + 1][y + 1]);
243
- }
244
- }
245
-
246
- return ret;
247
- };
248
-
249
- Graph.prototype.toString = function () {
250
- var graphString = [],
251
- nodes = this.grid, // when using grid
252
- rowDebug,
253
- row,
254
- y,
255
- l;
256
- for (var x = 0, len = nodes.length; x < len; x++) {
257
- rowDebug = [];
258
- row = nodes[x];
259
- for (y = 0, l = row.length; y < l; y++) {
260
- rowDebug.push(row[y].weight);
261
- }
262
- graphString.push(rowDebug.join(" "));
263
- }
264
- return graphString.join("\n");
265
- };
266
-
267
- function GridNode(x, y, weight) {
268
- this.x = x;
269
- this.y = y;
270
- this.weight = weight;
271
- }
272
-
273
- GridNode.prototype.toString = function () {
274
- return "[" + this.x + " " + this.y + "]";
275
- };
276
-
277
- GridNode.prototype.getCost = function (fromNeighbor) {
278
- // Take diagonal weight into consideration.
279
- if (fromNeighbor && fromNeighbor.x !== this.x && fromNeighbor.y !== this.y) {
280
- return this.weight * 1.41421;
281
- }
282
- return this.weight;
283
- };
284
-
285
- GridNode.prototype.isWall = function () {
286
- return this.weight === 0;
287
- };
288
-
289
- function BinaryHeap(scoreFunction) {
290
- this.content = [];
291
- this.scoreFunction = scoreFunction;
292
- }
293
-
294
- BinaryHeap.prototype = {
295
- push: function (element) {
296
- // Add the new element to the end of the array.
297
- this.content.push(element);
298
-
299
- // Allow it to sink down.
300
- this.sinkDown(this.content.length - 1);
301
- },
302
- pop: function () {
303
- // Store the first element so we can return it later.
304
- var result = this.content[0];
305
- // Get the element at the end of the array.
306
- var end = this.content.pop();
307
- // If there are any elements left, put the end element at the
308
- // start, and let it bubble up.
309
- if (this.content.length > 0) {
310
- this.content[0] = end;
311
- this.bubbleUp(0);
312
- }
313
- return result;
314
- },
315
- remove: function (node) {
316
- var i = this.content.indexOf(node);
317
-
318
- // When it is found, the process seen in 'pop' is repeated
319
- // to fill up the hole.
320
- var end = this.content.pop();
321
-
322
- if (i !== this.content.length - 1) {
323
- this.content[i] = end;
324
-
325
- if (this.scoreFunction(end) < this.scoreFunction(node)) {
326
- this.sinkDown(i);
327
- } else {
328
- this.bubbleUp(i);
329
- }
330
- }
331
- },
332
- size: function () {
333
- return this.content.length;
334
- },
335
- rescoreElement: function (node) {
336
- this.sinkDown(this.content.indexOf(node));
337
- },
338
- sinkDown: function (n) {
339
- // Fetch the element that has to be sunk.
340
- var element = this.content[n];
341
-
342
- // When at 0, an element can not sink any further.
343
- while (n > 0) {
344
- // Compute the parent element's index, and fetch it.
345
- var parentN = ((n + 1) >> 1) - 1,
346
- parent = this.content[parentN];
347
- // Swap the elements if the parent is greater.
348
- if (this.scoreFunction(element) < this.scoreFunction(parent)) {
349
- this.content[parentN] = element;
350
- this.content[n] = parent;
351
- // Update 'n' to continue at the new position.
352
- n = parentN;
353
- // Found a parent that is less, no need to sink any further.
354
- } else {
355
- break;
356
- }
357
- }
358
- },
359
- bubbleUp: function (n) {
360
- // Look up the target element and its score.
361
- var length = this.content.length,
362
- element = this.content[n],
363
- elemScore = this.scoreFunction(element);
364
-
365
- while (true) {
366
- // Compute the indices of the child elements.
367
- var child2N = (n + 1) << 1,
368
- child1N = child2N - 1;
369
- // This is used to store the new position of the element, if any.
370
- var swap = null,
371
- child1Score;
372
- // If the first child exists (is inside the array)...
373
- if (child1N < length) {
374
- // Look it up and compute its score.
375
- var child1 = this.content[child1N];
376
- child1Score = this.scoreFunction(child1);
377
-
378
- // If the score is less than our element's, we need to swap.
379
- if (child1Score < elemScore) {
380
- swap = child1N;
381
- }
382
- }
383
-
384
- // Do the same checks for the other child.
385
- if (child2N < length) {
386
- var child2 = this.content[child2N],
387
- child2Score = this.scoreFunction(child2);
388
- if (child2Score < (swap === null ? elemScore : child1Score)) {
389
- swap = child2N;
390
- }
391
- }
392
-
393
- // If the element needs to be moved, swap it, and continue.
394
- if (swap !== null) {
395
- this.content[n] = this.content[swap];
396
- this.content[swap] = element;
397
- n = swap;
398
- // Otherwise, we are done.
399
- } else {
400
- break;
401
- }
402
- }
403
- },
404
- };
405
-
406
- /**
407
- * Returns the shortest {@link LineString|path} from {@link Point|start} to {@link Point|end} without colliding with
408
- * any {@link Feature} in {@link FeatureCollection<Polygon>| obstacles}
409
- *
410
- * @name shortestPath
411
- * @param {Coord} start point
412
- * @param {Coord} end point
413
- * @param {Object} [options={}] optional parameters
414
- * @param {Geometry|Feature|FeatureCollection<Polygon>} [options.obstacles] areas which path cannot travel
415
- * @param {number} [options.minDistance] minimum distance between shortest path and obstacles
416
- * @param {string} [options.units='kilometers'] unit in which resolution & minimum distance will be expressed in; it can be degrees, radians, miles, kilometers, ...
417
- * @param {number} [options.resolution=100] distance between matrix points on which the path will be calculated
418
- * @returns {Feature<LineString>} shortest path between start and end
419
- * @example
420
- * var start = [-5, -6];
421
- * var end = [9, -6];
422
- * var options = {
423
- * obstacles: turf.polygon([[[0, -7], [5, -7], [5, -3], [0, -3], [0, -7]]])
424
- * };
425
- *
426
- * var path = turf.shortestPath(start, end, options);
427
- *
428
- * //addToMap
429
- * var addToMap = [start, end, options.obstacles, path];
430
- */
431
- function shortestPath(start, end, options) {
432
- // Optional parameters
433
- options = options || {};
434
- if (!isObject(options)) throw new Error("options is invalid");
435
- var resolution = options.resolution;
436
- var minDistance = options.minDistance;
437
- var obstacles = options.obstacles || featureCollection([]);
438
-
439
- // validation
440
- if (!start) throw new Error("start is required");
441
- if (!end) throw new Error("end is required");
442
- if ((resolution && !isNumber(resolution)) || resolution <= 0)
443
- throw new Error("options.resolution must be a number, greater than 0");
444
- if (minDistance)
445
- throw new Error("options.minDistance is not yet implemented");
446
-
447
- // Normalize Inputs
448
- var startCoord = getCoord(start);
449
- var endCoord = getCoord(end);
450
- start = point(startCoord);
451
- end = point(endCoord);
452
-
453
- // Handle obstacles
454
- switch (getType(obstacles)) {
455
- case "FeatureCollection":
456
- if (obstacles.features.length === 0)
457
- return lineString([startCoord, endCoord]);
458
- break;
459
- case "Polygon":
460
- obstacles = featureCollection([feature(getGeom(obstacles))]);
461
- break;
462
- default:
463
- throw new Error("invalid obstacles");
464
- }
465
-
466
- // define path grid area
467
- var collection = obstacles;
468
- collection.features.push(start);
469
- collection.features.push(end);
470
- var box = bbox(scale(bboxPolygon(bbox(collection)), 1.15)); // extend 15%
471
- if (!resolution) {
472
- var width = distance([box[0], box[1]], [box[2], box[1]], options);
473
- resolution = width / 100;
474
- }
475
- collection.features.pop();
476
- collection.features.pop();
477
-
478
- var west = box[0];
479
- var south = box[1];
480
- var east = box[2];
481
- var north = box[3];
482
-
483
- var xFraction = resolution / distance([west, south], [east, south], options);
484
- var cellWidth = xFraction * (east - west);
485
- var yFraction = resolution / distance([west, south], [west, north], options);
486
- var cellHeight = yFraction * (north - south);
487
-
488
- var bboxHorizontalSide = east - west;
489
- var bboxVerticalSide = north - south;
490
- var columns = Math.floor(bboxHorizontalSide / cellWidth);
491
- var rows = Math.floor(bboxVerticalSide / cellHeight);
492
- // adjust origin of the grid
493
- var deltaX = (bboxHorizontalSide - columns * cellWidth) / 2;
494
- var deltaY = (bboxVerticalSide - rows * cellHeight) / 2;
495
-
496
- // loop through points only once to speed up process
497
- // define matrix grid for A-star algorithm
498
- var pointMatrix = [];
499
- var matrix = [];
500
-
501
- var closestToStart = [];
502
- var closestToEnd = [];
503
- var minDistStart = Infinity;
504
- var minDistEnd = Infinity;
505
- var currentY = north - deltaY;
506
- var r = 0;
507
- while (currentY >= south) {
508
- // var currentY = south + deltaY;
509
- var matrixRow = [];
510
- var pointMatrixRow = [];
511
- var currentX = west + deltaX;
512
- var c = 0;
513
- while (currentX <= east) {
514
- var pt = point([currentX, currentY]);
515
- var isInsideObstacle = isInside(pt, obstacles);
516
- // feed obstacles matrix
517
- matrixRow.push(isInsideObstacle ? 0 : 1); // with javascript-astar
518
- // matrixRow.push(isInsideObstacle ? 1 : 0); // with astar-andrea
519
- // map point's coords
520
- pointMatrixRow.push(currentX + "|" + currentY);
521
- // set closest points
522
- var distStart = distance(pt, start);
523
- // if (distStart < minDistStart) {
524
- if (!isInsideObstacle && distStart < minDistStart) {
525
- minDistStart = distStart;
526
- closestToStart = { x: c, y: r };
527
- }
528
- var distEnd = distance(pt, end);
529
- // if (distEnd < minDistEnd) {
530
- if (!isInsideObstacle && distEnd < minDistEnd) {
531
- minDistEnd = distEnd;
532
- closestToEnd = { x: c, y: r };
533
- }
534
- currentX += cellWidth;
535
- c++;
536
- }
537
- matrix.push(matrixRow);
538
- pointMatrix.push(pointMatrixRow);
539
- currentY -= cellHeight;
540
- r++;
541
- }
542
-
543
- // find path on matrix grid
544
-
545
- // javascript-astar ----------------------
546
- var graph = new Graph(matrix, { diagonal: true });
547
- var startOnMatrix = graph.grid[closestToStart.y][closestToStart.x];
548
- var endOnMatrix = graph.grid[closestToEnd.y][closestToEnd.x];
549
- var result = astar.search(graph, startOnMatrix, endOnMatrix);
550
-
551
- var path = [startCoord];
552
- result.forEach(function (coord) {
553
- var coords = pointMatrix[coord.x][coord.y].split("|");
554
- path.push([+coords[0], +coords[1]]); // make sure coords are numbers
555
- });
556
- path.push(endCoord);
557
- // ---------------------------------------
558
-
559
- // astar-andrea ------------------------
560
- // var result = aStar(matrix, [closestToStart.x, closestToStart.y], [closestToEnd.x, closestToEnd.y], 'DiagonalFree');
561
- // var path = [start.geometry.coordinates];
562
- // result.forEach(function (coord) {
563
- // var coords = pointMatrix[coord[1]][coord[0]].split('|');
564
- // path.push([+coords[0], +coords[1]]); // make sure coords are numbers
565
- // });
566
- // path.push(end.geometry.coordinates);
567
- // ---------------------------------------
568
-
569
- return cleanCoords(lineString(path));
570
- }
571
-
572
- /**
573
- * Checks if Point is inside any of the Polygons
574
- *
575
- * @private
576
- * @param {Feature<Point>} pt to check
577
- * @param {FeatureCollection<Polygon>} polygons features
578
- * @returns {boolean} if inside or not
579
- */
580
- function isInside(pt, polygons) {
581
- for (var i = 0; i < polygons.features.length; i++) {
582
- if (booleanPointInPolygon(pt, polygons.features[i])) {
583
- return true;
584
- }
585
- }
586
- return false;
587
- }
588
-
589
- export default shortestPath;
@@ -1 +0,0 @@
1
- {"type":"module"}