terra-route 0.0.5 → 0.0.6
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/README.md +11 -2
- package/dist/fibonacci-heap.d.ts +11 -0
- package/dist/terra-route.cjs +1 -1
- package/dist/terra-route.cjs.map +1 -1
- package/dist/terra-route.d.ts +1 -1
- package/dist/terra-route.modern.js +1 -1
- package/dist/terra-route.modern.js.map +1 -1
- package/dist/terra-route.module.js +1 -1
- package/dist/terra-route.module.js.map +1 -1
- package/dist/terra-route.umd.js +1 -1
- package/dist/terra-route.umd.js.map +1 -1
- package/jest.config.js +1 -1
- package/package.json +6 -3
- package/src/fibonacci-heap.spec.ts +55 -0
- package/src/fibonacci-heap.ts +131 -0
- package/src/terra-route.spec.ts +2 -1
- package/src/terra-route.ts +3 -3
- package/src/test-utils/test-utils.ts +9 -0
- package/src/min-heap.spec.ts +0 -75
- package/src/min-heap.ts +0 -87
package/README.md
CHANGED
|
@@ -83,13 +83,22 @@ console.log("Shortest route:", JSON.stringify(route, null, 2));
|
|
|
83
83
|
|
|
84
84
|
## Benchmarks
|
|
85
85
|
|
|
86
|
-
You can run the benchmarks yourself using:
|
|
86
|
+
The benchmarks make use of a series out route example route networks from OSM in a moderate sized section of East London. It runs against the GeoJSON Path Finder library and also the ngraph.graph library. You can run the benchmarks yourself using:
|
|
87
87
|
|
|
88
88
|
```
|
|
89
89
|
npm run benchmark
|
|
90
90
|
```
|
|
91
91
|
|
|
92
|
-
|
|
92
|
+
Here is an example output of a benchmark run for routing:
|
|
93
|
+
|
|
94
|
+
TerraRoute with CheapRuler | █ 26ms
|
|
95
|
+
TerraRoute | ██ 42ms
|
|
96
|
+
GeoJSON Path Finder | █████████████████████████ 609ms
|
|
97
|
+
ngraph.graph | ██████████████████████████████████████████████████ 1227ms
|
|
98
|
+
|
|
99
|
+
Using default Haversine distance, Terra Route is approximately 13x faster than GeoJSON Path Finder with Haversine distance for A -> B path finding. If you pass in the CheapRuler distance metric (you can use the exposed `createCheapRuler` function), it is about 22x faster.
|
|
100
|
+
|
|
101
|
+
For initialisation of the network, Terra Route is about 9x faster with Haversine and 14x faster with CheapRuler than GeoJSON Path Finder. Terra Draw splits out instantiating the Class of the library from the actual graph building, which is done via `buildRouteGraph`. This allows you to defer graph creation to an appropriate time.
|
|
93
102
|
|
|
94
103
|
## Limitations
|
|
95
104
|
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare class FibonacciHeap {
|
|
2
|
+
private nodeCount;
|
|
3
|
+
private minNode;
|
|
4
|
+
insert(key: number, value: number): void;
|
|
5
|
+
extractMin(): number | null;
|
|
6
|
+
size(): number;
|
|
7
|
+
private consolidate;
|
|
8
|
+
private link;
|
|
9
|
+
private mergeLists;
|
|
10
|
+
private removeFromList;
|
|
11
|
+
}
|
package/dist/terra-route.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var
|
|
1
|
+
function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function e(e,n){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,n){if(e){if("string"==typeof e)return t(e,n);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(e,n):void 0}}(e))||n&&e&&"number"==typeof e.length){r&&(e=r);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n=/*#__PURE__*/function(){function t(){this.nodeCount=0,this.minNode=null}var n=t.prototype;return n.insert=function(t,e){var n={key:t,value:e,degree:0,mark:!1,parent:null,child:null,left:null,right:null};n.left=n,n.right=n,this.minNode=this.mergeLists(this.minNode,n),this.nodeCount++},n.extractMin=function(){var t=this.minNode;if(!t)return null;if(t.child){var e=t.child;do{e.parent=null,e=e.right}while(e!==t.child);this.minNode=this.mergeLists(this.minNode,t.child)}return this.removeFromList(t),t===t.right?this.minNode=null:(this.minNode=t.right,this.consolidate()),this.nodeCount--,t.value},n.size=function(){return this.nodeCount},n.consolidate=function(){var t=Math.floor(Math.log2(this.nodeCount))+1,n=new Array(t).fill(null),r=[],i=this.minNode;do{r.push(i),i=i.right}while(i!==this.minNode);for(var o=0,a=r;o<a.length;o++){for(var s=a[o],h=s.degree;n[h];){var d=n[h];if(s.key>d.key){var c=s;s=d,d=c}this.link(d,s),n[h]=null,h++}n[h]=s}this.minNode=null;for(var u,l=e(n);!(u=l()).done;){var f=u.value;f&&(this.minNode=this.mergeLists(this.minNode,f))}},n.link=function(t,e){this.removeFromList(t),t.left=t.right=t,e.child=this.mergeLists(e.child,t),t.parent=e,e.degree++,t.mark=!1},n.mergeLists=function(t,e){if(!t)return e;if(!e)return t;var n=t.right,r=e.right;return t.right=r,r.left=t,e.right=n,n.left=e,t.key<e.key?t:e},n.removeFromList=function(t){t.left.right=t.right,t.right.left=t.left},t}(),r=function(t,e){var n=function(t){return t*Math.PI/180},r=n(t[1]),i=n(t[0]),o=n(e[1]),a=o-r,s=n(e[0])-i,h=Math.sin(a/2)*Math.sin(a/2)+Math.cos(r)*Math.cos(o)*Math.sin(s/2)*Math.sin(s/2);return 2*Math.atan2(Math.sqrt(h),Math.sqrt(1-h))*6371e3/1e3};exports.TerraRoute=/*#__PURE__*/function(){function t(t){this.network=void 0,this.distanceMeasurement=void 0,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map,this.distanceMeasurement=t||r}var i=t.prototype;return i.coordinateIndex=function(t){var e=t[0],n=t[1];this.coordMap.has(e)||this.coordMap.set(e,new Map);var r=this.coordMap.get(e);if(r.has(n))return r.get(n);var i=this.coords.length;return this.coords.push(t),r.set(n,i),i},i.buildRouteGraph=function(t){this.network=t,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map;for(var n,r=e(this.network.features);!(n=r()).done;)for(var i=n.value.geometry.coordinates,o=0;o<i.length-1;o++){var a=this.coordinateIndex(i[o]),s=this.coordinateIndex(i[o+1]),h=this.distanceMeasurement(i[o],i[o+1]);this.adjacencyList.has(a)||this.adjacencyList.set(a,[]),this.adjacencyList.has(s)||this.adjacencyList.set(s,[]),this.adjacencyList.get(a).push({node:s,distance:h}),this.adjacencyList.get(s).push({node:a,distance:h})}},i.getRoute=function(t,r){if(!this.network)throw new Error("Network not built. Please call buildRouteGraph(network) first.");var i=this.coordinateIndex(t.geometry.coordinates),o=this.coordinateIndex(r.geometry.coordinates);if(i===o)return null;var a=new n,s=new n;a.insert(0,i),s.insert(0,o);for(var h=new Map,d=new Map,c=new Map([[i,0]]),u=new Map([[o,0]]),l=new Set,f=new Set,v=null;a.size()>0&&s.size()>0;){var g=a.extractMin();if(l.add(g),f.has(g)){v=g;break}for(var m,p=e(this.adjacencyList.get(g)||[]);!(m=p()).done;){var y,M,w=m.value,L=(null!=(y=c.get(g))?y:Infinity)+w.distance;if(L<(null!=(M=c.get(w.node))?M:Infinity)){h.set(w.node,g),c.set(w.node,L);var k=L+this.distanceMeasurement(this.coords[w.node],this.coords[o]);a.insert(k,w.node)}}var b=s.extractMin();if(f.add(b),l.has(b)){v=b;break}for(var I,N=e(this.adjacencyList.get(b)||[]);!(I=N()).done;){var j,x,S=I.value,A=(null!=(j=u.get(b))?j:Infinity)+S.distance;if(A<(null!=(x=u.get(S.node))?x:Infinity)){d.set(S.node,b),u.set(S.node,A);var C=A+this.distanceMeasurement(this.coords[S.node],this.coords[i]);s.insert(C,S.node)}}}if(null===v)return null;for(var R=[],q=v;void 0!==q;)R.unshift(this.coords[q]),q=h.get(q);var F=[];for(q=d.get(v);void 0!==q;)F.push(this.coords[q]),q=d.get(q);return{type:"Feature",geometry:{type:"LineString",coordinates:[].concat(R,F)},properties:{}}},t}(),exports.createCheapRuler=function(t){var e=1/298.257223563,n=e*(2-e),r=Math.PI/180,i=Math.cos(t*r),o=1/(1-n*(1-i*i)),a=Math.sqrt(o),s=6378.137*r,h=s*a*i,d=s*a*o*(1-n);return function(t,e){for(var n=t[0]-e[0];n<-180;)n+=360;for(;n>180;)n-=360;var r=n*h,i=(t[1]-e[1])*d;return Math.sqrt(r*r+i*i)}},exports.haversineDistance=r;
|
|
2
2
|
//# sourceMappingURL=terra-route.cjs.map
|
package/dist/terra-route.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"terra-route.cjs","sources":["../src/min-heap.ts","../src/distance/haversine.ts","../src/terra-route.ts","../src/distance/cheap-ruler.ts"],"sourcesContent":["export class MinHeap {\n private heap: Array<{ key: number; value: number; index: number }> = [];\n private insertCounter = 0;\n\n insert(key: number, value: number): void {\n const node = { key, value, index: this.insertCounter++ };\n let idx = this.heap.length;\n this.heap.push(node);\n\n // Optimized Bubble Up\n while (idx > 0) {\n const parentIdx = (idx - 1) >>> 1; // Fast Math.floor((idx - 1) / 2)\n const parent = this.heap[parentIdx];\n if (node.key > parent.key || (node.key === parent.key && node.index > parent.index)) break;\n this.heap[idx] = parent;\n idx = parentIdx;\n }\n this.heap[idx] = node;\n }\n\n extractMin(): number | null {\n const length = this.heap.length;\n if (length === 0) return null;\n\n const minNode = this.heap[0];\n const endNode = this.heap.pop()!;\n\n if (length > 1) {\n this.heap[0] = endNode;\n this.bubbleDown(0);\n }\n\n return minNode.value;\n }\n\n size(): number {\n return this.heap.length;\n }\n\n private bubbleDown(idx: number): void {\n const { heap } = this;\n const length = heap.length;\n // Grab the parent node once, then move it down only if needed\n const node = heap[idx];\n const nodeKey = node.key;\n const nodeIndex = node.index;\n\n while (true) {\n // Calculate left and right child indexes\n const leftIdx = (idx << 1) + 1;\n if (leftIdx >= length) {\n // No children => we’re already in place\n break;\n }\n\n // Assume left child is the smaller one by default\n let smallestIdx = leftIdx;\n let smallestKey = heap[leftIdx].key;\n let smallestIndex = heap[leftIdx].index;\n\n const rightIdx = leftIdx + 1;\n if (rightIdx < length) {\n // Compare left child vs. right child\n const rightKey = heap[rightIdx].key;\n const rightIndex = heap[rightIdx].index;\n if (rightKey < smallestKey || (rightKey === smallestKey && rightIndex < smallestIndex)) {\n smallestIdx = rightIdx;\n smallestKey = rightKey;\n smallestIndex = rightIndex;\n }\n }\n\n // Compare the smaller child with the parent\n if (smallestKey < nodeKey || (smallestKey === nodeKey && smallestIndex < nodeIndex)) {\n // Swap the smaller child up\n heap[idx] = heap[smallestIdx];\n idx = smallestIdx;\n } else {\n // We’re in the correct position now, so stop\n break;\n }\n }\n\n // Place the original node in its final position\n heap[idx] = node;\n }\n}\n","import { Position } from \"geojson\";\n\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { MinHeap } from \"./min-heap\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\n\n/**\n * TerraRoute is a routing utility for finding the shortest path\n * between two geographic points over a given GeoJSON LineString network.\n *\n * The class builds an internal graph structure based on the provided network,\n * then applies A* algorithm to compute the shortest route.\n */\nclass TerraRoute {\n private network: FeatureCollection<LineString> | undefined;\n private distanceMeasurement: (positionA: Position, positionB: Position) => number;\n private adjacencyList: Map<number, Array<{ node: number; distance: number }>> = new Map();\n private coords: Position[] = []\n private coordMap: Map<number, Map<number, number>> = new Map();\n\n /**\n * Creates a new instance of TerraRoute.\n * \n * @param distanceMeasurement - Optional custom distance measurement function (defaults to haversine distance).\n */\n constructor(\n distanceMeasurement?: (positionA: Position, positionB: Position) => number\n ) {\n this.distanceMeasurement = distanceMeasurement ? distanceMeasurement : haversineDistance;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n private coordinateIndex(coord: Position): number {\n const [lng, lat] = coord;\n if (!this.coordMap.has(lng)) this.coordMap.set(lng, new Map());\n\n const latMap = this.coordMap.get(lng)!;\n if (latMap.has(lat)) {\n return latMap.get(lat)!;\n }\n\n const idx = this.coords.length;\n this.coords.push(coord);\n latMap.set(lat, idx);\n\n return idx;\n }\n\n /**\n * Builds the internal graph representation (adjacency list) from the input network.\n * Each LineString segment is translated into bidirectional graph edges with associated distances.\n * Assumes that the network is a connected graph of LineStrings with shared coordinates. Calling this \n * method with a new network overwrite any existing network and reset all internal data structures.\n * \n * @param network - A GeoJSON FeatureCollection of LineStrings representing the road network.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n this.adjacencyList = new Map();\n this.coords = [];\n this.coordMap = new Map();\n\n for (const feature of this.network.features) {\n const coords = feature.geometry.coordinates;\n for (let i = 0; i < coords.length - 1; i++) {\n const aIdx = this.coordinateIndex(coords[i]);\n const bIdx = this.coordinateIndex(coords[i + 1]);\n const distance = this.distanceMeasurement(coords[i], coords[i + 1]);\n\n if (!this.adjacencyList.has(aIdx)) this.adjacencyList.set(aIdx, []);\n if (!this.adjacencyList.has(bIdx)) this.adjacencyList.set(bIdx, []);\n\n this.adjacencyList.get(aIdx)!.push({ node: bIdx, distance });\n this.adjacencyList.get(bIdx)!.push({ node: aIdx, distance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildNetworkGraph(network) first.\");\n }\n\n const startIdx = this.coordinateIndex(start.geometry.coordinates);\n const endIdx = this.coordinateIndex(end.geometry.coordinates);\n\n if (startIdx === endIdx) {\n return null;\n }\n\n const openSet = new MinHeap();\n openSet.insert(0, startIdx);\n const cameFrom = new Map<number, number>();\n const gScore = new Map<number, number>([[startIdx, 0]]);\n\n while (openSet.size() > 0) {\n const current = openSet.extractMin()!;\n\n if (current === endIdx) {\n const path: Position[] = [];\n let currNode: number | undefined = current;\n while (currNode !== undefined) {\n path.unshift(this.coords[currNode]);\n currNode = cameFrom.get(currNode);\n }\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: path },\n properties: {},\n };\n }\n\n const neighbors = this.adjacencyList.get(current) || [];\n\n for (const neighbor of neighbors) {\n const tentativeGScore = (gScore.get(current) ?? Infinity) + neighbor.distance;\n if (tentativeGScore < (gScore.get(neighbor.node) ?? Infinity)) {\n cameFrom.set(neighbor.node, current);\n gScore.set(neighbor.node, tentativeGScore);\n const fScore = tentativeGScore + this.distanceMeasurement(this.coords[neighbor.node], this.coords[endIdx]);\n openSet.insert(fScore, neighbor.node);\n }\n }\n }\n\n return null;\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}"],"names":["MinHeap","this","heap","insertCounter","_proto","prototype","insert","key","value","node","index","idx","length","push","parentIdx","parent","extractMin","minNode","endNode","pop","bubbleDown","size","nodeKey","nodeIndex","leftIdx","smallestIdx","smallestKey","smallestIndex","rightIdx","rightKey","rightIndex","haversineDistance","pointOne","pointTwo","toRadians","latOrLng","Math","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","a","sin","cos","atan2","sqrt","TerraRoute","distanceMeasurement","network","adjacencyList","Map","coords","coordMap","coordinateIndex","coord","lng","lat","has","set","latMap","get","buildRouteGraph","_iterator","_step","_createForOfIteratorHelperLoose","features","done","geometry","coordinates","i","aIdx","bIdx","distance","getRoute","start","end","Error","startIdx","endIdx","openSet","cameFrom","gScore","current","path","currNode","undefined","unshift","type","properties","_step2","_iterator2","_gScore$get","_gScore$get2","neighbor","tentativeGScore","Infinity","fScore","FE","E2","RAD","cosLat","w2","w","m","kx","ky","b","deltaLng","dx","dy"],"mappings":"oyBAAa,IAAAA,eAAO,WAAA,SAAAA,IAAAC,KACRC,KAA6D,GAC7DC,KAAAA,cAAgB,CAAC,KAAAC,EAAAJ,EAAAK,UAmFxB,OAnFwBD,EAEzBE,OAAA,SAAOC,EAAaC,GAChB,IAAMC,EAAO,CAAEF,IAAAA,EAAKC,MAAAA,EAAOE,MAAOT,KAAKE,iBACnCQ,EAAMV,KAAKC,KAAKU,OAIpB,IAHAX,KAAKC,KAAKW,KAAKJ,GAGRE,EAAM,GAAG,CACZ,IAAMG,EAAaH,EAAM,IAAO,EAC1BI,EAASd,KAAKC,KAAKY,GACzB,GAAIL,EAAKF,IAAMQ,EAAOR,KAAQE,EAAKF,MAAQQ,EAAOR,KAAOE,EAAKC,MAAQK,EAAOL,MAAQ,MACrFT,KAAKC,KAAKS,GAAOI,EACjBJ,EAAMG,CACV,CACAb,KAAKC,KAAKS,GAAOF,CACrB,EAACL,EAEDY,WAAA,WACI,IAAMJ,EAASX,KAAKC,KAAKU,OACzB,GAAe,IAAXA,EAAc,OAAW,KAE7B,IAAMK,EAAU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IiC,EAAStF,OAAKqF,EAAIG,UAAW,CAC3Df,EAAStB,IAAImC,EAAStF,KAAM2E,GAC5BD,EAAOvB,IAAImC,EAAStF,KAAMuF,GAC1B,IAAME,EAASF,EAAkB/F,KAAKgD,oBAAoBhD,KAAKoD,OAAO0C,EAAStF,MAAOR,KAAKoD,OAAO2B,IAClGC,EAAQ3E,OAAO4F,EAAQH,EAAStF,KACpC,CACJ,CACJ,CAEA,WACJ,EAACuC,CAAA,CAhIW,4BCoBV,SAA2BU,GAC7B,IACMyC,EAAK,EAAI,cACTC,EAAKD,GAAM,EAAIA,GACfE,EAAMjE,KAAKC,GAAK,IAEhBiE,EAASlE,KAAKS,IAAIa,EAAM2C,GACxBE,EAAK,GAAK,EAAIH,GAAM,EAAIE,EAASA,IACjCE,EAAIpE,KAAKW,KAAKwD,GAEdE,EATK,SASDJ,EACJK,EAAKD,EAAID,EAAIF,EACbK,EAAKF,EAAID,EAAID,GAAM,EAAIH,GAE7B,OAAgB,SAASzD,EAAaiE,GAGlC,IAFA,IAAIC,EAAWlE,EAAE,GAAKiE,EAAE,GAEjBC,GAAY,KAAKA,GAAY,IACpC,KAAOA,EAAW,KAAKA,GAAY,IAEnC,IAAMC,EAAKD,EAAWH,EAChBK,GAAMpE,EAAE,GAAKiE,EAAE,IAAMD,EAE3B,OAAOvE,KAAKW,KAAK+D,EAAKA,EAAKC,EAAKA,EACpC,CACJ"}
|
|
1
|
+
{"version":3,"file":"terra-route.cjs","sources":["../src/fibonacci-heap.ts","../src/distance/haversine.ts","../src/terra-route.ts","../src/distance/cheap-ruler.ts"],"sourcesContent":["type FibNode = {\n key: number;\n value: number;\n degree: number;\n mark: boolean;\n parent: FibNode | null;\n child: FibNode | null;\n left: FibNode;\n right: FibNode;\n};\n\nexport class FibonacciHeap {\n private nodeCount = 0;\n private minNode: FibNode | null = null;\n\n insert(key: number, value: number): void {\n const node: FibNode = {\n key,\n value,\n degree: 0,\n mark: false,\n parent: null,\n child: null,\n left: null as any,\n right: null as any,\n };\n node.left = node;\n node.right = node;\n\n this.minNode = this.mergeLists(this.minNode, node);\n this.nodeCount++;\n }\n\n extractMin(): number | null {\n const z = this.minNode;\n if (!z) return null;\n\n // Add children to root list\n if (z.child) {\n let child = z.child;\n do {\n child.parent = null;\n child = child.right!;\n } while (child !== z.child);\n this.minNode = this.mergeLists(this.minNode, z.child);\n }\n\n this.removeFromList(z);\n\n if (z === z.right) {\n this.minNode = null;\n } else {\n this.minNode = z.right;\n this.consolidate();\n }\n\n this.nodeCount--;\n return z.value;\n }\n\n size(): number {\n return this.nodeCount;\n }\n\n // ========== Internal Methods ==========\n\n private consolidate(): void {\n const maxDegree = Math.floor(Math.log2(this.nodeCount)) + 1;\n const A = new Array<FibNode | null>(maxDegree).fill(null);\n\n const rootList: FibNode[] = [];\n let curr = this.minNode!;\n do {\n rootList.push(curr);\n curr = curr.right!;\n } while (curr !== this.minNode);\n\n for (const w of rootList) {\n let x = w;\n let d = x.degree;\n while (A[d]) {\n let y = A[d]!;\n if (x.key > y.key) {\n const temp = x;\n x = y;\n y = temp;\n }\n this.link(y, x);\n A[d] = null;\n d++;\n }\n A[d] = x;\n }\n\n this.minNode = null;\n for (const node of A) {\n if (node) {\n this.minNode = this.mergeLists(this.minNode, node);\n }\n }\n }\n\n private link(y: FibNode, x: FibNode): void {\n this.removeFromList(y);\n y.left = y.right = y;\n x.child = this.mergeLists(x.child, y);\n y.parent = x;\n x.degree++;\n y.mark = false;\n }\n\n private mergeLists(a: FibNode | null, b: FibNode | null): FibNode {\n if (!a) return b!;\n if (!b) return a;\n\n const aRight = a.right!;\n const bRight = b.right!;\n\n a.right = bRight;\n bRight.left = a;\n b.right = aRight;\n aRight.left = b;\n\n return a.key < b.key ? a : b;\n }\n\n private removeFromList(node: FibNode): void {\n node.left.right = node.right;\n node.right.left = node.left;\n }\n}\n","import { Position } from \"geojson\";\n\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { FibonacciHeap } from \"./fibonacci-heap\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\n\n/**\n * TerraRoute is a routing utility for finding the shortest path\n * between two geographic points over a given GeoJSON LineString network.\n *\n * The class builds an internal graph structure based on the provided network,\n * then applies A* algorithm to compute the shortest route.\n */\nclass TerraRoute {\n private network: FeatureCollection<LineString> | undefined;\n private distanceMeasurement: (positionA: Position, positionB: Position) => number;\n private adjacencyList: Map<number, Array<{ node: number; distance: number }>> = new Map();\n private coords: Position[] = []\n private coordMap: Map<number, Map<number, number>> = new Map();\n\n /**\n * Creates a new instance of TerraRoute.\n * \n * @param distanceMeasurement - Optional custom distance measurement function (defaults to haversine distance).\n */\n constructor(\n distanceMeasurement?: (positionA: Position, positionB: Position) => number\n ) {\n this.distanceMeasurement = distanceMeasurement ? distanceMeasurement : haversineDistance;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n private coordinateIndex(coord: Position): number {\n const [lng, lat] = coord;\n if (!this.coordMap.has(lng)) this.coordMap.set(lng, new Map());\n\n const latMap = this.coordMap.get(lng)!;\n if (latMap.has(lat)) {\n return latMap.get(lat)!;\n }\n\n const index = this.coords.length;\n this.coords.push(coord);\n latMap.set(lat, index);\n\n return index;\n }\n\n /**\n * Builds the internal graph representation (adjacency list) from the input network.\n * Each LineString segment is translated into bidirectional graph edges with associated distances.\n * Assumes that the network is a connected graph of LineStrings with shared coordinates. Calling this \n * method with a new network overwrite any existing network and reset all internal data structures.\n * \n * @param network - A GeoJSON FeatureCollection of LineStrings representing the road network.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n this.adjacencyList = new Map();\n this.coords = [];\n this.coordMap = new Map();\n\n for (const feature of this.network.features) {\n const coords = feature.geometry.coordinates;\n for (let i = 0; i < coords.length - 1; i++) {\n const aIndex = this.coordinateIndex(coords[i]);\n const bIndex = this.coordinateIndex(coords[i + 1]);\n const distance = this.distanceMeasurement(coords[i], coords[i + 1]);\n\n if (!this.adjacencyList.has(aIndex)) this.adjacencyList.set(aIndex, []);\n if (!this.adjacencyList.has(bIndex)) this.adjacencyList.set(bIndex, []);\n\n this.adjacencyList.get(aIndex)!.push({ node: bIndex, distance });\n this.adjacencyList.get(bIndex)!.push({ node: aIndex, distance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using bidirectional A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildRouteGraph(network) first.\");\n }\n\n const startIndex = this.coordinateIndex(start.geometry.coordinates);\n const endIndex = this.coordinateIndex(end.geometry.coordinates);\n\n if (startIndex === endIndex) {\n return null;\n }\n\n const openSetForward = new FibonacciHeap();\n const openSetBackward = new FibonacciHeap();\n openSetForward.insert(0, startIndex);\n openSetBackward.insert(0, endIndex);\n\n const cameFromForward = new Map<number, number>();\n const cameFromBackward = new Map<number, number>();\n const gScoreForward = new Map<number, number>([[startIndex, 0]]);\n const gScoreBackward = new Map<number, number>([[endIndex, 0]]);\n\n const visitedForward = new Set<number>();\n const visitedBackward = new Set<number>();\n\n let meetingNode: number | null = null;\n\n while (openSetForward.size() > 0 && openSetBackward.size() > 0) {\n const currentForward = openSetForward.extractMin()!;\n visitedForward.add(currentForward);\n\n if (visitedBackward.has(currentForward)) {\n meetingNode = currentForward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentForward) || []) {\n const tentativeG = (gScoreForward.get(currentForward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreForward.get(neighbor.node) ?? Infinity)) {\n cameFromForward.set(neighbor.node, currentForward);\n gScoreForward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[endIndex]);\n openSetForward.insert(fScore, neighbor.node);\n }\n }\n\n const currentBackward = openSetBackward.extractMin()!;\n visitedBackward.add(currentBackward);\n\n if (visitedForward.has(currentBackward)) {\n meetingNode = currentBackward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentBackward) || []) {\n const tentativeG = (gScoreBackward.get(currentBackward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreBackward.get(neighbor.node) ?? Infinity)) {\n cameFromBackward.set(neighbor.node, currentBackward);\n gScoreBackward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[startIndex]);\n openSetBackward.insert(fScore, neighbor.node);\n }\n }\n }\n\n if (meetingNode === null) {\n return null;\n }\n\n // Reconstruct forward path\n const pathForward: Position[] = [];\n let node = meetingNode;\n while (node !== undefined) {\n pathForward.unshift(this.coords[node]);\n node = cameFromForward.get(node)!;\n }\n\n // Reconstruct backward path (omit meeting node to avoid duplication)\n const pathBackward: Position[] = [];\n node = cameFromBackward.get(meetingNode)!;\n while (node !== undefined) {\n pathBackward.push(this.coords[node]);\n node = cameFromBackward.get(node)!;\n }\n\n const fullPath = [...pathForward, ...pathBackward];\n\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: fullPath },\n properties: {},\n };\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}"],"names":["FibonacciHeap","this","nodeCount","minNode","_proto","prototype","insert","key","value","node","degree","mark","parent","child","left","right","mergeLists","extractMin","z","removeFromList","consolidate","size","maxDegree","Math","floor","log2","A","Array","fill","rootList","curr","push","_i","_rootList","length","x","d","y","temp","link","_step","_iterator","_createForOfIteratorHelperLoose","done","a","b","aRight","bRight","haversineDistance","pointOne","pointTwo","toRadians","latOrLng","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","sin","cos","atan2","sqrt","TerraRoute","distanceMeasurement","network","adjacencyList","Map","coords","coordMap","coordinateIndex","coord","lng","lat","has","set","latMap","get","index","buildRouteGraph","features","geometry","coordinates","i","aIndex","bIndex","distance","getRoute","start","end","Error","startIndex","endIndex","openSetForward","openSetBackward","cameFromForward","cameFromBackward","gScoreForward","gScoreBackward","visitedForward","Set","visitedBackward","meetingNode","currentForward","add","_iterator2","_step2","_gScoreForward$get","_gScoreForward$get2","neighbor","tentativeG","Infinity","fScore","currentBackward","_step3","_iterator3","_gScoreBackward$get","_gScoreBackward$get2","pathForward","undefined","unshift","pathBackward","type","concat","properties","FE","E2","RAD","cosLat","w2","w","m","kx","ky","deltaLng","dx","dy"],"mappings":"oyBAWA,IAAaA,eAAa,WAAA,SAAAA,IAAAC,KACdC,UAAY,EACZC,KAAAA,QAA0B,IAAI,CAAA,IAAAC,EAAAJ,EAAAK,iBAAAD,EAEtCE,OAAA,SAAOC,EAAaC,GAChB,IAAMC,EAAgB,CAClBF,IAAAA,EACAC,MAAAA,EACAE,OAAQ,EACRC,MAAM,EACNC,OAAQ,KACRC,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BA,EAAOuF,EAAiBnB,IAAIpE,GAKhC,MAAO,CACHiH,KAAM,UACNzC,SAAU,CAAEyC,KAAM,aAAcxC,YAJtB,GAAAyC,OAAOL,EAAgBG,IAKjCG,WAAY,CAAA,EAEpB,EAAC7D,CAAA,CA5KW,4BCoBV,SAA2BU,GAC7B,IACMoD,EAAK,EAAI,cACTC,EAAKD,GAAM,EAAIA,GACfE,EAAMxG,KAAK8B,GAAK,IAEhB2E,EAASzG,KAAKqC,IAAIa,EAAMsD,GACxBE,EAAK,GAAK,EAAIH,GAAM,EAAIE,EAASA,IACjCE,EAAI3G,KAAKuC,KAAKmE,GAEdE,EATK,SASDJ,EACJK,EAAKD,EAAID,EAAIF,EACbK,EAAKF,EAAID,EAAID,GAAM,EAAIH,GAE7B,OAAgB,SAASlF,EAAaC,GAGlC,IAFA,IAAIyF,EAAW1F,EAAE,GAAKC,EAAE,GAEjByF,GAAY,KAAKA,GAAY,IACpC,KAAOA,EAAW,KAAKA,GAAY,IAEnC,IAAMC,EAAKD,EAAWF,EAChBI,GAAM5F,EAAE,GAAKC,EAAE,IAAMwF,EAE3B,OAAO9G,KAAKuC,KAAKyE,EAAKA,EAAKC,EAAKA,EACpC,CACJ"}
|
package/dist/terra-route.d.ts
CHANGED
|
@@ -38,7 +38,7 @@ declare class TerraRoute {
|
|
|
38
38
|
*/
|
|
39
39
|
buildRouteGraph(network: FeatureCollection<LineString>): void;
|
|
40
40
|
/**
|
|
41
|
-
* Computes the shortest route between two points in the network using A* algorithm.
|
|
41
|
+
* Computes the shortest route between two points in the network using bidirectional A* algorithm.
|
|
42
42
|
*
|
|
43
43
|
* @param start - A GeoJSON Point Feature representing the start location.
|
|
44
44
|
* @param end - A GeoJSON Point Feature representing the end location.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
class t{constructor(){this.
|
|
1
|
+
class t{constructor(){this.nodeCount=0,this.minNode=null}insert(t,e){const n={key:t,value:e,degree:0,mark:!1,parent:null,child:null,left:null,right:null};n.left=n,n.right=n,this.minNode=this.mergeLists(this.minNode,n),this.nodeCount++}extractMin(){const t=this.minNode;if(!t)return null;if(t.child){let e=t.child;do{e.parent=null,e=e.right}while(e!==t.child);this.minNode=this.mergeLists(this.minNode,t.child)}return this.removeFromList(t),t===t.right?this.minNode=null:(this.minNode=t.right,this.consolidate()),this.nodeCount--,t.value}size(){return this.nodeCount}consolidate(){const t=Math.floor(Math.log2(this.nodeCount))+1,e=new Array(t).fill(null),n=[];let s=this.minNode;do{n.push(s),s=s.right}while(s!==this.minNode);for(const t of n){let n=t,s=n.degree;for(;e[s];){let t=e[s];if(n.key>t.key){const e=n;n=t,t=e}this.link(t,n),e[s]=null,s++}e[s]=n}this.minNode=null;for(const t of e)t&&(this.minNode=this.mergeLists(this.minNode,t))}link(t,e){this.removeFromList(t),t.left=t.right=t,e.child=this.mergeLists(e.child,t),t.parent=e,e.degree++,t.mark=!1}mergeLists(t,e){if(!t)return e;if(!e)return t;const n=t.right,s=e.right;return t.right=s,s.left=t,e.right=n,n.left=e,t.key<e.key?t:e}removeFromList(t){t.left.right=t.right,t.right.left=t.left}}const e=(t,e)=>{const n=t=>t*Math.PI/180,s=n(t[1]),i=n(t[0]),o=n(e[1]),r=o-s,h=n(e[0])-i,a=Math.sin(r/2)*Math.sin(r/2)+Math.cos(s)*Math.cos(o)*Math.sin(h/2)*Math.sin(h/2);return 2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))*6371e3/1e3};function n(t){const e=1/298.257223563,n=e*(2-e),s=Math.PI/180,i=Math.cos(t*s),o=1/(1-n*(1-i*i)),r=Math.sqrt(o),h=6378.137*s,a=h*r*i,c=h*r*o*(1-n);return function(t,e){let n=t[0]-e[0];for(;n<-180;)n+=360;for(;n>180;)n-=360;const s=n*a,i=(t[1]-e[1])*c;return Math.sqrt(s*s+i*i)}}class s{constructor(t){this.network=void 0,this.distanceMeasurement=void 0,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map,this.distanceMeasurement=t||e}coordinateIndex(t){const[e,n]=t;this.coordMap.has(e)||this.coordMap.set(e,new Map);const s=this.coordMap.get(e);if(s.has(n))return s.get(n);const i=this.coords.length;return this.coords.push(t),s.set(n,i),i}buildRouteGraph(t){this.network=t,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map;for(const t of this.network.features){const e=t.geometry.coordinates;for(let t=0;t<e.length-1;t++){const n=this.coordinateIndex(e[t]),s=this.coordinateIndex(e[t+1]),i=this.distanceMeasurement(e[t],e[t+1]);this.adjacencyList.has(n)||this.adjacencyList.set(n,[]),this.adjacencyList.has(s)||this.adjacencyList.set(s,[]),this.adjacencyList.get(n).push({node:s,distance:i}),this.adjacencyList.get(s).push({node:n,distance:i})}}}getRoute(e,n){if(!this.network)throw new Error("Network not built. Please call buildRouteGraph(network) first.");const s=this.coordinateIndex(e.geometry.coordinates),i=this.coordinateIndex(n.geometry.coordinates);if(s===i)return null;const o=new t,r=new t;o.insert(0,s),r.insert(0,i);const h=new Map,a=new Map,c=new Map([[s,0]]),d=new Map([[i,0]]),l=new Set,u=new Set;let f=null;for(;o.size()>0&&r.size()>0;){const t=o.extractMin();if(l.add(t),u.has(t)){f=t;break}for(const e of this.adjacencyList.get(t)||[]){var g,M;const n=(null!=(g=c.get(t))?g:Infinity)+e.distance;if(n<(null!=(M=c.get(e.node))?M:Infinity)){h.set(e.node,t),c.set(e.node,n);const s=n+this.distanceMeasurement(this.coords[e.node],this.coords[i]);o.insert(s,e.node)}}const e=r.extractMin();if(u.add(e),l.has(e)){f=e;break}for(const t of this.adjacencyList.get(e)||[]){var m,p;const n=(null!=(m=d.get(e))?m:Infinity)+t.distance;if(n<(null!=(p=d.get(t.node))?p:Infinity)){a.set(t.node,e),d.set(t.node,n);const i=n+this.distanceMeasurement(this.coords[t.node],this.coords[s]);r.insert(i,t.node)}}}if(null===f)return null;const y=[];let w=f;for(;void 0!==w;)y.unshift(this.coords[w]),w=h.get(w);const L=[];for(w=a.get(f);void 0!==w;)L.push(this.coords[w]),w=a.get(w);return{type:"Feature",geometry:{type:"LineString",coordinates:[...y,...L]},properties:{}}}}export{s as TerraRoute,n as createCheapRuler,e as haversineDistance};
|
|
2
2
|
//# sourceMappingURL=terra-route.modern.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"terra-route.modern.js","sources":["../src/min-heap.ts","../src/distance/haversine.ts","../src/distance/cheap-ruler.ts","../src/terra-route.ts"],"sourcesContent":["export class MinHeap {\n private heap: Array<{ key: number; value: number; index: number }> = [];\n private insertCounter = 0;\n\n insert(key: number, value: number): void {\n const node = { key, value, index: this.insertCounter++ };\n let idx = this.heap.length;\n this.heap.push(node);\n\n // Optimized Bubble Up\n while (idx > 0) {\n const parentIdx = (idx - 1) >>> 1; // Fast Math.floor((idx - 1) / 2)\n const parent = this.heap[parentIdx];\n if (node.key > parent.key || (node.key === parent.key && node.index > parent.index)) break;\n this.heap[idx] = parent;\n idx = parentIdx;\n }\n this.heap[idx] = node;\n }\n\n extractMin(): number | null {\n const length = this.heap.length;\n if (length === 0) return null;\n\n const minNode = this.heap[0];\n const endNode = this.heap.pop()!;\n\n if (length > 1) {\n this.heap[0] = endNode;\n this.bubbleDown(0);\n }\n\n return minNode.value;\n }\n\n size(): number {\n return this.heap.length;\n }\n\n private bubbleDown(idx: number): void {\n const { heap } = this;\n const length = heap.length;\n // Grab the parent node once, then move it down only if needed\n const node = heap[idx];\n const nodeKey = node.key;\n const nodeIndex = node.index;\n\n while (true) {\n // Calculate left and right child indexes\n const leftIdx = (idx << 1) + 1;\n if (leftIdx >= length) {\n // No children => we’re already in place\n break;\n }\n\n // Assume left child is the smaller one by default\n let smallestIdx = leftIdx;\n let smallestKey = heap[leftIdx].key;\n let smallestIndex = heap[leftIdx].index;\n\n const rightIdx = leftIdx + 1;\n if (rightIdx < length) {\n // Compare left child vs. right child\n const rightKey = heap[rightIdx].key;\n const rightIndex = heap[rightIdx].index;\n if (rightKey < smallestKey || (rightKey === smallestKey && rightIndex < smallestIndex)) {\n smallestIdx = rightIdx;\n smallestKey = rightKey;\n smallestIndex = rightIndex;\n }\n }\n\n // Compare the smaller child with the parent\n if (smallestKey < nodeKey || (smallestKey === nodeKey && smallestIndex < nodeIndex)) {\n // Swap the smaller child up\n heap[idx] = heap[smallestIdx];\n idx = smallestIdx;\n } else {\n // We’re in the correct position now, so stop\n break;\n }\n }\n\n // Place the original node in its final position\n heap[idx] = node;\n }\n}\n","import { Position } from \"geojson\";\n\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { MinHeap } from \"./min-heap\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\n\n/**\n * TerraRoute is a routing utility for finding the shortest path\n * between two geographic points over a given GeoJSON LineString network.\n *\n * The class builds an internal graph structure based on the provided network,\n * then applies A* algorithm to compute the shortest route.\n */\nclass TerraRoute {\n private network: FeatureCollection<LineString> | undefined;\n private distanceMeasurement: (positionA: Position, positionB: Position) => number;\n private adjacencyList: Map<number, Array<{ node: number; distance: number }>> = new Map();\n private coords: Position[] = []\n private coordMap: Map<number, Map<number, number>> = new Map();\n\n /**\n * Creates a new instance of TerraRoute.\n * \n * @param distanceMeasurement - Optional custom distance measurement function (defaults to haversine distance).\n */\n constructor(\n distanceMeasurement?: (positionA: Position, positionB: Position) => number\n ) {\n this.distanceMeasurement = distanceMeasurement ? distanceMeasurement : haversineDistance;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n private coordinateIndex(coord: Position): number {\n const [lng, lat] = coord;\n if (!this.coordMap.has(lng)) this.coordMap.set(lng, new Map());\n\n const latMap = this.coordMap.get(lng)!;\n if (latMap.has(lat)) {\n return latMap.get(lat)!;\n }\n\n const idx = this.coords.length;\n this.coords.push(coord);\n latMap.set(lat, idx);\n\n return idx;\n }\n\n /**\n * Builds the internal graph representation (adjacency list) from the input network.\n * Each LineString segment is translated into bidirectional graph edges with associated distances.\n * Assumes that the network is a connected graph of LineStrings with shared coordinates. Calling this \n * method with a new network overwrite any existing network and reset all internal data structures.\n * \n * @param network - A GeoJSON FeatureCollection of LineStrings representing the road network.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n this.adjacencyList = new Map();\n this.coords = [];\n this.coordMap = new Map();\n\n for (const feature of this.network.features) {\n const coords = feature.geometry.coordinates;\n for (let i = 0; i < coords.length - 1; i++) {\n const aIdx = this.coordinateIndex(coords[i]);\n const bIdx = this.coordinateIndex(coords[i + 1]);\n const distance = this.distanceMeasurement(coords[i], coords[i + 1]);\n\n if (!this.adjacencyList.has(aIdx)) this.adjacencyList.set(aIdx, []);\n if (!this.adjacencyList.has(bIdx)) this.adjacencyList.set(bIdx, []);\n\n this.adjacencyList.get(aIdx)!.push({ node: bIdx, distance });\n this.adjacencyList.get(bIdx)!.push({ node: aIdx, distance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildNetworkGraph(network) first.\");\n }\n\n const startIdx = this.coordinateIndex(start.geometry.coordinates);\n const endIdx = this.coordinateIndex(end.geometry.coordinates);\n\n if (startIdx === endIdx) {\n return null;\n }\n\n const openSet = new MinHeap();\n openSet.insert(0, startIdx);\n const cameFrom = new Map<number, number>();\n const gScore = new Map<number, number>([[startIdx, 0]]);\n\n while (openSet.size() > 0) {\n const current = openSet.extractMin()!;\n\n if (current === endIdx) {\n const path: Position[] = [];\n let currNode: number | undefined = current;\n while (currNode !== undefined) {\n path.unshift(this.coords[currNode]);\n currNode = cameFrom.get(currNode);\n }\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: path },\n properties: {},\n };\n }\n\n const neighbors = this.adjacencyList.get(current) || [];\n\n for (const neighbor of neighbors) {\n const tentativeGScore = (gScore.get(current) ?? Infinity) + neighbor.distance;\n if (tentativeGScore < (gScore.get(neighbor.node) ?? Infinity)) {\n cameFrom.set(neighbor.node, current);\n gScore.set(neighbor.node, tentativeGScore);\n const fScore = tentativeGScore + this.distanceMeasurement(this.coords[neighbor.node], this.coords[endIdx]);\n openSet.insert(fScore, neighbor.node);\n }\n }\n }\n\n return null;\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }"],"names":["MinHeap","constructor","heap","insertCounter","insert","key","value","node","index","this","idx","length","push","parentIdx","parent","extractMin","minNode","endNode","pop","bubbleDown","size","nodeKey","nodeIndex","leftIdx","smallestIdx","smallestKey","smallestIndex","rightIdx","rightKey","rightIndex","haversineDistance","pointOne","pointTwo","toRadians","latOrLng","Math","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","a","sin","cos","atan2","sqrt","createCheapRuler","lat","FE","E2","RAD","cosLat","w2","w","m","kx","ky","b","deltaLng","dx","dy","TerraRoute","distanceMeasurement","network","adjacencyList","Map","coords","coordMap","coordinateIndex","coord","lng","has","set","latMap","get","buildRouteGraph","feature","features","geometry","coordinates","i","aIdx","bIdx","distance","getRoute","start","end","Error","startIdx","endIdx","openSet","cameFrom","gScore","current","path","currNode","undefined","unshift","type","properties","neighbors","neighbor","_gScore$get","_gScore$get2","tentativeGScore","Infinity","fScore"],"mappings":"MAAaA,EAAOC,WAAAA,GACRC,KAAAA,KAA6D,GAC7DC,KAAAA,cAAgB,CAAC,CAEzBC,MAAAA,CAAOC,EAAaC,GAChB,MAAMC,EAAO,CAAEF,MAAKC,QAAOE,MAAOC,KAAKN,iBACvC,IAAIO,EAAMD,KAAKP,KAAKS,OAIpB,IAHAF,KAAKP,KAAKU,KAAKL,GAGRG,EAAM,GAAG,CACZ,MAAMG,EAAaH,EAAM,IAAO,EAC1BI,EAASL,KAAKP,KAAKW,GACzB,GAAIN,EAAKF,IAAMS,EAAOT,KAAQE,EAAKF,MAAQS,EAAOT,KAAOE,EAAKC,MAAQM,EAAON,MAAQ,MACrFC,KAAKP,KAAKQ,GAAOI,EACjBJ,EAAMG,CACV,CACAJ,KAAKP,KAAKQ,GAAOH,CACrB,CAEAQ,UAAAA,GACI,MAAMJ,EAASF,KAAKP,KAAKS,OACzB,GAAe,IAAXA,EAAc,OAAW,KAE7B,MAAMK,EAAUP,KAAKP,KAAK,GACpBe,EAAUR,KAAKP,KAAKgB,MAO1B,OALIP,EAAS,IACTF,KAAKP,KAAK,GAAKe,EACfR,KAAKU,WAAW,IAGbH,EAAQV,KACnB,CAEAc,IAAAA,GACI,YAAYlB,KAAKS,MACrB,CAEQQ,UAAAA,CAAWT,GACf,MAAMR,KAAEA,GAASO,KACXE,EAAST,EAAKS,OAEdJ,EAAOL,EAAKQ,GACZW,EAAUd,EAAKF,IACfiB,EAAYf,EAAKC,MAEvB,OAAa,CAET,MAAM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AAeD,EAAIX,EAAOlB,IAAI2B,EAAS/F,OAAKiG,EAAIE,UAAW,CAC3Dd,EAASnB,IAAI6B,EAAS/F,KAAMuF,GAC5BD,EAAOpB,IAAI6B,EAAS/F,KAAMkG,GAC1B,MAAME,EAASF,EAAkBhG,KAAKsD,oBAAoBtD,KAAK0D,OAAOmC,EAAS/F,MAAOE,KAAK0D,OAAOuB,IAClGC,EAAQvF,OAAOuG,EAAQL,EAAS/F,KACpC,CACJ,CACJ,CAEA,OAAO,IACX"}
|
|
1
|
+
{"version":3,"file":"terra-route.modern.js","sources":["../src/fibonacci-heap.ts","../src/distance/haversine.ts","../src/distance/cheap-ruler.ts","../src/terra-route.ts"],"sourcesContent":["type FibNode = {\n key: number;\n value: number;\n degree: number;\n mark: boolean;\n parent: FibNode | null;\n child: FibNode | null;\n left: FibNode;\n right: FibNode;\n};\n\nexport class FibonacciHeap {\n private nodeCount = 0;\n private minNode: FibNode | null = null;\n\n insert(key: number, value: number): void {\n const node: FibNode = {\n key,\n value,\n degree: 0,\n mark: false,\n parent: null,\n child: null,\n left: null as any,\n right: null as any,\n };\n node.left = node;\n node.right = node;\n\n this.minNode = this.mergeLists(this.minNode, node);\n this.nodeCount++;\n }\n\n extractMin(): number | null {\n const z = this.minNode;\n if (!z) return null;\n\n // Add children to root list\n if (z.child) {\n let child = z.child;\n do {\n child.parent = null;\n child = child.right!;\n } while (child !== z.child);\n this.minNode = this.mergeLists(this.minNode, z.child);\n }\n\n this.removeFromList(z);\n\n if (z === z.right) {\n this.minNode = null;\n } else {\n this.minNode = z.right;\n this.consolidate();\n }\n\n this.nodeCount--;\n return z.value;\n }\n\n size(): number {\n return this.nodeCount;\n }\n\n // ========== Internal Methods ==========\n\n private consolidate(): void {\n const maxDegree = Math.floor(Math.log2(this.nodeCount)) + 1;\n const A = new Array<FibNode | null>(maxDegree).fill(null);\n\n const rootList: FibNode[] = [];\n let curr = this.minNode!;\n do {\n rootList.push(curr);\n curr = curr.right!;\n } while (curr !== this.minNode);\n\n for (const w of rootList) {\n let x = w;\n let d = x.degree;\n while (A[d]) {\n let y = A[d]!;\n if (x.key > y.key) {\n const temp = x;\n x = y;\n y = temp;\n }\n this.link(y, x);\n A[d] = null;\n d++;\n }\n A[d] = x;\n }\n\n this.minNode = null;\n for (const node of A) {\n if (node) {\n this.minNode = this.mergeLists(this.minNode, node);\n }\n }\n }\n\n private link(y: FibNode, x: FibNode): void {\n this.removeFromList(y);\n y.left = y.right = y;\n x.child = this.mergeLists(x.child, y);\n y.parent = x;\n x.degree++;\n y.mark = false;\n }\n\n private mergeLists(a: FibNode | null, b: FibNode | null): FibNode {\n if (!a) return b!;\n if (!b) return a;\n\n const aRight = a.right!;\n const bRight = b.right!;\n\n a.right = bRight;\n bRight.left = a;\n b.right = aRight;\n aRight.left = b;\n\n return a.key < b.key ? a : b;\n }\n\n private removeFromList(node: FibNode): void {\n node.left.right = node.right;\n node.right.left = node.left;\n }\n}\n","import { Position } from \"geojson\";\n\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { FibonacciHeap } from \"./fibonacci-heap\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\n\n/**\n * TerraRoute is a routing utility for finding the shortest path\n * between two geographic points over a given GeoJSON LineString network.\n *\n * The class builds an internal graph structure based on the provided network,\n * then applies A* algorithm to compute the shortest route.\n */\nclass TerraRoute {\n private network: FeatureCollection<LineString> | undefined;\n private distanceMeasurement: (positionA: Position, positionB: Position) => number;\n private adjacencyList: Map<number, Array<{ node: number; distance: number }>> = new Map();\n private coords: Position[] = []\n private coordMap: Map<number, Map<number, number>> = new Map();\n\n /**\n * Creates a new instance of TerraRoute.\n * \n * @param distanceMeasurement - Optional custom distance measurement function (defaults to haversine distance).\n */\n constructor(\n distanceMeasurement?: (positionA: Position, positionB: Position) => number\n ) {\n this.distanceMeasurement = distanceMeasurement ? distanceMeasurement : haversineDistance;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n private coordinateIndex(coord: Position): number {\n const [lng, lat] = coord;\n if (!this.coordMap.has(lng)) this.coordMap.set(lng, new Map());\n\n const latMap = this.coordMap.get(lng)!;\n if (latMap.has(lat)) {\n return latMap.get(lat)!;\n }\n\n const index = this.coords.length;\n this.coords.push(coord);\n latMap.set(lat, index);\n\n return index;\n }\n\n /**\n * Builds the internal graph representation (adjacency list) from the input network.\n * Each LineString segment is translated into bidirectional graph edges with associated distances.\n * Assumes that the network is a connected graph of LineStrings with shared coordinates. Calling this \n * method with a new network overwrite any existing network and reset all internal data structures.\n * \n * @param network - A GeoJSON FeatureCollection of LineStrings representing the road network.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n this.adjacencyList = new Map();\n this.coords = [];\n this.coordMap = new Map();\n\n for (const feature of this.network.features) {\n const coords = feature.geometry.coordinates;\n for (let i = 0; i < coords.length - 1; i++) {\n const aIndex = this.coordinateIndex(coords[i]);\n const bIndex = this.coordinateIndex(coords[i + 1]);\n const distance = this.distanceMeasurement(coords[i], coords[i + 1]);\n\n if (!this.adjacencyList.has(aIndex)) this.adjacencyList.set(aIndex, []);\n if (!this.adjacencyList.has(bIndex)) this.adjacencyList.set(bIndex, []);\n\n this.adjacencyList.get(aIndex)!.push({ node: bIndex, distance });\n this.adjacencyList.get(bIndex)!.push({ node: aIndex, distance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using bidirectional A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildRouteGraph(network) first.\");\n }\n\n const startIndex = this.coordinateIndex(start.geometry.coordinates);\n const endIndex = this.coordinateIndex(end.geometry.coordinates);\n\n if (startIndex === endIndex) {\n return null;\n }\n\n const openSetForward = new FibonacciHeap();\n const openSetBackward = new FibonacciHeap();\n openSetForward.insert(0, startIndex);\n openSetBackward.insert(0, endIndex);\n\n const cameFromForward = new Map<number, number>();\n const cameFromBackward = new Map<number, number>();\n const gScoreForward = new Map<number, number>([[startIndex, 0]]);\n const gScoreBackward = new Map<number, number>([[endIndex, 0]]);\n\n const visitedForward = new Set<number>();\n const visitedBackward = new Set<number>();\n\n let meetingNode: number | null = null;\n\n while (openSetForward.size() > 0 && openSetBackward.size() > 0) {\n const currentForward = openSetForward.extractMin()!;\n visitedForward.add(currentForward);\n\n if (visitedBackward.has(currentForward)) {\n meetingNode = currentForward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentForward) || []) {\n const tentativeG = (gScoreForward.get(currentForward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreForward.get(neighbor.node) ?? Infinity)) {\n cameFromForward.set(neighbor.node, currentForward);\n gScoreForward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[endIndex]);\n openSetForward.insert(fScore, neighbor.node);\n }\n }\n\n const currentBackward = openSetBackward.extractMin()!;\n visitedBackward.add(currentBackward);\n\n if (visitedForward.has(currentBackward)) {\n meetingNode = currentBackward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentBackward) || []) {\n const tentativeG = (gScoreBackward.get(currentBackward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreBackward.get(neighbor.node) ?? Infinity)) {\n cameFromBackward.set(neighbor.node, currentBackward);\n gScoreBackward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[startIndex]);\n openSetBackward.insert(fScore, neighbor.node);\n }\n }\n }\n\n if (meetingNode === null) {\n return null;\n }\n\n // Reconstruct forward path\n const pathForward: Position[] = [];\n let node = meetingNode;\n while (node !== undefined) {\n pathForward.unshift(this.coords[node]);\n node = cameFromForward.get(node)!;\n }\n\n // Reconstruct backward path (omit meeting node to avoid duplication)\n const pathBackward: Position[] = [];\n node = cameFromBackward.get(meetingNode)!;\n while (node !== undefined) {\n pathBackward.push(this.coords[node]);\n node = cameFromBackward.get(node)!;\n }\n\n const fullPath = [...pathForward, ...pathBackward];\n\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: fullPath },\n properties: {},\n };\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }"],"names":["FibonacciHeap","constructor","nodeCount","minNode","insert","key","value","node","degree","mark","parent","child","left","right","this","mergeLists","extractMin","z","removeFromList","consolidate","size","maxDegree","Math","floor","log2","A","Array","fill","rootList","curr","push","w","x","d","y","temp","link","a","b","aRight","bRight","haversineDistance","pointOne","pointTwo","toRadians","latOrLng","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","sin","cos","atan2","sqrt","createCheapRuler","lat","FE","E2","RAD","cosLat","w2","m","kx","ky","deltaLng","dx","dy","TerraRoute","distanceMeasurement","network","adjacencyList","Map","coords","coordMap","coordinateIndex","coord","lng","has","set","latMap","get","index","length","buildRouteGraph","feature","features","geometry","coordinates","i","aIndex","bIndex","distance","getRoute","start","end","Error","startIndex","endIndex","openSetForward","openSetBackward","cameFromForward","cameFromBackward","gScoreForward","gScoreBackward","visitedForward","Set","visitedBackward","meetingNode","currentForward","add","neighbor","_gScoreForward$get","_gScoreForward$get2","tentativeG","Infinity","fScore","currentBackward","_gScoreBackward$get","_gScoreBackward$get2","pathForward","undefined","unshift","pathBackward","type","properties"],"mappings":"AAWa,MAAAA,EAAaC,WAAAA,GACdC,KAAAA,UAAY,EACZC,KAAAA,QAA0B,IAAI,CAEtCC,MAAAA,CAAOC,EAAaC,GAChB,MAAMC,EAAgB,CAClBF,MACAC,QACAE,OAAQ,EACRC,MAAM,EACNC,OAAQ,KACRC,MAAO,KACPC,KAAM,KACNC,MAAO,MAEXN,EAAKK,KAAOL,EACZA,EAAKM,MAAQN,EAEbO,KAAKX,QAAUW,KAAKC,WAAWD,KAAKX,QAASI,GAC7CO,KAAKZ,WACT,CAEAc,UAAAA,GACI,MAAMC,EAAIH,KAAKX,QACf,IAAKc,EAAG,OAAW,KAGnB,GAAIA,EAAEN,MAAO,CACT,IAAIA,EAAQM,EAAEN,MACd,GACIA,EAAMD,OAAS,KACfC,EAAQA,EAAME,YACTF,IAAUM,EAAEN,OACrBG,KAAKX,QAAUW,KAAKC,WAAWD,KAAKX,QAASc,EAAEN,MACnD,CAYA,OAVAG,KAAKI,eAAeD,GAEhBA,IAAMA,EAAEJ,MACRC,KAAKX,QAAU,MAEfW,KAAKX,QAAUc,EAAEJ,MACjBC,KAAKK,eAGTL,KAAKZ,YACEe,EAAEX,KACb,CAEAc,IAAAA,GACI,YAAYlB,SAChB,CAIQiB,WAAAA,GACJ,MAAME,EAAYC,KAAKC,MAAMD,KAAKE,KAAKV,KAAKZ,YAAc,EACpDuB,EAAI,IAAIC,MA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AAAC,IAAAA,EAAAC,EAClE,MAAML,GAAiDI,OAApCA,EAACd,EAAevB,IAAIoC,IAAgBC,EAAIH,UAAYJ,EAASnB,SAChF,GAAIsB,GAA+C,OAArCK,EAAIf,EAAevB,IAAI8B,EAASzG,OAAKiH,EAAIJ,UAAW,CAC9Db,EAAiBvB,IAAIgC,EAASzG,KAAM+G,GACpCb,EAAezB,IAAIgC,EAASzG,KAAM4G,GAClC,MAAME,EAASF,EAAarG,KAAKwD,oBAAoBxD,KAAK4D,OAAOsC,EAASzG,MAAOO,KAAK4D,OAAOwB,IAC7FG,EAAgBjG,OAAOiH,EAAQL,EAASzG,KAC5C,CACJ,CACJ,CAEA,GAAoB,OAAhBsG,EACA,OACJ,KAGA,MAAMY,EAA0B,GAChC,IAAIlH,EAAOsG,EACX,UAAgBa,IAATnH,GACHkH,EAAYE,QAAQ7G,KAAK4D,OAAOnE,IAChCA,EAAO+F,EAAgBpB,IAAI3E,GAI/B,MAAMqH,EAA2B,GAEjC,IADArH,EAAOgG,EAAiBrB,IAAI2B,QACZa,IAATnH,GACHqH,EAAa9F,KAAKhB,KAAK4D,OAAOnE,IAC9BA,EAAOgG,EAAiBrB,IAAI3E,GAKhC,MAAO,CACHsH,KAAM,UACNrC,SAAU,CAAEqC,KAAM,aAAcpC,YAJnB,IAAIgC,KAAgBG,IAKjCE,WAAY,GAEpB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var
|
|
1
|
+
function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function e(e,n){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,n){if(e){if("string"==typeof e)return t(e,n);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(e,n):void 0}}(e))||n&&e&&"number"==typeof e.length){r&&(e=r);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n=/*#__PURE__*/function(){function t(){this.nodeCount=0,this.minNode=null}var n=t.prototype;return n.insert=function(t,e){var n={key:t,value:e,degree:0,mark:!1,parent:null,child:null,left:null,right:null};n.left=n,n.right=n,this.minNode=this.mergeLists(this.minNode,n),this.nodeCount++},n.extractMin=function(){var t=this.minNode;if(!t)return null;if(t.child){var e=t.child;do{e.parent=null,e=e.right}while(e!==t.child);this.minNode=this.mergeLists(this.minNode,t.child)}return this.removeFromList(t),t===t.right?this.minNode=null:(this.minNode=t.right,this.consolidate()),this.nodeCount--,t.value},n.size=function(){return this.nodeCount},n.consolidate=function(){var t=Math.floor(Math.log2(this.nodeCount))+1,n=new Array(t).fill(null),r=[],i=this.minNode;do{r.push(i),i=i.right}while(i!==this.minNode);for(var o=0,a=r;o<a.length;o++){for(var s=a[o],h=s.degree;n[h];){var d=n[h];if(s.key>d.key){var c=s;s=d,d=c}this.link(d,s),n[h]=null,h++}n[h]=s}this.minNode=null;for(var u,l=e(n);!(u=l()).done;){var f=u.value;f&&(this.minNode=this.mergeLists(this.minNode,f))}},n.link=function(t,e){this.removeFromList(t),t.left=t.right=t,e.child=this.mergeLists(e.child,t),t.parent=e,e.degree++,t.mark=!1},n.mergeLists=function(t,e){if(!t)return e;if(!e)return t;var n=t.right,r=e.right;return t.right=r,r.left=t,e.right=n,n.left=e,t.key<e.key?t:e},n.removeFromList=function(t){t.left.right=t.right,t.right.left=t.left},t}(),r=function(t,e){var n=function(t){return t*Math.PI/180},r=n(t[1]),i=n(t[0]),o=n(e[1]),a=o-r,s=n(e[0])-i,h=Math.sin(a/2)*Math.sin(a/2)+Math.cos(r)*Math.cos(o)*Math.sin(s/2)*Math.sin(s/2);return 2*Math.atan2(Math.sqrt(h),Math.sqrt(1-h))*6371e3/1e3};function i(t){var e=1/298.257223563,n=e*(2-e),r=Math.PI/180,i=Math.cos(t*r),o=1/(1-n*(1-i*i)),a=Math.sqrt(o),s=6378.137*r,h=s*a*i,d=s*a*o*(1-n);return function(t,e){for(var n=t[0]-e[0];n<-180;)n+=360;for(;n>180;)n-=360;var r=n*h,i=(t[1]-e[1])*d;return Math.sqrt(r*r+i*i)}}var o=/*#__PURE__*/function(){function t(t){this.network=void 0,this.distanceMeasurement=void 0,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map,this.distanceMeasurement=t||r}var i=t.prototype;return i.coordinateIndex=function(t){var e=t[0],n=t[1];this.coordMap.has(e)||this.coordMap.set(e,new Map);var r=this.coordMap.get(e);if(r.has(n))return r.get(n);var i=this.coords.length;return this.coords.push(t),r.set(n,i),i},i.buildRouteGraph=function(t){this.network=t,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map;for(var n,r=e(this.network.features);!(n=r()).done;)for(var i=n.value.geometry.coordinates,o=0;o<i.length-1;o++){var a=this.coordinateIndex(i[o]),s=this.coordinateIndex(i[o+1]),h=this.distanceMeasurement(i[o],i[o+1]);this.adjacencyList.has(a)||this.adjacencyList.set(a,[]),this.adjacencyList.has(s)||this.adjacencyList.set(s,[]),this.adjacencyList.get(a).push({node:s,distance:h}),this.adjacencyList.get(s).push({node:a,distance:h})}},i.getRoute=function(t,r){if(!this.network)throw new Error("Network not built. Please call buildRouteGraph(network) first.");var i=this.coordinateIndex(t.geometry.coordinates),o=this.coordinateIndex(r.geometry.coordinates);if(i===o)return null;var a=new n,s=new n;a.insert(0,i),s.insert(0,o);for(var h=new Map,d=new Map,c=new Map([[i,0]]),u=new Map([[o,0]]),l=new Set,f=new Set,v=null;a.size()>0&&s.size()>0;){var g=a.extractMin();if(l.add(g),f.has(g)){v=g;break}for(var m,y=e(this.adjacencyList.get(g)||[]);!(m=y()).done;){var p,M,w=m.value,L=(null!=(p=c.get(g))?p:Infinity)+w.distance;if(L<(null!=(M=c.get(w.node))?M:Infinity)){h.set(w.node,g),c.set(w.node,L);var k=L+this.distanceMeasurement(this.coords[w.node],this.coords[o]);a.insert(k,w.node)}}var b=s.extractMin();if(f.add(b),l.has(b)){v=b;break}for(var I,N=e(this.adjacencyList.get(b)||[]);!(I=N()).done;){var j,x,S=I.value,A=(null!=(j=u.get(b))?j:Infinity)+S.distance;if(A<(null!=(x=u.get(S.node))?x:Infinity)){d.set(S.node,b),u.set(S.node,A);var C=A+this.distanceMeasurement(this.coords[S.node],this.coords[i]);s.insert(C,S.node)}}}if(null===v)return null;for(var q=[],F=v;void 0!==F;)q.unshift(this.coords[F]),F=h.get(F);var z=[];for(F=d.get(v);void 0!==F;)z.push(this.coords[F]),F=d.get(F);return{type:"Feature",geometry:{type:"LineString",coordinates:[].concat(q,z)},properties:{}}},t}();export{o as TerraRoute,i as createCheapRuler,r as haversineDistance};
|
|
2
2
|
//# sourceMappingURL=terra-route.module.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"terra-route.module.js","sources":["../src/min-heap.ts","../src/distance/haversine.ts","../src/distance/cheap-ruler.ts","../src/terra-route.ts"],"sourcesContent":["export class MinHeap {\n private heap: Array<{ key: number; value: number; index: number }> = [];\n private insertCounter = 0;\n\n insert(key: number, value: number): void {\n const node = { key, value, index: this.insertCounter++ };\n let idx = this.heap.length;\n this.heap.push(node);\n\n // Optimized Bubble Up\n while (idx > 0) {\n const parentIdx = (idx - 1) >>> 1; // Fast Math.floor((idx - 1) / 2)\n const parent = this.heap[parentIdx];\n if (node.key > parent.key || (node.key === parent.key && node.index > parent.index)) break;\n this.heap[idx] = parent;\n idx = parentIdx;\n }\n this.heap[idx] = node;\n }\n\n extractMin(): number | null {\n const length = this.heap.length;\n if (length === 0) return null;\n\n const minNode = this.heap[0];\n const endNode = this.heap.pop()!;\n\n if (length > 1) {\n this.heap[0] = endNode;\n this.bubbleDown(0);\n }\n\n return minNode.value;\n }\n\n size(): number {\n return this.heap.length;\n }\n\n private bubbleDown(idx: number): void {\n const { heap } = this;\n const length = heap.length;\n // Grab the parent node once, then move it down only if needed\n const node = heap[idx];\n const nodeKey = node.key;\n const nodeIndex = node.index;\n\n while (true) {\n // Calculate left and right child indexes\n const leftIdx = (idx << 1) + 1;\n if (leftIdx >= length) {\n // No children => we’re already in place\n break;\n }\n\n // Assume left child is the smaller one by default\n let smallestIdx = leftIdx;\n let smallestKey = heap[leftIdx].key;\n let smallestIndex = heap[leftIdx].index;\n\n const rightIdx = leftIdx + 1;\n if (rightIdx < length) {\n // Compare left child vs. right child\n const rightKey = heap[rightIdx].key;\n const rightIndex = heap[rightIdx].index;\n if (rightKey < smallestKey || (rightKey === smallestKey && rightIndex < smallestIndex)) {\n smallestIdx = rightIdx;\n smallestKey = rightKey;\n smallestIndex = rightIndex;\n }\n }\n\n // Compare the smaller child with the parent\n if (smallestKey < nodeKey || (smallestKey === nodeKey && smallestIndex < nodeIndex)) {\n // Swap the smaller child up\n heap[idx] = heap[smallestIdx];\n idx = smallestIdx;\n } else {\n // We’re in the correct position now, so stop\n break;\n }\n }\n\n // Place the original node in its final position\n heap[idx] = node;\n }\n}\n","import { Position } from \"geojson\";\n\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { MinHeap } from \"./min-heap\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\n\n/**\n * TerraRoute is a routing utility for finding the shortest path\n * between two geographic points over a given GeoJSON LineString network.\n *\n * The class builds an internal graph structure based on the provided network,\n * then applies A* algorithm to compute the shortest route.\n */\nclass TerraRoute {\n private network: FeatureCollection<LineString> | undefined;\n private distanceMeasurement: (positionA: Position, positionB: Position) => number;\n private adjacencyList: Map<number, Array<{ node: number; distance: number }>> = new Map();\n private coords: Position[] = []\n private coordMap: Map<number, Map<number, number>> = new Map();\n\n /**\n * Creates a new instance of TerraRoute.\n * \n * @param distanceMeasurement - Optional custom distance measurement function (defaults to haversine distance).\n */\n constructor(\n distanceMeasurement?: (positionA: Position, positionB: Position) => number\n ) {\n this.distanceMeasurement = distanceMeasurement ? distanceMeasurement : haversineDistance;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n private coordinateIndex(coord: Position): number {\n const [lng, lat] = coord;\n if (!this.coordMap.has(lng)) this.coordMap.set(lng, new Map());\n\n const latMap = this.coordMap.get(lng)!;\n if (latMap.has(lat)) {\n return latMap.get(lat)!;\n }\n\n const idx = this.coords.length;\n this.coords.push(coord);\n latMap.set(lat, idx);\n\n return idx;\n }\n\n /**\n * Builds the internal graph representation (adjacency list) from the input network.\n * Each LineString segment is translated into bidirectional graph edges with associated distances.\n * Assumes that the network is a connected graph of LineStrings with shared coordinates. Calling this \n * method with a new network overwrite any existing network and reset all internal data structures.\n * \n * @param network - A GeoJSON FeatureCollection of LineStrings representing the road network.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n this.adjacencyList = new Map();\n this.coords = [];\n this.coordMap = new Map();\n\n for (const feature of this.network.features) {\n const coords = feature.geometry.coordinates;\n for (let i = 0; i < coords.length - 1; i++) {\n const aIdx = this.coordinateIndex(coords[i]);\n const bIdx = this.coordinateIndex(coords[i + 1]);\n const distance = this.distanceMeasurement(coords[i], coords[i + 1]);\n\n if (!this.adjacencyList.has(aIdx)) this.adjacencyList.set(aIdx, []);\n if (!this.adjacencyList.has(bIdx)) this.adjacencyList.set(bIdx, []);\n\n this.adjacencyList.get(aIdx)!.push({ node: bIdx, distance });\n this.adjacencyList.get(bIdx)!.push({ node: aIdx, distance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildNetworkGraph(network) first.\");\n }\n\n const startIdx = this.coordinateIndex(start.geometry.coordinates);\n const endIdx = this.coordinateIndex(end.geometry.coordinates);\n\n if (startIdx === endIdx) {\n return null;\n }\n\n const openSet = new MinHeap();\n openSet.insert(0, startIdx);\n const cameFrom = new Map<number, number>();\n const gScore = new Map<number, number>([[startIdx, 0]]);\n\n while (openSet.size() > 0) {\n const current = openSet.extractMin()!;\n\n if (current === endIdx) {\n const path: Position[] = [];\n let currNode: number | undefined = current;\n while (currNode !== undefined) {\n path.unshift(this.coords[currNode]);\n currNode = cameFrom.get(currNode);\n }\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: path },\n properties: {},\n };\n }\n\n const neighbors = this.adjacencyList.get(current) || [];\n\n for (const neighbor of neighbors) {\n const tentativeGScore = (gScore.get(current) ?? Infinity) + neighbor.distance;\n if (tentativeGScore < (gScore.get(neighbor.node) ?? Infinity)) {\n cameFrom.set(neighbor.node, current);\n gScore.set(neighbor.node, tentativeGScore);\n const fScore = tentativeGScore + this.distanceMeasurement(this.coords[neighbor.node], this.coords[endIdx]);\n openSet.insert(fScore, neighbor.node);\n }\n }\n }\n\n return null;\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }"],"names":["MinHeap","this","heap","insertCounter","_proto","prototype","insert","key","value","node","index","idx","length","push","parentIdx","parent","extractMin","minNode","endNode","pop","bubbleDown","size","nodeKey","nodeIndex","leftIdx","smallestIdx","smallestKey","smallestIndex","rightIdx","rightKey","rightIndex","haversineDistance","pointOne","pointTwo","toRadians","latOrLng","Math","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","a","sin","cos","atan2","sqrt","createCheapRuler","lat","FE","E2","RAD","cosLat","w2","w","m","kx","ky","b","deltaLng","dx","dy","TerraRoute","distanceMeasurement","network","adjacencyList","Map","coords","coordMap","coordinateIndex","coord","lng","has","set","latMap","get","buildRouteGraph","_iterator","_step","_createForOfIteratorHelperLoose","features","done","geometry","coordinates","i","aIdx","bIdx","distance","getRoute","start","end","Error","startIdx","endIdx","openSet","cameFrom","gScore","current","path","currNode","undefined","unshift","type","properties","_step2","_iterator2","_gScore$get","_gScore$get2","neighbor","tentativeGScore","Infinity","fScore"],"mappings":"oyBAAa,IAAAA,eAAO,WAAA,SAAAA,IAAAC,KACRC,KAA6D,GAC7DC,KAAAA,cAAgB,CAAC,KAAAC,EAAAJ,EAAAK,UAmFxB,OAnFwBD,EAEzBE,OAAA,SAAOC,EAAaC,GAChB,IAAMC,EAAO,CAAEF,IAAAA,EAAKC,MAAAA,EAAOE,MAAOT,KAAKE,iBACnCQ,EAAMV,KAAKC,KAAKU,OAIpB,IAHAX,KAAKC,KAAKW,KAAKJ,GAGRE,EAAM,GAAG,CACZ,IAAMG,EAAaH,EAAM,IAAO,EAC1BI,EAASd,KAAK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src/fibonacci-heap.ts","../src/distance/haversine.ts","../src/distance/cheap-ruler.ts","../src/terra-route.ts"],"sourcesContent":["type FibNode = {\n key: number;\n value: number;\n degree: number;\n mark: boolean;\n parent: FibNode | null;\n child: FibNode | null;\n left: FibNode;\n right: FibNode;\n};\n\nexport class FibonacciHeap {\n private nodeCount = 0;\n private minNode: FibNode | null = null;\n\n insert(key: number, value: number): void {\n const node: FibNode = {\n key,\n value,\n degree: 0,\n mark: false,\n parent: null,\n child: null,\n left: null as any,\n right: null as any,\n };\n node.left = node;\n node.right = node;\n\n this.minNode = this.mergeLists(this.minNode, node);\n this.nodeCount++;\n }\n\n extractMin(): number | null {\n const z = this.minNode;\n if (!z) return null;\n\n // Add children to root list\n if (z.child) {\n let child = z.child;\n do {\n child.parent = null;\n child = child.right!;\n } while (child !== z.child);\n this.minNode = this.mergeLists(this.minNode, z.child);\n }\n\n this.removeFromList(z);\n\n if (z === z.right) {\n this.minNode = null;\n } else {\n this.minNode = z.right;\n this.consolidate();\n }\n\n this.nodeCount--;\n return z.value;\n }\n\n size(): number {\n return this.nodeCount;\n }\n\n // ========== Internal Methods ==========\n\n private consolidate(): void {\n const maxDegree = Math.floor(Math.log2(this.nodeCount)) + 1;\n const A = new Array<FibNode | null>(maxDegree).fill(null);\n\n const rootList: FibNode[] = [];\n let curr = this.minNode!;\n do {\n rootList.push(curr);\n curr = curr.right!;\n } while (curr !== this.minNode);\n\n for (const w of rootList) {\n let x = w;\n let d = x.degree;\n while (A[d]) {\n let y = A[d]!;\n if (x.key > y.key) {\n const temp = x;\n x = y;\n y = temp;\n }\n this.link(y, x);\n A[d] = null;\n d++;\n }\n A[d] = x;\n }\n\n this.minNode = null;\n for (const node of A) {\n if (node) {\n this.minNode = this.mergeLists(this.minNode, node);\n }\n }\n }\n\n private link(y: FibNode, x: FibNode): void {\n this.removeFromList(y);\n y.left = y.right = y;\n x.child = this.mergeLists(x.child, y);\n y.parent = x;\n x.degree++;\n y.mark = false;\n }\n\n private mergeLists(a: FibNode | null, b: FibNode | null): FibNode {\n if (!a) return b!;\n if (!b) return a;\n\n const aRight = a.right!;\n const bRight = b.right!;\n\n a.right = bRight;\n bRight.left = a;\n b.right = aRight;\n aRight.left = b;\n\n return a.key < b.key ? a : b;\n }\n\n private removeFromList(node: FibNode): void {\n node.left.right = node.right;\n node.right.left = node.left;\n }\n}\n","import { Position } from \"geojson\";\n\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { FibonacciHeap } from \"./fibonacci-heap\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\n\n/**\n * TerraRoute is a routing utility for finding the shortest path\n * between two geographic points over a given GeoJSON LineString network.\n *\n * The class builds an internal graph structure based on the provided network,\n * then applies A* algorithm to compute the shortest route.\n */\nclass TerraRoute {\n private network: FeatureCollection<LineString> | undefined;\n private distanceMeasurement: (positionA: Position, positionB: Position) => number;\n private adjacencyList: Map<number, Array<{ node: number; distance: number }>> = new Map();\n private coords: Position[] = []\n private coordMap: Map<number, Map<number, number>> = new Map();\n\n /**\n * Creates a new instance of TerraRoute.\n * \n * @param distanceMeasurement - Optional custom distance measurement function (defaults to haversine distance).\n */\n constructor(\n distanceMeasurement?: (positionA: Position, positionB: Position) => number\n ) {\n this.distanceMeasurement = distanceMeasurement ? distanceMeasurement : haversineDistance;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n private coordinateIndex(coord: Position): number {\n const [lng, lat] = coord;\n if (!this.coordMap.has(lng)) this.coordMap.set(lng, new Map());\n\n const latMap = this.coordMap.get(lng)!;\n if (latMap.has(lat)) {\n return latMap.get(lat)!;\n }\n\n const index = this.coords.length;\n this.coords.push(coord);\n latMap.set(lat, index);\n\n return index;\n }\n\n /**\n * Builds the internal graph representation (adjacency list) from the input network.\n * Each LineString segment is translated into bidirectional graph edges with associated distances.\n * Assumes that the network is a connected graph of LineStrings with shared coordinates. Calling this \n * method with a new network overwrite any existing network and reset all internal data structures.\n * \n * @param network - A GeoJSON FeatureCollection of LineStrings representing the road network.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n this.adjacencyList = new Map();\n this.coords = [];\n this.coordMap = new Map();\n\n for (const feature of this.network.features) {\n const coords = feature.geometry.coordinates;\n for (let i = 0; i < coords.length - 1; i++) {\n const aIndex = this.coordinateIndex(coords[i]);\n const bIndex = this.coordinateIndex(coords[i + 1]);\n const distance = this.distanceMeasurement(coords[i], coords[i + 1]);\n\n if (!this.adjacencyList.has(aIndex)) this.adjacencyList.set(aIndex, []);\n if (!this.adjacencyList.has(bIndex)) this.adjacencyList.set(bIndex, []);\n\n this.adjacencyList.get(aIndex)!.push({ node: bIndex, distance });\n this.adjacencyList.get(bIndex)!.push({ node: aIndex, distance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using bidirectional A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildRouteGraph(network) first.\");\n }\n\n const startIndex = this.coordinateIndex(start.geometry.coordinates);\n const endIndex = this.coordinateIndex(end.geometry.coordinates);\n\n if (startIndex === endIndex) {\n return null;\n }\n\n const openSetForward = new FibonacciHeap();\n const openSetBackward = new FibonacciHeap();\n openSetForward.insert(0, startIndex);\n openSetBackward.insert(0, endIndex);\n\n const cameFromForward = new Map<number, number>();\n const cameFromBackward = new Map<number, number>();\n const gScoreForward = new Map<number, number>([[startIndex, 0]]);\n const gScoreBackward = new Map<number, number>([[endIndex, 0]]);\n\n const visitedForward = new Set<number>();\n const visitedBackward = new Set<number>();\n\n let meetingNode: number | null = null;\n\n while (openSetForward.size() > 0 && openSetBackward.size() > 0) {\n const currentForward = openSetForward.extractMin()!;\n visitedForward.add(currentForward);\n\n if (visitedBackward.has(currentForward)) {\n meetingNode = currentForward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentForward) || []) {\n const tentativeG = (gScoreForward.get(currentForward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreForward.get(neighbor.node) ?? Infinity)) {\n cameFromForward.set(neighbor.node, currentForward);\n gScoreForward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[endIndex]);\n openSetForward.insert(fScore, neighbor.node);\n }\n }\n\n const currentBackward = openSetBackward.extractMin()!;\n visitedBackward.add(currentBackward);\n\n if (visitedForward.has(currentBackward)) {\n meetingNode = currentBackward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentBackward) || []) {\n const tentativeG = (gScoreBackward.get(currentBackward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreBackward.get(neighbor.node) ?? Infinity)) {\n cameFromBackward.set(neighbor.node, currentBackward);\n gScoreBackward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[startIndex]);\n openSetBackward.insert(fScore, neighbor.node);\n }\n }\n }\n\n if (meetingNode === null) {\n return null;\n }\n\n // Reconstruct forward path\n const pathForward: Position[] = [];\n let node = meetingNode;\n while (node !== undefined) {\n pathForward.unshift(this.coords[node]);\n node = cameFromForward.get(node)!;\n }\n\n // Reconstruct backward path (omit meeting node to avoid duplication)\n const pathBackward: Position[] = [];\n node = cameFromBackward.get(meetingNode)!;\n while (node !== undefined) {\n pathBackward.push(this.coords[node]);\n node = cameFromBackward.get(node)!;\n }\n\n const fullPath = [...pathForward, ...pathBackward];\n\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: fullPath },\n properties: {},\n };\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }"],"names":["FibonacciHeap","this","nodeCount","minNode","_proto","prototype","insert","key","value","node","degree","mark","parent","child","left","right","mergeLists","extractMin","z","removeFromList","consolidate","size","maxDegree","Math","floor","log2","A","Array","fill","rootList","curr","push","_i","_rootList","length","x","d","y","temp","link","_step","_iterator","_createForOfIteratorHelperLoose","done","a","b","aRight","bRight","haversineDistance","pointOne","pointTwo","toRadians","latOrLng","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","sin","cos","atan2","sqrt","createCheapRuler","lat","FE","E2","RAD","cosLat","w2","w","m","kx","ky","deltaLng","dx","dy","TerraRoute","distanceMeasurement","network","adjacencyList","Map","coords","coordMap","coordinateIndex","coord","lng","has","set","latMap","get","index","buildRouteGraph","features","geometry","coordinates","i","aIndex","bIndex","distance","getRoute","start","end","Error","startIndex","endIndex","openSetForward","openSetBackward","cameFromForward","cameFromBackward","gScoreForward","gScoreBackward","visitedForward","Set","visitedBackward","meetingNode","currentForward","add","_iterator2","_step2","_gScoreForward$get","_gScoreForward$get2","neighbor","tentativeG","Infinity","fScore","currentBackward","_step3","_iterator3","_gScoreBackward$get","_gScoreBackward$get2","pathForward","undefined","unshift","pathBackward","type","concat","properties"],"mappings":"oyBAWA,IAAaA,eAAa,WAAA,SAAAA,IAAAC,KACdC,UAAY,EACZC,KAAAA,QAA0B,IAAI,CAAA,IAAAC,EAAAJ,EAAAK,iBAAAD,EAEtCE,OAAA,SAAOC,EAAaC,GAChB,IAAMC,EAAgB,CAClBF,IAAAA,EACAC,MAAAA,EACAE,OAAQ,EACRC,MAAM,EACNC,OAAQ,KACRC,MAAO,KACPC,KAAM,KACNC,MAAO,MAEXN,EAAKK,KAAOL,EACZA,EAAKM,MAAQN,EAEbR,KAAKE,QAAUF,KAAKe,WAAWf,KAAKE,QAASM,GAC7CR,KAAKC,WACT,EAACE,EAEDa,WAAA,WACI,IAAMC,EAAIjB,KAAKE,QACf,IAAKe,EAAG,OAAW,KAGnB,GAAIA,EAAEL,MAAO,CACT,IAAIA,EAAQK,EAAEL,MACd,GACIA,EAAMD,OAAS,KACfC,EAAQA,EAAME,YACTF,IAAUK,EAAEL,OACrBZ,KAAKE,QAAUF,KAAKe,WAAWf,KAAKE,QAASe,EAAEL,MACnD,CAYA,OAVAZ,KAAKkB,eAAeD,GAEhBA,IAAMA,EAAEH,MACRd,KAAKE,QAAU,MAEfF,KAAKE,QAAUe,EAAEH,MACjBd,KAAKmB,eAGTnB,KAAKC,YACEgB,EAAEV,KACb,EAACJ,EAEDiB,KAAA,WACI,OAAOpB,KAAKC,SAChB,EAACE,EAIOgB,YAAA,WACJ,IAAME,EAAYC,KAAKC,MAAMD,KAAKE,KAAKxB,KAAKC,YAAc,EACpDwB,EAAI,IAAIC,MAAsBL,GAAWM,KAAK,MAE9CC,EAAsB,GACxBC,EAAO7B,KAAKE,QAChB,GACI0B,EAASE,KAAKD,GACdA,EAAOA,EAAKf,YACPe,IAAS7B,KAAKE,SAEvB,IAAA,IAAA6B,EAAAC,EAAAA,EAAgBJ,EAAQG,EAAAC,EAAAC,OAAAF,IAAE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,GAFAiG,EAAgBG,IAAIS,GAEhBd,EAAezB,IAAIuC,GAAkB,CACrCX,EAAcW,EACd,KACJ,CAEA,IAAA,IAAoEC,EAApEC,EAAAtF,EAAuBzC,KAAK+E,cAAcU,IAAIoC,IAAoB,MAAEC,EAAAC,KAAArF,MAAE,CAAAsF,IAAAA,EAAAC,EAA3DR,EAAQK,EAAAvH,MACTmH,GAAiDM,OAApCA,EAAClB,EAAerB,IAAIoC,IAAgBG,EAAIL,UAAYF,EAASvB,SAChF,GAAIwB,GAA+CO,OAArCA,EAAInB,EAAerB,IAAIgC,EAASjH,OAAKyH,EAAIN,UAAW,CAC9Df,EAAiBrB,IAAIkC,EAASjH,KAAMqH,GACpCf,EAAevB,IAAIkC,EAASjH,KAAMkH,GAClC,IAAME,EAASF,EAAa1H,KAAK6E,oBAAoB7E,KAAKiF,OAAOwC,EAASjH,MAAOR,KAAKiF,OAAOsB,IAC7FG,EAAgBrG,OAAOuH,EAAQH,EAASjH,KAC5C,CACJ,CACJ,CAEA,GAAoB,OAAhB0G,EACA,OAAO,KAMX,IAFA,IAAMgB,EAA0B,GAC5B1H,EAAO0G,OACKiB,IAAT3H,GACH0H,EAAYE,QAAQpI,KAAKiF,OAAOzE,IAChCA,EAAOmG,EAAgBlB,IAAIjF,GAI/B,IAAM6H,EAA2B,GAEjC,IADA7H,EAAOoG,EAAiBnB,IAAIyB,QACZiB,IAAT3H,GACH6H,EAAavG,KAAK9B,KAAKiF,OAAOzE,IAC9BA,EAAOoG,EAAiBnB,IAAIjF,GAKhC,MAAO,CACH8H,KAAM,UACNzC,SAAU,CAAEyC,KAAM,aAAcxC,YAJtB,GAAAyC,OAAOL,EAAgBG,IAKjCG,WAAY,CAAA,EAEpB,EAAC5D,CAAA,CA5KW"}
|
package/dist/terra-route.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t||self).terraRoute={})}(this,function(t){function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function n(t,n){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}(t))||n&&t&&"number"==typeof t.length){r&&(t=r);var i=0;return function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r=/*#__PURE__*/function(){function t(){this.
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t||self).terraRoute={})}(this,function(t){function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function n(t,n){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}(t))||n&&t&&"number"==typeof t.length){r&&(t=r);var i=0;return function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r=/*#__PURE__*/function(){function t(){this.nodeCount=0,this.minNode=null}var e=t.prototype;return e.insert=function(t,e){var n={key:t,value:e,degree:0,mark:!1,parent:null,child:null,left:null,right:null};n.left=n,n.right=n,this.minNode=this.mergeLists(this.minNode,n),this.nodeCount++},e.extractMin=function(){var t=this.minNode;if(!t)return null;if(t.child){var e=t.child;do{e.parent=null,e=e.right}while(e!==t.child);this.minNode=this.mergeLists(this.minNode,t.child)}return this.removeFromList(t),t===t.right?this.minNode=null:(this.minNode=t.right,this.consolidate()),this.nodeCount--,t.value},e.size=function(){return this.nodeCount},e.consolidate=function(){var t=Math.floor(Math.log2(this.nodeCount))+1,e=new Array(t).fill(null),r=[],i=this.minNode;do{r.push(i),i=i.right}while(i!==this.minNode);for(var o=0,a=r;o<a.length;o++){for(var s=a[o],h=s.degree;e[h];){var d=e[h];if(s.key>d.key){var u=s;s=d,d=u}this.link(d,s),e[h]=null,h++}e[h]=s}this.minNode=null;for(var c,l=n(e);!(c=l()).done;){var f=c.value;f&&(this.minNode=this.mergeLists(this.minNode,f))}},e.link=function(t,e){this.removeFromList(t),t.left=t.right=t,e.child=this.mergeLists(e.child,t),t.parent=e,e.degree++,t.mark=!1},e.mergeLists=function(t,e){if(!t)return e;if(!e)return t;var n=t.right,r=e.right;return t.right=r,r.left=t,e.right=n,n.left=e,t.key<e.key?t:e},e.removeFromList=function(t){t.left.right=t.right,t.right.left=t.left},t}(),i=function(t,e){var n=function(t){return t*Math.PI/180},r=n(t[1]),i=n(t[0]),o=n(e[1]),a=o-r,s=n(e[0])-i,h=Math.sin(a/2)*Math.sin(a/2)+Math.cos(r)*Math.cos(o)*Math.sin(s/2)*Math.sin(s/2);return 2*Math.atan2(Math.sqrt(h),Math.sqrt(1-h))*6371e3/1e3};t.TerraRoute=/*#__PURE__*/function(){function t(t){this.network=void 0,this.distanceMeasurement=void 0,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map,this.distanceMeasurement=t||i}var e=t.prototype;return e.coordinateIndex=function(t){var e=t[0],n=t[1];this.coordMap.has(e)||this.coordMap.set(e,new Map);var r=this.coordMap.get(e);if(r.has(n))return r.get(n);var i=this.coords.length;return this.coords.push(t),r.set(n,i),i},e.buildRouteGraph=function(t){this.network=t,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map;for(var e,r=n(this.network.features);!(e=r()).done;)for(var i=e.value.geometry.coordinates,o=0;o<i.length-1;o++){var a=this.coordinateIndex(i[o]),s=this.coordinateIndex(i[o+1]),h=this.distanceMeasurement(i[o],i[o+1]);this.adjacencyList.has(a)||this.adjacencyList.set(a,[]),this.adjacencyList.has(s)||this.adjacencyList.set(s,[]),this.adjacencyList.get(a).push({node:s,distance:h}),this.adjacencyList.get(s).push({node:a,distance:h})}},e.getRoute=function(t,e){if(!this.network)throw new Error("Network not built. Please call buildRouteGraph(network) first.");var i=this.coordinateIndex(t.geometry.coordinates),o=this.coordinateIndex(e.geometry.coordinates);if(i===o)return null;var a=new r,s=new r;a.insert(0,i),s.insert(0,o);for(var h=new Map,d=new Map,u=new Map([[i,0]]),c=new Map([[o,0]]),l=new Set,f=new Set,v=null;a.size()>0&&s.size()>0;){var g=a.extractMin();if(l.add(g),f.has(g)){v=g;break}for(var m,p=n(this.adjacencyList.get(g)||[]);!(m=p()).done;){var y,M,w=m.value,L=(null!=(y=u.get(g))?y:Infinity)+w.distance;if(L<(null!=(M=u.get(w.node))?M:Infinity)){h.set(w.node,g),u.set(w.node,L);var b=L+this.distanceMeasurement(this.coords[w.node],this.coords[o]);a.insert(b,w.node)}}var k=s.extractMin();if(f.add(k),l.has(k)){v=k;break}for(var I,N=n(this.adjacencyList.get(k)||[]);!(I=N()).done;){var j,x,S=I.value,A=(null!=(j=c.get(k))?j:Infinity)+S.distance;if(A<(null!=(x=c.get(S.node))?x:Infinity)){d.set(S.node,k),c.set(S.node,A);var C=A+this.distanceMeasurement(this.coords[S.node],this.coords[i]);s.insert(C,S.node)}}}if(null===v)return null;for(var R=[],q=v;void 0!==q;)R.unshift(this.coords[q]),q=h.get(q);var F=[];for(q=d.get(v);void 0!==q;)F.push(this.coords[q]),q=d.get(q);return{type:"Feature",geometry:{type:"LineString",coordinates:[].concat(R,F)},properties:{}}},t}(),t.createCheapRuler=function(t){var e=1/298.257223563,n=e*(2-e),r=Math.PI/180,i=Math.cos(t*r),o=1/(1-n*(1-i*i)),a=Math.sqrt(o),s=6378.137*r,h=s*a*i,d=s*a*o*(1-n);return function(t,e){for(var n=t[0]-e[0];n<-180;)n+=360;for(;n>180;)n-=360;var r=n*h,i=(t[1]-e[1])*d;return Math.sqrt(r*r+i*i)}},t.haversineDistance=i});
|
|
2
2
|
//# sourceMappingURL=terra-route.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"terra-route.umd.js","sources":["../src/min-heap.ts","../src/distance/haversine.ts","../src/terra-route.ts","../src/distance/cheap-ruler.ts"],"sourcesContent":["export class MinHeap {\n private heap: Array<{ key: number; value: number; index: number }> = [];\n private insertCounter = 0;\n\n insert(key: number, value: number): void {\n const node = { key, value, index: this.insertCounter++ };\n let idx = this.heap.length;\n this.heap.push(node);\n\n // Optimized Bubble Up\n while (idx > 0) {\n const parentIdx = (idx - 1) >>> 1; // Fast Math.floor((idx - 1) / 2)\n const parent = this.heap[parentIdx];\n if (node.key > parent.key || (node.key === parent.key && node.index > parent.index)) break;\n this.heap[idx] = parent;\n idx = parentIdx;\n }\n this.heap[idx] = node;\n }\n\n extractMin(): number | null {\n const length = this.heap.length;\n if (length === 0) return null;\n\n const minNode = this.heap[0];\n const endNode = this.heap.pop()!;\n\n if (length > 1) {\n this.heap[0] = endNode;\n this.bubbleDown(0);\n }\n\n return minNode.value;\n }\n\n size(): number {\n return this.heap.length;\n }\n\n private bubbleDown(idx: number): void {\n const { heap } = this;\n const length = heap.length;\n // Grab the parent node once, then move it down only if needed\n const node = heap[idx];\n const nodeKey = node.key;\n const nodeIndex = node.index;\n\n while (true) {\n // Calculate left and right child indexes\n const leftIdx = (idx << 1) + 1;\n if (leftIdx >= length) {\n // No children => we’re already in place\n break;\n }\n\n // Assume left child is the smaller one by default\n let smallestIdx = leftIdx;\n let smallestKey = heap[leftIdx].key;\n let smallestIndex = heap[leftIdx].index;\n\n const rightIdx = leftIdx + 1;\n if (rightIdx < length) {\n // Compare left child vs. right child\n const rightKey = heap[rightIdx].key;\n const rightIndex = heap[rightIdx].index;\n if (rightKey < smallestKey || (rightKey === smallestKey && rightIndex < smallestIndex)) {\n smallestIdx = rightIdx;\n smallestKey = rightKey;\n smallestIndex = rightIndex;\n }\n }\n\n // Compare the smaller child with the parent\n if (smallestKey < nodeKey || (smallestKey === nodeKey && smallestIndex < nodeIndex)) {\n // Swap the smaller child up\n heap[idx] = heap[smallestIdx];\n idx = smallestIdx;\n } else {\n // We’re in the correct position now, so stop\n break;\n }\n }\n\n // Place the original node in its final position\n heap[idx] = node;\n }\n}\n","import { Position } from \"geojson\";\n\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { MinHeap } from \"./min-heap\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\n\n/**\n * TerraRoute is a routing utility for finding the shortest path\n * between two geographic points over a given GeoJSON LineString network.\n *\n * The class builds an internal graph structure based on the provided network,\n * then applies A* algorithm to compute the shortest route.\n */\nclass TerraRoute {\n private network: FeatureCollection<LineString> | undefined;\n private distanceMeasurement: (positionA: Position, positionB: Position) => number;\n private adjacencyList: Map<number, Array<{ node: number; distance: number }>> = new Map();\n private coords: Position[] = []\n private coordMap: Map<number, Map<number, number>> = new Map();\n\n /**\n * Creates a new instance of TerraRoute.\n * \n * @param distanceMeasurement - Optional custom distance measurement function (defaults to haversine distance).\n */\n constructor(\n distanceMeasurement?: (positionA: Position, positionB: Position) => number\n ) {\n this.distanceMeasurement = distanceMeasurement ? distanceMeasurement : haversineDistance;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n private coordinateIndex(coord: Position): number {\n const [lng, lat] = coord;\n if (!this.coordMap.has(lng)) this.coordMap.set(lng, new Map());\n\n const latMap = this.coordMap.get(lng)!;\n if (latMap.has(lat)) {\n return latMap.get(lat)!;\n }\n\n const idx = this.coords.length;\n this.coords.push(coord);\n latMap.set(lat, idx);\n\n return idx;\n }\n\n /**\n * Builds the internal graph representation (adjacency list) from the input network.\n * Each LineString segment is translated into bidirectional graph edges with associated distances.\n * Assumes that the network is a connected graph of LineStrings with shared coordinates. Calling this \n * method with a new network overwrite any existing network and reset all internal data structures.\n * \n * @param network - A GeoJSON FeatureCollection of LineStrings representing the road network.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n this.adjacencyList = new Map();\n this.coords = [];\n this.coordMap = new Map();\n\n for (const feature of this.network.features) {\n const coords = feature.geometry.coordinates;\n for (let i = 0; i < coords.length - 1; i++) {\n const aIdx = this.coordinateIndex(coords[i]);\n const bIdx = this.coordinateIndex(coords[i + 1]);\n const distance = this.distanceMeasurement(coords[i], coords[i + 1]);\n\n if (!this.adjacencyList.has(aIdx)) this.adjacencyList.set(aIdx, []);\n if (!this.adjacencyList.has(bIdx)) this.adjacencyList.set(bIdx, []);\n\n this.adjacencyList.get(aIdx)!.push({ node: bIdx, distance });\n this.adjacencyList.get(bIdx)!.push({ node: aIdx, distance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildNetworkGraph(network) first.\");\n }\n\n const startIdx = this.coordinateIndex(start.geometry.coordinates);\n const endIdx = this.coordinateIndex(end.geometry.coordinates);\n\n if (startIdx === endIdx) {\n return null;\n }\n\n const openSet = new MinHeap();\n openSet.insert(0, startIdx);\n const cameFrom = new Map<number, number>();\n const gScore = new Map<number, number>([[startIdx, 0]]);\n\n while (openSet.size() > 0) {\n const current = openSet.extractMin()!;\n\n if (current === endIdx) {\n const path: Position[] = [];\n let currNode: number | undefined = current;\n while (currNode !== undefined) {\n path.unshift(this.coords[currNode]);\n currNode = cameFrom.get(currNode);\n }\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: path },\n properties: {},\n };\n }\n\n const neighbors = this.adjacencyList.get(current) || [];\n\n for (const neighbor of neighbors) {\n const tentativeGScore = (gScore.get(current) ?? Infinity) + neighbor.distance;\n if (tentativeGScore < (gScore.get(neighbor.node) ?? Infinity)) {\n cameFrom.set(neighbor.node, current);\n gScore.set(neighbor.node, tentativeGScore);\n const fScore = tentativeGScore + this.distanceMeasurement(this.coords[neighbor.node], this.coords[endIdx]);\n openSet.insert(fScore, neighbor.node);\n }\n }\n }\n\n return null;\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}"],"names":["MinHeap","this","heap","insertCounter","_proto","prototype","insert","key","value","node","index","idx","length","push","parentIdx","parent","extractMin","minNode","endNode","pop","bubbleDown","size","nodeKey","nodeIndex","leftIdx","smallestIdx","smallestKey","smallestIndex","rightIdx","rightKey","rightIndex","haversineDistance","pointOne","pointTwo","toRadians","latOrLng","Math","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","a","sin","cos","atan2","sqrt","TerraRoute","distanceMeasurement","network","adjacencyList","Map","coords","coordMap","coordinateIndex","coord","lng","lat","has","set","latMap","get","buildRouteGraph","_iterator","_step","_createForOfIteratorHelperLoose","features","done","geometry","coordinates","i","aIdx","bIdx","distance","getRoute","start","end","Error","startIdx","endIdx","openSet","cameFrom","gScore","current","path","currNode","undefined","unshift","type","properties","_step2","_iterator2","_gScore$get","_gScore$get2","neighbor","tentativeGScore","Infinity","fScore","FE","E2","RAD","cosLat","w2","w","m","kx","ky","b","deltaLng","dx","dy"],"mappings":"wgCAAa,IAAAA,eAAO,WAAA,SAAAA,IAAAC,KACRC,KAA6D,GAC7DC,KAAAA,cAAgB,CAAC,KAAAC,EAAAJ,EAAAK,UAmFxB,OAnFwBD,EAEzBE,OAAA,SAAOC,EAAaC,GAChB,IAAMC,EAAO,CAAEF,IAAAA,EAAKC,MAAAA,EAAOE,MAAOT,KAAKE,iBACnCQ,EAAMV,KAAKC,KAAKU,OAIpB,IAHAX,KAAKC,KAAKW,KAAKJ,GAGRE,EAAM,GAAG,CACZ,IAAMG,EAAaH,EAAM,IAAO,EAC1BI,EAASd,KAAKC,KAAKY,GACzB,GAAIL,EAAKF,IAAMQ,EAAOR,KAAQE,EAAKF,MAAQQ,EAAOR,KAAOE,EAAKC,MAAQK,EAAOL,MAAQ,MACrFT,KAAKC,KAAKS,GAAOI,EACjBJ,EAAMG,CACV,CACAb,KAAKC,KAAKS,GAAOF,CACrB,EAACL,EAEDY,WAAA,WACI,IAAMJ,EAASX,KAAKC,KAAKU,OACzB,GAAe,IAAXA,EAAc,OA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BF,EAAIX,EAAOrB,IAAIiC,EAAStF,OAAKqF,EAAIG,UAAW,CAC3Df,EAAStB,IAAImC,EAAStF,KAAM2E,GAC5BD,EAAOvB,IAAImC,EAAStF,KAAMuF,GAC1B,IAAME,EAASF,EAAkB/F,KAAKgD,oBAAoBhD,KAAKoD,OAAO0C,EAAStF,MAAOR,KAAKoD,OAAO2B,IAClGC,EAAQ3E,OAAO4F,EAAQH,EAAStF,KACpC,CACJ,CACJ,CAEA,WACJ,EAACuC,CAAA,CAhIW,sBCoBV,SAA2BU,GAC7B,IACMyC,EAAK,EAAI,cACTC,EAAKD,GAAM,EAAIA,GACfE,EAAMjE,KAAKC,GAAK,IAEhBiE,EAASlE,KAAKS,IAAIa,EAAM2C,GACxBE,EAAK,GAAK,EAAIH,GAAM,EAAIE,EAASA,IACjCE,EAAIpE,KAAKW,KAAKwD,GAEdE,EATK,SASDJ,EACJK,EAAKD,EAAID,EAAIF,EACbK,EAAKF,EAAID,EAAID,GAAM,EAAIH,GAE7B,OAAgB,SAASzD,EAAaiE,GAGlC,IAFA,IAAIC,EAAWlE,EAAE,GAAKiE,EAAE,GAEjBC,GAAY,KAAKA,GAAY,IACpC,KAAOA,EAAW,KAAKA,GAAY,IAEnC,IAAMC,EAAKD,EAAWH,EAChBK,GAAMpE,EAAE,GAAKiE,EAAE,IAAMD,EAE3B,OAAOvE,KAAKW,KAAK+D,EAAKA,EAAKC,EAAKA,EACpC,CACJ"}
|
|
1
|
+
{"version":3,"file":"terra-route.umd.js","sources":["../src/fibonacci-heap.ts","../src/distance/haversine.ts","../src/terra-route.ts","../src/distance/cheap-ruler.ts"],"sourcesContent":["type FibNode = {\n key: number;\n value: number;\n degree: number;\n mark: boolean;\n parent: FibNode | null;\n child: FibNode | null;\n left: FibNode;\n right: FibNode;\n};\n\nexport class FibonacciHeap {\n private nodeCount = 0;\n private minNode: FibNode | null = null;\n\n insert(key: number, value: number): void {\n const node: FibNode = {\n key,\n value,\n degree: 0,\n mark: false,\n parent: null,\n child: null,\n left: null as any,\n right: null as any,\n };\n node.left = node;\n node.right = node;\n\n this.minNode = this.mergeLists(this.minNode, node);\n this.nodeCount++;\n }\n\n extractMin(): number | null {\n const z = this.minNode;\n if (!z) return null;\n\n // Add children to root list\n if (z.child) {\n let child = z.child;\n do {\n child.parent = null;\n child = child.right!;\n } while (child !== z.child);\n this.minNode = this.mergeLists(this.minNode, z.child);\n }\n\n this.removeFromList(z);\n\n if (z === z.right) {\n this.minNode = null;\n } else {\n this.minNode = z.right;\n this.consolidate();\n }\n\n this.nodeCount--;\n return z.value;\n }\n\n size(): number {\n return this.nodeCount;\n }\n\n // ========== Internal Methods ==========\n\n private consolidate(): void {\n const maxDegree = Math.floor(Math.log2(this.nodeCount)) + 1;\n const A = new Array<FibNode | null>(maxDegree).fill(null);\n\n const rootList: FibNode[] = [];\n let curr = this.minNode!;\n do {\n rootList.push(curr);\n curr = curr.right!;\n } while (curr !== this.minNode);\n\n for (const w of rootList) {\n let x = w;\n let d = x.degree;\n while (A[d]) {\n let y = A[d]!;\n if (x.key > y.key) {\n const temp = x;\n x = y;\n y = temp;\n }\n this.link(y, x);\n A[d] = null;\n d++;\n }\n A[d] = x;\n }\n\n this.minNode = null;\n for (const node of A) {\n if (node) {\n this.minNode = this.mergeLists(this.minNode, node);\n }\n }\n }\n\n private link(y: FibNode, x: FibNode): void {\n this.removeFromList(y);\n y.left = y.right = y;\n x.child = this.mergeLists(x.child, y);\n y.parent = x;\n x.degree++;\n y.mark = false;\n }\n\n private mergeLists(a: FibNode | null, b: FibNode | null): FibNode {\n if (!a) return b!;\n if (!b) return a;\n\n const aRight = a.right!;\n const bRight = b.right!;\n\n a.right = bRight;\n bRight.left = a;\n b.right = aRight;\n aRight.left = b;\n\n return a.key < b.key ? a : b;\n }\n\n private removeFromList(node: FibNode): void {\n node.left.right = node.right;\n node.right.left = node.left;\n }\n}\n","import { Position } from \"geojson\";\n\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { FibonacciHeap } from \"./fibonacci-heap\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\n\n/**\n * TerraRoute is a routing utility for finding the shortest path\n * between two geographic points over a given GeoJSON LineString network.\n *\n * The class builds an internal graph structure based on the provided network,\n * then applies A* algorithm to compute the shortest route.\n */\nclass TerraRoute {\n private network: FeatureCollection<LineString> | undefined;\n private distanceMeasurement: (positionA: Position, positionB: Position) => number;\n private adjacencyList: Map<number, Array<{ node: number; distance: number }>> = new Map();\n private coords: Position[] = []\n private coordMap: Map<number, Map<number, number>> = new Map();\n\n /**\n * Creates a new instance of TerraRoute.\n * \n * @param distanceMeasurement - Optional custom distance measurement function (defaults to haversine distance).\n */\n constructor(\n distanceMeasurement?: (positionA: Position, positionB: Position) => number\n ) {\n this.distanceMeasurement = distanceMeasurement ? distanceMeasurement : haversineDistance;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n private coordinateIndex(coord: Position): number {\n const [lng, lat] = coord;\n if (!this.coordMap.has(lng)) this.coordMap.set(lng, new Map());\n\n const latMap = this.coordMap.get(lng)!;\n if (latMap.has(lat)) {\n return latMap.get(lat)!;\n }\n\n const index = this.coords.length;\n this.coords.push(coord);\n latMap.set(lat, index);\n\n return index;\n }\n\n /**\n * Builds the internal graph representation (adjacency list) from the input network.\n * Each LineString segment is translated into bidirectional graph edges with associated distances.\n * Assumes that the network is a connected graph of LineStrings with shared coordinates. Calling this \n * method with a new network overwrite any existing network and reset all internal data structures.\n * \n * @param network - A GeoJSON FeatureCollection of LineStrings representing the road network.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n this.adjacencyList = new Map();\n this.coords = [];\n this.coordMap = new Map();\n\n for (const feature of this.network.features) {\n const coords = feature.geometry.coordinates;\n for (let i = 0; i < coords.length - 1; i++) {\n const aIndex = this.coordinateIndex(coords[i]);\n const bIndex = this.coordinateIndex(coords[i + 1]);\n const distance = this.distanceMeasurement(coords[i], coords[i + 1]);\n\n if (!this.adjacencyList.has(aIndex)) this.adjacencyList.set(aIndex, []);\n if (!this.adjacencyList.has(bIndex)) this.adjacencyList.set(bIndex, []);\n\n this.adjacencyList.get(aIndex)!.push({ node: bIndex, distance });\n this.adjacencyList.get(bIndex)!.push({ node: aIndex, distance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using bidirectional A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildRouteGraph(network) first.\");\n }\n\n const startIndex = this.coordinateIndex(start.geometry.coordinates);\n const endIndex = this.coordinateIndex(end.geometry.coordinates);\n\n if (startIndex === endIndex) {\n return null;\n }\n\n const openSetForward = new FibonacciHeap();\n const openSetBackward = new FibonacciHeap();\n openSetForward.insert(0, startIndex);\n openSetBackward.insert(0, endIndex);\n\n const cameFromForward = new Map<number, number>();\n const cameFromBackward = new Map<number, number>();\n const gScoreForward = new Map<number, number>([[startIndex, 0]]);\n const gScoreBackward = new Map<number, number>([[endIndex, 0]]);\n\n const visitedForward = new Set<number>();\n const visitedBackward = new Set<number>();\n\n let meetingNode: number | null = null;\n\n while (openSetForward.size() > 0 && openSetBackward.size() > 0) {\n const currentForward = openSetForward.extractMin()!;\n visitedForward.add(currentForward);\n\n if (visitedBackward.has(currentForward)) {\n meetingNode = currentForward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentForward) || []) {\n const tentativeG = (gScoreForward.get(currentForward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreForward.get(neighbor.node) ?? Infinity)) {\n cameFromForward.set(neighbor.node, currentForward);\n gScoreForward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[endIndex]);\n openSetForward.insert(fScore, neighbor.node);\n }\n }\n\n const currentBackward = openSetBackward.extractMin()!;\n visitedBackward.add(currentBackward);\n\n if (visitedForward.has(currentBackward)) {\n meetingNode = currentBackward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentBackward) || []) {\n const tentativeG = (gScoreBackward.get(currentBackward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreBackward.get(neighbor.node) ?? Infinity)) {\n cameFromBackward.set(neighbor.node, currentBackward);\n gScoreBackward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[startIndex]);\n openSetBackward.insert(fScore, neighbor.node);\n }\n }\n }\n\n if (meetingNode === null) {\n return null;\n }\n\n // Reconstruct forward path\n const pathForward: Position[] = [];\n let node = meetingNode;\n while (node !== undefined) {\n pathForward.unshift(this.coords[node]);\n node = cameFromForward.get(node)!;\n }\n\n // Reconstruct backward path (omit meeting node to avoid duplication)\n const pathBackward: Position[] = [];\n node = cameFromBackward.get(meetingNode)!;\n while (node !== undefined) {\n pathBackward.push(this.coords[node]);\n node = cameFromBackward.get(node)!;\n }\n\n const fullPath = [...pathForward, ...pathBackward];\n\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: fullPath },\n properties: {},\n };\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}"],"names":["FibonacciHeap","this","nodeCount","minNode","_proto","prototype","insert","key","value","node","degree","mark","parent","child","left","right","mergeLists","extractMin","z","removeFromList","consolidate","size","maxDegree","Math","floor","log2","A","Array","fill","rootList","curr","push","_i","_rootList","length","x","d","y","temp","link","_step","_iterator","_createForOfIteratorHelperLoose","done","a","b","aRight","bRight","haversineDistance","pointOne","pointTwo","toRadians","latOrLng","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","sin","cos","atan2","sqrt","TerraRoute","distanceMeasurement","network","adjacencyList","Map","coords","coordMap","coordinateIndex","coord","lng","lat","has","set","latMap","get","index","buildRouteGraph","features","geometry","coordinates","i","aIndex","bIndex","distance","getRoute","start","end","Error","startIndex","endIndex","openSetForward","openSetBackward","cameFromForward","cameFromBackward","gScoreForward","gScoreBackward","visitedForward","Set","visitedBackward","meetingNode","currentForward","add","_iterator2","_step2","_gScoreForward$get","_gScoreForward$get2","neighbor","tentativeG","Infinity","fScore","currentBackward","_step3","_iterator3","_gScoreBackward$get","_gScoreBackward$get2","pathForward","undefined","unshift","pathBackward","type","concat","properties","FE","E2","RAD","cosLat","w2","w","m","kx","ky","deltaLng","dx","dy"],"mappings":"wgCAWA,IAAaA,eAAa,WAAA,SAAAA,IAAAC,KACdC,UAAY,EACZC,KAAAA,QAA0B,IAAI,CAAA,IAAAC,EAAAJ,EAAAK,iBAAAD,EAEtCE,OAAA,SAAOC,EAAaC,GAChB,IAAMC,EAAgB,CAClBF,IAAAA,EACAC,MAAAA,EACAE,OAAQ,EACRC,M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B,KAAKmE,OAAO3D,IAC9BA,EAAOuF,EAAiBnB,IAAIpE,GAKhC,MAAO,CACHiH,KAAM,UACNzC,SAAU,CAAEyC,KAAM,aAAcxC,YAJtB,GAAAyC,OAAOL,EAAgBG,IAKjCG,WAAY,CAAA,EAEpB,EAAC7D,CAAA,CA5KW,sBCoBV,SAA2BU,GAC7B,IACMoD,EAAK,EAAI,cACTC,EAAKD,GAAM,EAAIA,GACfE,EAAMxG,KAAK8B,GAAK,IAEhB2E,EAASzG,KAAKqC,IAAIa,EAAMsD,GACxBE,EAAK,GAAK,EAAIH,GAAM,EAAIE,EAASA,IACjCE,EAAI3G,KAAKuC,KAAKmE,GAEdE,EATK,SASDJ,EACJK,EAAKD,EAAID,EAAIF,EACbK,EAAKF,EAAID,EAAID,GAAM,EAAIH,GAE7B,OAAgB,SAASlF,EAAaC,GAGlC,IAFA,IAAIyF,EAAW1F,EAAE,GAAKC,EAAE,GAEjByF,GAAY,KAAKA,GAAY,IACpC,KAAOA,EAAW,KAAKA,GAAY,IAEnC,IAAMC,EAAKD,EAAWF,EAChBI,GAAM5F,EAAE,GAAKC,EAAE,IAAMwF,EAE3B,OAAO9G,KAAKuC,KAAKyE,EAAKA,EAAKC,EAAKA,EACpC,CACJ"}
|
package/jest.config.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "terra-route",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.6",
|
|
4
4
|
"description": "A library for routing along GeoJSON LineString networks",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"docs": "typedoc",
|
|
@@ -40,18 +40,18 @@
|
|
|
40
40
|
"eslint": "8.57.1",
|
|
41
41
|
"eslint-config-prettier": "9.1.0",
|
|
42
42
|
"eslint-plugin-prettier": "5.2.1",
|
|
43
|
-
"geojson": "^0.5.0",
|
|
44
43
|
"geojson-path-finder": "^2.0.2",
|
|
45
44
|
"jest": "^29.7.0",
|
|
46
45
|
"knip": "^5.38.1",
|
|
47
46
|
"microbundle": "0.15.1",
|
|
47
|
+
"ngraph.graph": "^20.0.1",
|
|
48
|
+
"ngraph.path": "^1.5.0",
|
|
48
49
|
"serve": "^14.2.4",
|
|
49
50
|
"ts-jest": "^29.2.5",
|
|
50
51
|
"tsx": "^4.19.3",
|
|
51
52
|
"typedoc": "^0.28.1",
|
|
52
53
|
"typescript": "^5.8.3"
|
|
53
54
|
},
|
|
54
|
-
"dependencies": {},
|
|
55
55
|
"keywords": [
|
|
56
56
|
"geojson",
|
|
57
57
|
"linestring",
|
|
@@ -89,5 +89,8 @@
|
|
|
89
89
|
"out": "docs",
|
|
90
90
|
"skipErrorChecking": true,
|
|
91
91
|
"sourceLinkExternal": true
|
|
92
|
+
},
|
|
93
|
+
"dependencies": {
|
|
94
|
+
"@types/geojson": "^7946.0.16"
|
|
92
95
|
}
|
|
93
96
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { FibonacciHeap } from './fibonacci-heap';
|
|
2
|
+
|
|
3
|
+
describe('FibonacciHeap', () => {
|
|
4
|
+
let heap: FibonacciHeap;
|
|
5
|
+
|
|
6
|
+
beforeEach(() => {
|
|
7
|
+
heap = new FibonacciHeap();
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
test('insert() and size()', () => {
|
|
11
|
+
expect(heap.size()).toBe(0);
|
|
12
|
+
heap.insert(10, 1);
|
|
13
|
+
expect(heap.size()).toBe(1);
|
|
14
|
+
heap.insert(5, 2);
|
|
15
|
+
expect(heap.size()).toBe(2);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test('extractMin() returns the correct value', () => {
|
|
19
|
+
heap.insert(20, 101);
|
|
20
|
+
heap.insert(5, 102);
|
|
21
|
+
heap.insert(15, 103);
|
|
22
|
+
|
|
23
|
+
expect(heap.extractMin()).toBe(102); // key 5
|
|
24
|
+
expect(heap.size()).toBe(2);
|
|
25
|
+
expect(heap.extractMin()).toBe(103); // key 15
|
|
26
|
+
expect(heap.extractMin()).toBe(101); // key 20
|
|
27
|
+
expect(heap.extractMin()).toBeNull();
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('extractMin() on empty heap returns null', () => {
|
|
31
|
+
expect(heap.extractMin()).toBeNull();
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test('insert() handles duplicate keys', () => {
|
|
35
|
+
heap.insert(10, 201);
|
|
36
|
+
heap.insert(10, 202);
|
|
37
|
+
heap.insert(10, 203);
|
|
38
|
+
|
|
39
|
+
const values = [heap.extractMin(), heap.extractMin(), heap.extractMin()];
|
|
40
|
+
expect(values).toContain(201);
|
|
41
|
+
expect(values).toContain(202);
|
|
42
|
+
expect(values).toContain(203);
|
|
43
|
+
expect(heap.size()).toBe(0);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test('interleaved insert and extractMin()', () => {
|
|
47
|
+
heap.insert(30, 301);
|
|
48
|
+
heap.insert(10, 302);
|
|
49
|
+
expect(heap.extractMin()).toBe(302);
|
|
50
|
+
heap.insert(20, 303);
|
|
51
|
+
expect(heap.extractMin()).toBe(303);
|
|
52
|
+
expect(heap.extractMin()).toBe(301);
|
|
53
|
+
expect(heap.extractMin()).toBeNull();
|
|
54
|
+
});
|
|
55
|
+
});
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
type FibNode = {
|
|
2
|
+
key: number;
|
|
3
|
+
value: number;
|
|
4
|
+
degree: number;
|
|
5
|
+
mark: boolean;
|
|
6
|
+
parent: FibNode | null;
|
|
7
|
+
child: FibNode | null;
|
|
8
|
+
left: FibNode;
|
|
9
|
+
right: FibNode;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export class FibonacciHeap {
|
|
13
|
+
private nodeCount = 0;
|
|
14
|
+
private minNode: FibNode | null = null;
|
|
15
|
+
|
|
16
|
+
insert(key: number, value: number): void {
|
|
17
|
+
const node: FibNode = {
|
|
18
|
+
key,
|
|
19
|
+
value,
|
|
20
|
+
degree: 0,
|
|
21
|
+
mark: false,
|
|
22
|
+
parent: null,
|
|
23
|
+
child: null,
|
|
24
|
+
left: null as any,
|
|
25
|
+
right: null as any,
|
|
26
|
+
};
|
|
27
|
+
node.left = node;
|
|
28
|
+
node.right = node;
|
|
29
|
+
|
|
30
|
+
this.minNode = this.mergeLists(this.minNode, node);
|
|
31
|
+
this.nodeCount++;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
extractMin(): number | null {
|
|
35
|
+
const z = this.minNode;
|
|
36
|
+
if (!z) return null;
|
|
37
|
+
|
|
38
|
+
// Add children to root list
|
|
39
|
+
if (z.child) {
|
|
40
|
+
let child = z.child;
|
|
41
|
+
do {
|
|
42
|
+
child.parent = null;
|
|
43
|
+
child = child.right!;
|
|
44
|
+
} while (child !== z.child);
|
|
45
|
+
this.minNode = this.mergeLists(this.minNode, z.child);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
this.removeFromList(z);
|
|
49
|
+
|
|
50
|
+
if (z === z.right) {
|
|
51
|
+
this.minNode = null;
|
|
52
|
+
} else {
|
|
53
|
+
this.minNode = z.right;
|
|
54
|
+
this.consolidate();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
this.nodeCount--;
|
|
58
|
+
return z.value;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
size(): number {
|
|
62
|
+
return this.nodeCount;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ========== Internal Methods ==========
|
|
66
|
+
|
|
67
|
+
private consolidate(): void {
|
|
68
|
+
const maxDegree = Math.floor(Math.log2(this.nodeCount)) + 1;
|
|
69
|
+
const A = new Array<FibNode | null>(maxDegree).fill(null);
|
|
70
|
+
|
|
71
|
+
const rootList: FibNode[] = [];
|
|
72
|
+
let curr = this.minNode!;
|
|
73
|
+
do {
|
|
74
|
+
rootList.push(curr);
|
|
75
|
+
curr = curr.right!;
|
|
76
|
+
} while (curr !== this.minNode);
|
|
77
|
+
|
|
78
|
+
for (const w of rootList) {
|
|
79
|
+
let x = w;
|
|
80
|
+
let d = x.degree;
|
|
81
|
+
while (A[d]) {
|
|
82
|
+
let y = A[d]!;
|
|
83
|
+
if (x.key > y.key) {
|
|
84
|
+
const temp = x;
|
|
85
|
+
x = y;
|
|
86
|
+
y = temp;
|
|
87
|
+
}
|
|
88
|
+
this.link(y, x);
|
|
89
|
+
A[d] = null;
|
|
90
|
+
d++;
|
|
91
|
+
}
|
|
92
|
+
A[d] = x;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
this.minNode = null;
|
|
96
|
+
for (const node of A) {
|
|
97
|
+
if (node) {
|
|
98
|
+
this.minNode = this.mergeLists(this.minNode, node);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private link(y: FibNode, x: FibNode): void {
|
|
104
|
+
this.removeFromList(y);
|
|
105
|
+
y.left = y.right = y;
|
|
106
|
+
x.child = this.mergeLists(x.child, y);
|
|
107
|
+
y.parent = x;
|
|
108
|
+
x.degree++;
|
|
109
|
+
y.mark = false;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private mergeLists(a: FibNode | null, b: FibNode | null): FibNode {
|
|
113
|
+
if (!a) return b!;
|
|
114
|
+
if (!b) return a;
|
|
115
|
+
|
|
116
|
+
const aRight = a.right!;
|
|
117
|
+
const bRight = b.right!;
|
|
118
|
+
|
|
119
|
+
a.right = bRight;
|
|
120
|
+
bRight.left = a;
|
|
121
|
+
b.right = aRight;
|
|
122
|
+
aRight.left = b;
|
|
123
|
+
|
|
124
|
+
return a.key < b.key ? a : b;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private removeFromList(node: FibNode): void {
|
|
128
|
+
node.left.right = node.right;
|
|
129
|
+
node.right.left = node.left;
|
|
130
|
+
}
|
|
131
|
+
}
|
package/src/terra-route.spec.ts
CHANGED
|
@@ -356,6 +356,7 @@ describe("TerraRoute", () => {
|
|
|
356
356
|
const result = routeFinder.getRoute(start, end);
|
|
357
357
|
|
|
358
358
|
expect(result).not.toBeNull();
|
|
359
|
+
expect(getReasonIfLineStringInvalid(result)).toBe(undefined);
|
|
359
360
|
|
|
360
361
|
// Should take diagonals: (0,0) → (0.01,0.01) → (0.05,0.05)
|
|
361
362
|
const expectedRoute = [
|
|
@@ -371,7 +372,7 @@ describe("TerraRoute", () => {
|
|
|
371
372
|
|
|
372
373
|
const resultTwo = routeFinder.getRoute(end, start);
|
|
373
374
|
expect(resultTwo).not.toBeNull();
|
|
374
|
-
expect(getReasonIfLineStringInvalid(
|
|
375
|
+
expect(getReasonIfLineStringInvalid(resultTwo)).toBe(undefined);
|
|
375
376
|
expect(resultTwo!.geometry.coordinates).toEqual(expectedRoute.reverse());
|
|
376
377
|
})
|
|
377
378
|
|
package/src/terra-route.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { FeatureCollection, LineString, Point, Feature, Position } from "geojson";
|
|
2
|
-
import {
|
|
2
|
+
import { FibonacciHeap } from "./fibonacci-heap";
|
|
3
3
|
import { haversineDistance } from "./distance/haversine";
|
|
4
4
|
import { createCheapRuler } from "./distance/cheap-ruler";
|
|
5
5
|
|
|
@@ -102,8 +102,8 @@ class TerraRoute {
|
|
|
102
102
|
return null;
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
-
const openSetForward = new
|
|
106
|
-
const openSetBackward = new
|
|
105
|
+
const openSetForward = new FibonacciHeap();
|
|
106
|
+
const openSetBackward = new FibonacciHeap();
|
|
107
107
|
openSetForward.insert(0, startIndex);
|
|
108
108
|
openSetBackward.insert(0, endIndex);
|
|
109
109
|
|
|
@@ -374,6 +374,8 @@ export function getReasonIfLineStringInvalid(
|
|
|
374
374
|
return `Not enough coordinates: ${coords.length} (${coords})`;
|
|
375
375
|
}
|
|
376
376
|
|
|
377
|
+
const seen = new Set<string>();
|
|
378
|
+
|
|
377
379
|
// 5. Validate each coordinate is a valid Position
|
|
378
380
|
// (At minimum, [number, number] or [number, number, number])
|
|
379
381
|
for (const position of coords) {
|
|
@@ -389,5 +391,12 @@ export function getReasonIfLineStringInvalid(
|
|
|
389
391
|
) {
|
|
390
392
|
return 'Not a Position; elements are not a numbers';
|
|
391
393
|
}
|
|
394
|
+
|
|
395
|
+
// 6. Check for duplicates
|
|
396
|
+
const key = `${position[0]},${position[1]}`;
|
|
397
|
+
if (seen.has(key)) {
|
|
398
|
+
return `Duplicate coordinate: ${key}`;
|
|
399
|
+
}
|
|
400
|
+
seen.add(key);
|
|
392
401
|
}
|
|
393
402
|
}
|
package/src/min-heap.spec.ts
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import { MinHeap } from './min-heap';
|
|
2
|
-
|
|
3
|
-
describe('MinHeap', () => {
|
|
4
|
-
let heap: MinHeap;
|
|
5
|
-
|
|
6
|
-
beforeEach(() => {
|
|
7
|
-
heap = new MinHeap();
|
|
8
|
-
});
|
|
9
|
-
|
|
10
|
-
it('should create an empty heap', () => {
|
|
11
|
-
expect(heap.size()).toBe(0);
|
|
12
|
-
});
|
|
13
|
-
|
|
14
|
-
it('should insert a single element', () => {
|
|
15
|
-
heap.insert(5, 100);
|
|
16
|
-
expect(heap.size()).toBe(1);
|
|
17
|
-
expect(heap.extractMin()).toBe(100);
|
|
18
|
-
expect(heap.size()).toBe(0);
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
it('should maintain correct heap order when inserting multiple elements', () => {
|
|
22
|
-
heap.insert(10, 200);
|
|
23
|
-
heap.insert(5, 100);
|
|
24
|
-
heap.insert(3, 50);
|
|
25
|
-
heap.insert(7, 150);
|
|
26
|
-
|
|
27
|
-
expect(heap.size()).toBe(4);
|
|
28
|
-
expect(heap.extractMin()).toBe(50);
|
|
29
|
-
expect(heap.extractMin()).toBe(100);
|
|
30
|
-
expect(heap.extractMin()).toBe(150);
|
|
31
|
-
expect(heap.extractMin()).toBe(200);
|
|
32
|
-
expect(heap.size()).toBe(0);
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
it('should return null when extracting from an empty heap', () => {
|
|
36
|
-
expect(heap.extractMin()).toBeNull();
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
it('should handle duplicate keys properly', () => {
|
|
40
|
-
heap.insert(5, 100);
|
|
41
|
-
heap.insert(5, 200);
|
|
42
|
-
heap.insert(5, 300);
|
|
43
|
-
|
|
44
|
-
expect(heap.size()).toBe(3);
|
|
45
|
-
expect(heap.extractMin()).toBe(100);
|
|
46
|
-
expect(heap.extractMin()).toBe(200);
|
|
47
|
-
expect(heap.extractMin()).toBe(300);
|
|
48
|
-
expect(heap.size()).toBe(0);
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
it('should correctly reorder after sequential insert and extract', () => {
|
|
52
|
-
heap.insert(10, 100);
|
|
53
|
-
heap.insert(1, 50);
|
|
54
|
-
expect(heap.extractMin()).toBe(50);
|
|
55
|
-
|
|
56
|
-
heap.insert(2, 60);
|
|
57
|
-
heap.insert(3, 70);
|
|
58
|
-
expect(heap.extractMin()).toBe(60);
|
|
59
|
-
expect(heap.extractMin()).toBe(70);
|
|
60
|
-
expect(heap.extractMin()).toBe(100);
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
it('should handle large number of elements correctly', () => {
|
|
64
|
-
const elements = Array.from({ length: 1000 }, (_, i) => ({ key: 1000 - i, value: i }));
|
|
65
|
-
elements.forEach(el => heap.insert(el.key, el.value));
|
|
66
|
-
|
|
67
|
-
expect(heap.size()).toBe(1000);
|
|
68
|
-
|
|
69
|
-
for (let i = 999; i >= 0; i--) {
|
|
70
|
-
expect(heap.extractMin()).toBe(i);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
expect(heap.size()).toBe(0);
|
|
74
|
-
});
|
|
75
|
-
});
|
package/src/min-heap.ts
DELETED
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
export class MinHeap {
|
|
2
|
-
private heap: Array<{ key: number; value: number; index: number }> = [];
|
|
3
|
-
private insertCounter = 0;
|
|
4
|
-
|
|
5
|
-
insert(key: number, value: number): void {
|
|
6
|
-
const node = { key, value, index: this.insertCounter++ };
|
|
7
|
-
let idx = this.heap.length;
|
|
8
|
-
this.heap.push(node);
|
|
9
|
-
|
|
10
|
-
// Optimized Bubble Up
|
|
11
|
-
while (idx > 0) {
|
|
12
|
-
const parentIdx = (idx - 1) >>> 1; // Fast Math.floor((idx - 1) / 2)
|
|
13
|
-
const parent = this.heap[parentIdx];
|
|
14
|
-
if (node.key > parent.key || (node.key === parent.key && node.index > parent.index)) break;
|
|
15
|
-
this.heap[idx] = parent;
|
|
16
|
-
idx = parentIdx;
|
|
17
|
-
}
|
|
18
|
-
this.heap[idx] = node;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
extractMin(): number | null {
|
|
22
|
-
const length = this.heap.length;
|
|
23
|
-
if (length === 0) return null;
|
|
24
|
-
|
|
25
|
-
const minNode = this.heap[0];
|
|
26
|
-
const endNode = this.heap.pop()!;
|
|
27
|
-
|
|
28
|
-
if (length > 1) {
|
|
29
|
-
this.heap[0] = endNode;
|
|
30
|
-
this.bubbleDown(0);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
return minNode.value;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
size(): number {
|
|
37
|
-
return this.heap.length;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
private bubbleDown(idx: number): void {
|
|
41
|
-
const { heap } = this;
|
|
42
|
-
const length = heap.length;
|
|
43
|
-
// Grab the parent node once, then move it down only if needed
|
|
44
|
-
const node = heap[idx];
|
|
45
|
-
const nodeKey = node.key;
|
|
46
|
-
const nodeIndex = node.index;
|
|
47
|
-
|
|
48
|
-
while (true) {
|
|
49
|
-
// Calculate left and right child indexes
|
|
50
|
-
const leftIdx = (idx << 1) + 1;
|
|
51
|
-
if (leftIdx >= length) {
|
|
52
|
-
// No children => we’re already in place
|
|
53
|
-
break;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// Assume left child is the smaller one by default
|
|
57
|
-
let smallestIdx = leftIdx;
|
|
58
|
-
let smallestKey = heap[leftIdx].key;
|
|
59
|
-
let smallestIndex = heap[leftIdx].index;
|
|
60
|
-
|
|
61
|
-
const rightIdx = leftIdx + 1;
|
|
62
|
-
if (rightIdx < length) {
|
|
63
|
-
// Compare left child vs. right child
|
|
64
|
-
const rightKey = heap[rightIdx].key;
|
|
65
|
-
const rightIndex = heap[rightIdx].index;
|
|
66
|
-
if (rightKey < smallestKey || (rightKey === smallestKey && rightIndex < smallestIndex)) {
|
|
67
|
-
smallestIdx = rightIdx;
|
|
68
|
-
smallestKey = rightKey;
|
|
69
|
-
smallestIndex = rightIndex;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// Compare the smaller child with the parent
|
|
74
|
-
if (smallestKey < nodeKey || (smallestKey === nodeKey && smallestIndex < nodeIndex)) {
|
|
75
|
-
// Swap the smaller child up
|
|
76
|
-
heap[idx] = heap[smallestIdx];
|
|
77
|
-
idx = smallestIdx;
|
|
78
|
-
} else {
|
|
79
|
-
// We’re in the correct position now, so stop
|
|
80
|
-
break;
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// Place the original node in its final position
|
|
85
|
-
heap[idx] = node;
|
|
86
|
-
}
|
|
87
|
-
}
|