Graph.js 11 KB

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