Graph.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import Node from "./Node.js";
  2. import Edge from "./Edge.js";
  3. import EdgeRing from "./EdgeRing.js";
  4. import { flattenEach, coordReduce } from "@turf/meta";
  5. import { featureOf } from "@turf/invariant";
  6. /**
  7. * Validates the geoJson.
  8. *
  9. * @param {GeoJSON} geoJson - input geoJson.
  10. * @throws {Error} if geoJson is invalid.
  11. */
  12. function validateGeoJson(geoJson) {
  13. if (!geoJson)
  14. throw new Error("No geojson passed");
  15. if (geoJson.type !== "FeatureCollection" &&
  16. geoJson.type !== "GeometryCollection" &&
  17. geoJson.type !== "MultiLineString" &&
  18. geoJson.type !== "LineString" &&
  19. geoJson.type !== "Feature")
  20. throw new Error("Invalid input type '" + geoJson.type + "'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature");
  21. }
  22. /**
  23. * Represents a planar graph of edges and nodes that can be used to compute a polygonization.
  24. *
  25. * Although, this class is inspired by GEOS's `geos::operation::polygonize::PolygonizeGraph`,
  26. * it isn't a rewrite. As regards algorithm, this class implements the same logic, but it
  27. * isn't a javascript transcription of the C++ source.
  28. *
  29. * This graph is directed (both directions are created)
  30. */
  31. var Graph = /** @class */ (function () {
  32. function Graph() {
  33. this.edges = []; //< {Edge[]} dirEdges
  34. // The key is the `id` of the Node (ie: coordinates.join(','))
  35. this.nodes = {};
  36. }
  37. /**
  38. * Creates a graph from a GeoJSON.
  39. *
  40. * @param {FeatureCollection<LineString>} geoJson - it must comply with the restrictions detailed in the index
  41. * @returns {Graph} - The newly created graph
  42. * @throws {Error} if geoJson is invalid.
  43. */
  44. Graph.fromGeoJson = function (geoJson) {
  45. validateGeoJson(geoJson);
  46. var graph = new Graph();
  47. flattenEach(geoJson, function (feature) {
  48. featureOf(feature, "LineString", "Graph::fromGeoJson");
  49. // When a LineString if formed by many segments, split them
  50. coordReduce(feature, function (prev, cur) {
  51. if (prev) {
  52. var start = graph.getNode(prev), end = graph.getNode(cur);
  53. graph.addEdge(start, end);
  54. }
  55. return cur;
  56. });
  57. });
  58. return graph;
  59. };
  60. /**
  61. * Creates or get a Node.
  62. *
  63. * @param {number[]} coordinates - Coordinates of the node
  64. * @returns {Node} - The created or stored node
  65. */
  66. Graph.prototype.getNode = function (coordinates) {
  67. var id = Node.buildId(coordinates);
  68. var node = this.nodes[id];
  69. if (!node)
  70. node = this.nodes[id] = new Node(coordinates);
  71. return node;
  72. };
  73. /**
  74. * Adds an Edge and its symetricall.
  75. *
  76. * Edges are added symetrically, i.e.: we also add its symetric
  77. *
  78. * @param {Node} from - Node which starts the Edge
  79. * @param {Node} to - Node which ends the Edge
  80. */
  81. Graph.prototype.addEdge = function (from, to) {
  82. var edge = new Edge(from, to), symetricEdge = edge.getSymetric();
  83. this.edges.push(edge);
  84. this.edges.push(symetricEdge);
  85. };
  86. /**
  87. * Removes Dangle Nodes (nodes with grade 1).
  88. */
  89. Graph.prototype.deleteDangles = function () {
  90. var _this = this;
  91. Object.keys(this.nodes)
  92. .map(function (id) { return _this.nodes[id]; })
  93. .forEach(function (node) { return _this._removeIfDangle(node); });
  94. };
  95. /**
  96. * Check if node is dangle, if so, remove it.
  97. *
  98. * It calls itself recursively, removing a dangling node might cause another dangling node
  99. *
  100. * @param {Node} node - Node to check if it's a dangle
  101. */
  102. Graph.prototype._removeIfDangle = function (node) {
  103. var _this = this;
  104. // As edges are directed and symetrical, we count only innerEdges
  105. if (node.innerEdges.length <= 1) {
  106. var outerNodes = node.getOuterEdges().map(function (e) { return e.to; });
  107. this.removeNode(node);
  108. outerNodes.forEach(function (n) { return _this._removeIfDangle(n); });
  109. }
  110. };
  111. /**
  112. * Delete cut-edges (bridge edges).
  113. *
  114. * The graph will be traversed, all the edges will be labeled according the ring
  115. * in which they are. (The label is a number incremented by 1). Edges with the same
  116. * label are cut-edges.
  117. */
  118. Graph.prototype.deleteCutEdges = function () {
  119. var _this = this;
  120. this._computeNextCWEdges();
  121. this._findLabeledEdgeRings();
  122. // Cut-edges (bridges) are edges where both edges have the same label
  123. this.edges.forEach(function (edge) {
  124. if (edge.label === edge.symetric.label) {
  125. _this.removeEdge(edge.symetric);
  126. _this.removeEdge(edge);
  127. }
  128. });
  129. };
  130. /**
  131. * Set the `next` property of each Edge.
  132. *
  133. * The graph will be transversed in a CW form, so, we set the next of the symetrical edge as the previous one.
  134. * OuterEdges are sorted CCW.
  135. *
  136. * @param {Node} [node] - If no node is passed, the function calls itself for every node in the Graph
  137. */
  138. Graph.prototype._computeNextCWEdges = function (node) {
  139. var _this = this;
  140. if (typeof node === "undefined") {
  141. Object.keys(this.nodes).forEach(function (id) {
  142. return _this._computeNextCWEdges(_this.nodes[id]);
  143. });
  144. }
  145. else {
  146. node.getOuterEdges().forEach(function (edge, i) {
  147. node.getOuterEdge((i === 0 ? node.getOuterEdges().length : i) - 1).symetric.next = edge;
  148. });
  149. }
  150. };
  151. /**
  152. * Computes the next edge pointers going CCW around the given node, for the given edgering label.
  153. *
  154. * This algorithm has the effect of converting maximal edgerings into minimal edgerings
  155. *
  156. * XXX: method literally transcribed from `geos::operation::polygonize::PolygonizeGraph::computeNextCCWEdges`,
  157. * could be written in a more javascript way.
  158. *
  159. * @param {Node} node - Node
  160. * @param {number} label - Ring's label
  161. */
  162. Graph.prototype._computeNextCCWEdges = function (node, label) {
  163. var edges = node.getOuterEdges();
  164. var firstOutDE, prevInDE;
  165. for (var i = edges.length - 1; i >= 0; --i) {
  166. var de = edges[i], sym = de.symetric, outDE = void 0, inDE = void 0;
  167. if (de.label === label)
  168. outDE = de;
  169. if (sym.label === label)
  170. inDE = sym;
  171. if (!outDE || !inDE)
  172. // This edge is not in edgering
  173. continue;
  174. if (inDE)
  175. prevInDE = inDE;
  176. if (outDE) {
  177. if (prevInDE) {
  178. prevInDE.next = outDE;
  179. prevInDE = undefined;
  180. }
  181. if (!firstOutDE)
  182. firstOutDE = outDE;
  183. }
  184. }
  185. if (prevInDE)
  186. prevInDE.next = firstOutDE;
  187. };
  188. /**
  189. * Finds rings and labels edges according to which rings are.
  190. *
  191. * The label is a number which is increased for each ring.
  192. *
  193. * @returns {Edge[]} edges that start rings
  194. */
  195. Graph.prototype._findLabeledEdgeRings = function () {
  196. var edgeRingStarts = [];
  197. var label = 0;
  198. this.edges.forEach(function (edge) {
  199. if (edge.label >= 0)
  200. return;
  201. edgeRingStarts.push(edge);
  202. var e = edge;
  203. do {
  204. e.label = label;
  205. e = e.next;
  206. } while (!edge.isEqual(e));
  207. label++;
  208. });
  209. return edgeRingStarts;
  210. };
  211. /**
  212. * Computes the EdgeRings formed by the edges in this graph.
  213. *
  214. * @returns {EdgeRing[]} - A list of all the EdgeRings in the graph.
  215. */
  216. Graph.prototype.getEdgeRings = function () {
  217. var _this = this;
  218. this._computeNextCWEdges();
  219. // Clear labels
  220. this.edges.forEach(function (edge) {
  221. edge.label = undefined;
  222. });
  223. this._findLabeledEdgeRings().forEach(function (edge) {
  224. // convertMaximalToMinimalEdgeRings
  225. _this._findIntersectionNodes(edge).forEach(function (node) {
  226. _this._computeNextCCWEdges(node, edge.label);
  227. });
  228. });
  229. var edgeRingList = [];
  230. // find all edgerings
  231. this.edges.forEach(function (edge) {
  232. if (edge.ring)
  233. return;
  234. edgeRingList.push(_this._findEdgeRing(edge));
  235. });
  236. return edgeRingList;
  237. };
  238. /**
  239. * Find all nodes in a Maxima EdgeRing which are self-intersection nodes.
  240. *
  241. * @param {Node} startEdge - Start Edge of the Ring
  242. * @returns {Node[]} - intersection nodes
  243. */
  244. Graph.prototype._findIntersectionNodes = function (startEdge) {
  245. var intersectionNodes = [];
  246. var edge = startEdge;
  247. var _loop_1 = function () {
  248. // getDegree
  249. var degree = 0;
  250. edge.from.getOuterEdges().forEach(function (e) {
  251. if (e.label === startEdge.label)
  252. ++degree;
  253. });
  254. if (degree > 1)
  255. intersectionNodes.push(edge.from);
  256. edge = edge.next;
  257. };
  258. do {
  259. _loop_1();
  260. } while (!startEdge.isEqual(edge));
  261. return intersectionNodes;
  262. };
  263. /**
  264. * Get the edge-ring which starts from the provided Edge.
  265. *
  266. * @param {Edge} startEdge - starting edge of the edge ring
  267. * @returns {EdgeRing} - EdgeRing which start Edge is the provided one.
  268. */
  269. Graph.prototype._findEdgeRing = function (startEdge) {
  270. var edge = startEdge;
  271. var edgeRing = new EdgeRing();
  272. do {
  273. edgeRing.push(edge);
  274. edge.ring = edgeRing;
  275. edge = edge.next;
  276. } while (!startEdge.isEqual(edge));
  277. return edgeRing;
  278. };
  279. /**
  280. * Removes a node from the Graph.
  281. *
  282. * It also removes edges asociated to that node
  283. * @param {Node} node - Node to be removed
  284. */
  285. Graph.prototype.removeNode = function (node) {
  286. var _this = this;
  287. node.getOuterEdges().forEach(function (edge) { return _this.removeEdge(edge); });
  288. node.innerEdges.forEach(function (edge) { return _this.removeEdge(edge); });
  289. delete this.nodes[node.id];
  290. };
  291. /**
  292. * Remove edge from the graph and deletes the edge.
  293. *
  294. * @param {Edge} edge - Edge to be removed
  295. */
  296. Graph.prototype.removeEdge = function (edge) {
  297. this.edges = this.edges.filter(function (e) { return !e.isEqual(edge); });
  298. edge.deleteEdge();
  299. };
  300. return Graph;
  301. }());
  302. export default Graph;