planarity.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  1. from collections import defaultdict
  2. from copy import deepcopy
  3. import networkx as nx
  4. __all__ = ["check_planarity", "is_planar", "PlanarEmbedding"]
  5. @nx._dispatchable
  6. def is_planar(G):
  7. """Returns True if and only if `G` is planar.
  8. A graph is *planar* iff it can be drawn in a plane without
  9. any edge intersections.
  10. Parameters
  11. ----------
  12. G : NetworkX graph
  13. Returns
  14. -------
  15. bool
  16. Whether the graph is planar.
  17. Examples
  18. --------
  19. >>> G = nx.Graph([(0, 1), (0, 2)])
  20. >>> nx.is_planar(G)
  21. True
  22. >>> nx.is_planar(nx.complete_graph(5))
  23. False
  24. See Also
  25. --------
  26. check_planarity :
  27. Check if graph is planar *and* return a `PlanarEmbedding` instance if True.
  28. """
  29. return check_planarity(G, counterexample=False)[0]
  30. @nx._dispatchable(returns_graph=True)
  31. def check_planarity(G, counterexample=False):
  32. """Check if a graph is planar and return a counterexample or an embedding.
  33. A graph is planar iff it can be drawn in a plane without
  34. any edge intersections.
  35. Parameters
  36. ----------
  37. G : NetworkX graph
  38. counterexample : bool
  39. A Kuratowski subgraph (to proof non planarity) is only returned if set
  40. to true.
  41. Returns
  42. -------
  43. (is_planar, certificate) : (bool, NetworkX graph) tuple
  44. is_planar is true if the graph is planar.
  45. If the graph is planar `certificate` is a PlanarEmbedding
  46. otherwise it is a Kuratowski subgraph.
  47. Examples
  48. --------
  49. >>> G = nx.Graph([(0, 1), (0, 2)])
  50. >>> is_planar, P = nx.check_planarity(G)
  51. >>> print(is_planar)
  52. True
  53. When `G` is planar, a `PlanarEmbedding` instance is returned:
  54. >>> P.get_data()
  55. {0: [1, 2], 1: [0], 2: [0]}
  56. Notes
  57. -----
  58. A (combinatorial) embedding consists of cyclic orderings of the incident
  59. edges at each vertex. Given such an embedding there are multiple approaches
  60. discussed in literature to drawing the graph (subject to various
  61. constraints, e.g. integer coordinates), see e.g. [2].
  62. The planarity check algorithm and extraction of the combinatorial embedding
  63. is based on the Left-Right Planarity Test [1].
  64. A counterexample is only generated if the corresponding parameter is set,
  65. because the complexity of the counterexample generation is higher.
  66. See also
  67. --------
  68. is_planar :
  69. Check for planarity without creating a `PlanarEmbedding` or counterexample.
  70. References
  71. ----------
  72. .. [1] Ulrik Brandes:
  73. The Left-Right Planarity Test
  74. 2009
  75. http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.217.9208
  76. .. [2] Takao Nishizeki, Md Saidur Rahman:
  77. Planar graph drawing
  78. Lecture Notes Series on Computing: Volume 12
  79. 2004
  80. """
  81. planarity_state = LRPlanarity(G)
  82. embedding = planarity_state.lr_planarity()
  83. if embedding is None:
  84. # graph is not planar
  85. if counterexample:
  86. return False, get_counterexample(G)
  87. else:
  88. return False, None
  89. else:
  90. # graph is planar
  91. return True, embedding
  92. @nx._dispatchable(returns_graph=True)
  93. def check_planarity_recursive(G, counterexample=False):
  94. """Recursive version of :meth:`check_planarity`."""
  95. planarity_state = LRPlanarity(G)
  96. embedding = planarity_state.lr_planarity_recursive()
  97. if embedding is None:
  98. # graph is not planar
  99. if counterexample:
  100. return False, get_counterexample_recursive(G)
  101. else:
  102. return False, None
  103. else:
  104. # graph is planar
  105. return True, embedding
  106. @nx._dispatchable(returns_graph=True)
  107. def get_counterexample(G):
  108. """Obtains a Kuratowski subgraph.
  109. Raises nx.NetworkXException if G is planar.
  110. The function removes edges such that the graph is still not planar.
  111. At some point the removal of any edge would make the graph planar.
  112. This subgraph must be a Kuratowski subgraph.
  113. Parameters
  114. ----------
  115. G : NetworkX graph
  116. Returns
  117. -------
  118. subgraph : NetworkX graph
  119. A Kuratowski subgraph that proves that G is not planar.
  120. """
  121. # copy graph
  122. G = nx.Graph(G)
  123. if check_planarity(G)[0]:
  124. raise nx.NetworkXException("G is planar - no counter example.")
  125. # find Kuratowski subgraph
  126. subgraph = nx.Graph()
  127. for u in G:
  128. nbrs = list(G[u])
  129. for v in nbrs:
  130. G.remove_edge(u, v)
  131. if check_planarity(G)[0]:
  132. G.add_edge(u, v)
  133. subgraph.add_edge(u, v)
  134. return subgraph
  135. @nx._dispatchable(returns_graph=True)
  136. def get_counterexample_recursive(G):
  137. """Recursive version of :meth:`get_counterexample`."""
  138. # copy graph
  139. G = nx.Graph(G)
  140. if check_planarity_recursive(G)[0]:
  141. raise nx.NetworkXException("G is planar - no counter example.")
  142. # find Kuratowski subgraph
  143. subgraph = nx.Graph()
  144. for u in G:
  145. nbrs = list(G[u])
  146. for v in nbrs:
  147. G.remove_edge(u, v)
  148. if check_planarity_recursive(G)[0]:
  149. G.add_edge(u, v)
  150. subgraph.add_edge(u, v)
  151. return subgraph
  152. class Interval:
  153. """Represents a set of return edges.
  154. All return edges in an interval induce a same constraint on the contained
  155. edges, which means that all edges must either have a left orientation or
  156. all edges must have a right orientation.
  157. """
  158. def __init__(self, low=None, high=None):
  159. self.low = low
  160. self.high = high
  161. def empty(self):
  162. """Check if the interval is empty"""
  163. return self.low is None and self.high is None
  164. def copy(self):
  165. """Returns a copy of this interval"""
  166. return Interval(self.low, self.high)
  167. def conflicting(self, b, planarity_state):
  168. """Returns True if interval I conflicts with edge b"""
  169. return (
  170. not self.empty()
  171. and planarity_state.lowpt[self.high] > planarity_state.lowpt[b]
  172. )
  173. class ConflictPair:
  174. """Represents a different constraint between two intervals.
  175. The edges in the left interval must have a different orientation than
  176. the one in the right interval.
  177. """
  178. def __init__(self, left=Interval(), right=Interval()):
  179. self.left = left
  180. self.right = right
  181. def swap(self):
  182. """Swap left and right intervals"""
  183. temp = self.left
  184. self.left = self.right
  185. self.right = temp
  186. def lowest(self, planarity_state):
  187. """Returns the lowest lowpoint of a conflict pair"""
  188. if self.left.empty():
  189. return planarity_state.lowpt[self.right.low]
  190. if self.right.empty():
  191. return planarity_state.lowpt[self.left.low]
  192. return min(
  193. planarity_state.lowpt[self.left.low], planarity_state.lowpt[self.right.low]
  194. )
  195. def top_of_stack(l):
  196. """Returns the element on top of the stack."""
  197. if not l:
  198. return None
  199. return l[-1]
  200. class LRPlanarity:
  201. """A class to maintain the state during planarity check."""
  202. __slots__ = [
  203. "G",
  204. "roots",
  205. "height",
  206. "lowpt",
  207. "lowpt2",
  208. "nesting_depth",
  209. "parent_edge",
  210. "DG",
  211. "adjs",
  212. "ordered_adjs",
  213. "ref",
  214. "side",
  215. "S",
  216. "stack_bottom",
  217. "lowpt_edge",
  218. "left_ref",
  219. "right_ref",
  220. "embedding",
  221. ]
  222. def __init__(self, G):
  223. # copy G without adding self-loops
  224. self.G = nx.Graph()
  225. self.G.add_nodes_from(G.nodes)
  226. for e in G.edges:
  227. if e[0] != e[1]:
  228. self.G.add_edge(e[0], e[1])
  229. self.roots = []
  230. # distance from tree root
  231. self.height = defaultdict(lambda: None)
  232. self.lowpt = {} # height of lowest return point of an edge
  233. self.lowpt2 = {} # height of second lowest return point
  234. self.nesting_depth = {} # for nesting order
  235. # None -> missing edge
  236. self.parent_edge = defaultdict(lambda: None)
  237. # oriented DFS graph
  238. self.DG = nx.DiGraph()
  239. self.DG.add_nodes_from(G.nodes)
  240. self.adjs = {}
  241. self.ordered_adjs = {}
  242. self.ref = defaultdict(lambda: None)
  243. self.side = defaultdict(lambda: 1)
  244. # stack of conflict pairs
  245. self.S = []
  246. self.stack_bottom = {}
  247. self.lowpt_edge = {}
  248. self.left_ref = {}
  249. self.right_ref = {}
  250. self.embedding = PlanarEmbedding()
  251. def lr_planarity(self):
  252. """Execute the LR planarity test.
  253. Returns
  254. -------
  255. embedding : dict
  256. If the graph is planar an embedding is returned. Otherwise None.
  257. """
  258. if self.G.order() > 2 and self.G.size() > 3 * self.G.order() - 6:
  259. # graph is not planar
  260. return None
  261. # make adjacency lists for dfs
  262. for v in self.G:
  263. self.adjs[v] = list(self.G[v])
  264. # orientation of the graph by depth first search traversal
  265. for v in self.G:
  266. if self.height[v] is None:
  267. self.height[v] = 0
  268. self.roots.append(v)
  269. self.dfs_orientation(v)
  270. # Free no longer used variables
  271. self.G = None
  272. self.lowpt2 = None
  273. self.adjs = None
  274. # testing
  275. for v in self.DG: # sort the adjacency lists by nesting depth
  276. # note: this sorting leads to non linear time
  277. self.ordered_adjs[v] = sorted(
  278. self.DG[v], key=lambda x: self.nesting_depth[(v, x)]
  279. )
  280. for v in self.roots:
  281. if not self.dfs_testing(v):
  282. return None
  283. # Free no longer used variables
  284. self.height = None
  285. self.lowpt = None
  286. self.S = None
  287. self.stack_bottom = None
  288. self.lowpt_edge = None
  289. for e in self.DG.edges:
  290. self.nesting_depth[e] = self.sign(e) * self.nesting_depth[e]
  291. self.embedding.add_nodes_from(self.DG.nodes)
  292. for v in self.DG:
  293. # sort the adjacency lists again
  294. self.ordered_adjs[v] = sorted(
  295. self.DG[v], key=lambda x: self.nesting_depth[(v, x)]
  296. )
  297. # initialize the embedding
  298. previous_node = None
  299. for w in self.ordered_adjs[v]:
  300. self.embedding.add_half_edge(v, w, ccw=previous_node)
  301. previous_node = w
  302. # Free no longer used variables
  303. self.DG = None
  304. self.nesting_depth = None
  305. self.ref = None
  306. # compute the complete embedding
  307. for v in self.roots:
  308. self.dfs_embedding(v)
  309. # Free no longer used variables
  310. self.roots = None
  311. self.parent_edge = None
  312. self.ordered_adjs = None
  313. self.left_ref = None
  314. self.right_ref = None
  315. self.side = None
  316. return self.embedding
  317. def lr_planarity_recursive(self):
  318. """Recursive version of :meth:`lr_planarity`."""
  319. if self.G.order() > 2 and self.G.size() > 3 * self.G.order() - 6:
  320. # graph is not planar
  321. return None
  322. # orientation of the graph by depth first search traversal
  323. for v in self.G:
  324. if self.height[v] is None:
  325. self.height[v] = 0
  326. self.roots.append(v)
  327. self.dfs_orientation_recursive(v)
  328. # Free no longer used variable
  329. self.G = None
  330. # testing
  331. for v in self.DG: # sort the adjacency lists by nesting depth
  332. # note: this sorting leads to non linear time
  333. self.ordered_adjs[v] = sorted(
  334. self.DG[v], key=lambda x: self.nesting_depth[(v, x)]
  335. )
  336. for v in self.roots:
  337. if not self.dfs_testing_recursive(v):
  338. return None
  339. for e in self.DG.edges:
  340. self.nesting_depth[e] = self.sign_recursive(e) * self.nesting_depth[e]
  341. self.embedding.add_nodes_from(self.DG.nodes)
  342. for v in self.DG:
  343. # sort the adjacency lists again
  344. self.ordered_adjs[v] = sorted(
  345. self.DG[v], key=lambda x: self.nesting_depth[(v, x)]
  346. )
  347. # initialize the embedding
  348. previous_node = None
  349. for w in self.ordered_adjs[v]:
  350. self.embedding.add_half_edge(v, w, ccw=previous_node)
  351. previous_node = w
  352. # compute the complete embedding
  353. for v in self.roots:
  354. self.dfs_embedding_recursive(v)
  355. return self.embedding
  356. def dfs_orientation(self, v):
  357. """Orient the graph by DFS, compute lowpoints and nesting order."""
  358. # the recursion stack
  359. dfs_stack = [v]
  360. # index of next edge to handle in adjacency list of each node
  361. ind = defaultdict(lambda: 0)
  362. # boolean to indicate whether to skip the initial work for an edge
  363. skip_init = defaultdict(lambda: False)
  364. while dfs_stack:
  365. v = dfs_stack.pop()
  366. e = self.parent_edge[v]
  367. for w in self.adjs[v][ind[v] :]:
  368. vw = (v, w)
  369. if not skip_init[vw]:
  370. if (v, w) in self.DG.edges or (w, v) in self.DG.edges:
  371. ind[v] += 1
  372. continue # the edge was already oriented
  373. self.DG.add_edge(v, w) # orient the edge
  374. self.lowpt[vw] = self.height[v]
  375. self.lowpt2[vw] = self.height[v]
  376. if self.height[w] is None: # (v, w) is a tree edge
  377. self.parent_edge[w] = vw
  378. self.height[w] = self.height[v] + 1
  379. dfs_stack.append(v) # revisit v after finishing w
  380. dfs_stack.append(w) # visit w next
  381. skip_init[vw] = True # don't redo this block
  382. break # handle next node in dfs_stack (i.e. w)
  383. else: # (v, w) is a back edge
  384. self.lowpt[vw] = self.height[w]
  385. # determine nesting graph
  386. self.nesting_depth[vw] = 2 * self.lowpt[vw]
  387. if self.lowpt2[vw] < self.height[v]: # chordal
  388. self.nesting_depth[vw] += 1
  389. # update lowpoints of parent edge e
  390. if e is not None:
  391. if self.lowpt[vw] < self.lowpt[e]:
  392. self.lowpt2[e] = min(self.lowpt[e], self.lowpt2[vw])
  393. self.lowpt[e] = self.lowpt[vw]
  394. elif self.lowpt[vw] > self.lowpt[e]:
  395. self.lowpt2[e] = min(self.lowpt2[e], self.lowpt[vw])
  396. else:
  397. self.lowpt2[e] = min(self.lowpt2[e], self.lowpt2[vw])
  398. ind[v] += 1
  399. def dfs_orientation_recursive(self, v):
  400. """Recursive version of :meth:`dfs_orientation`."""
  401. e = self.parent_edge[v]
  402. for w in self.G[v]:
  403. if (v, w) in self.DG.edges or (w, v) in self.DG.edges:
  404. continue # the edge was already oriented
  405. vw = (v, w)
  406. self.DG.add_edge(v, w) # orient the edge
  407. self.lowpt[vw] = self.height[v]
  408. self.lowpt2[vw] = self.height[v]
  409. if self.height[w] is None: # (v, w) is a tree edge
  410. self.parent_edge[w] = vw
  411. self.height[w] = self.height[v] + 1
  412. self.dfs_orientation_recursive(w)
  413. else: # (v, w) is a back edge
  414. self.lowpt[vw] = self.height[w]
  415. # determine nesting graph
  416. self.nesting_depth[vw] = 2 * self.lowpt[vw]
  417. if self.lowpt2[vw] < self.height[v]: # chordal
  418. self.nesting_depth[vw] += 1
  419. # update lowpoints of parent edge e
  420. if e is not None:
  421. if self.lowpt[vw] < self.lowpt[e]:
  422. self.lowpt2[e] = min(self.lowpt[e], self.lowpt2[vw])
  423. self.lowpt[e] = self.lowpt[vw]
  424. elif self.lowpt[vw] > self.lowpt[e]:
  425. self.lowpt2[e] = min(self.lowpt2[e], self.lowpt[vw])
  426. else:
  427. self.lowpt2[e] = min(self.lowpt2[e], self.lowpt2[vw])
  428. def dfs_testing(self, v):
  429. """Test for LR partition."""
  430. # the recursion stack
  431. dfs_stack = [v]
  432. # index of next edge to handle in adjacency list of each node
  433. ind = defaultdict(lambda: 0)
  434. # boolean to indicate whether to skip the initial work for an edge
  435. skip_init = defaultdict(lambda: False)
  436. while dfs_stack:
  437. v = dfs_stack.pop()
  438. e = self.parent_edge[v]
  439. # to indicate whether to skip the final block after the for loop
  440. skip_final = False
  441. for w in self.ordered_adjs[v][ind[v] :]:
  442. ei = (v, w)
  443. if not skip_init[ei]:
  444. self.stack_bottom[ei] = top_of_stack(self.S)
  445. if ei == self.parent_edge[w]: # tree edge
  446. dfs_stack.append(v) # revisit v after finishing w
  447. dfs_stack.append(w) # visit w next
  448. skip_init[ei] = True # don't redo this block
  449. skip_final = True # skip final work after breaking
  450. break # handle next node in dfs_stack (i.e. w)
  451. else: # back edge
  452. self.lowpt_edge[ei] = ei
  453. self.S.append(ConflictPair(right=Interval(ei, ei)))
  454. # integrate new return edges
  455. if self.lowpt[ei] < self.height[v]:
  456. if w == self.ordered_adjs[v][0]: # e_i has return edge
  457. self.lowpt_edge[e] = self.lowpt_edge[ei]
  458. else: # add constraints of e_i
  459. if not self.add_constraints(ei, e):
  460. # graph is not planar
  461. return False
  462. ind[v] += 1
  463. if not skip_final:
  464. # remove back edges returning to parent
  465. if e is not None: # v isn't root
  466. self.remove_back_edges(e)
  467. return True
  468. def dfs_testing_recursive(self, v):
  469. """Recursive version of :meth:`dfs_testing`."""
  470. e = self.parent_edge[v]
  471. for w in self.ordered_adjs[v]:
  472. ei = (v, w)
  473. self.stack_bottom[ei] = top_of_stack(self.S)
  474. if ei == self.parent_edge[w]: # tree edge
  475. if not self.dfs_testing_recursive(w):
  476. return False
  477. else: # back edge
  478. self.lowpt_edge[ei] = ei
  479. self.S.append(ConflictPair(right=Interval(ei, ei)))
  480. # integrate new return edges
  481. if self.lowpt[ei] < self.height[v]:
  482. if w == self.ordered_adjs[v][0]: # e_i has return edge
  483. self.lowpt_edge[e] = self.lowpt_edge[ei]
  484. else: # add constraints of e_i
  485. if not self.add_constraints(ei, e):
  486. # graph is not planar
  487. return False
  488. # remove back edges returning to parent
  489. if e is not None: # v isn't root
  490. self.remove_back_edges(e)
  491. return True
  492. def add_constraints(self, ei, e):
  493. P = ConflictPair()
  494. # merge return edges of e_i into P.right
  495. while True:
  496. Q = self.S.pop()
  497. if not Q.left.empty():
  498. Q.swap()
  499. if not Q.left.empty(): # not planar
  500. return False
  501. if self.lowpt[Q.right.low] > self.lowpt[e]:
  502. # merge intervals
  503. if P.right.empty(): # topmost interval
  504. P.right = Q.right.copy()
  505. else:
  506. self.ref[P.right.low] = Q.right.high
  507. P.right.low = Q.right.low
  508. else: # align
  509. self.ref[Q.right.low] = self.lowpt_edge[e]
  510. if top_of_stack(self.S) == self.stack_bottom[ei]:
  511. break
  512. # merge conflicting return edges of e_1,...,e_i-1 into P.L
  513. while top_of_stack(self.S).left.conflicting(ei, self) or top_of_stack(
  514. self.S
  515. ).right.conflicting(ei, self):
  516. Q = self.S.pop()
  517. if Q.right.conflicting(ei, self):
  518. Q.swap()
  519. if Q.right.conflicting(ei, self): # not planar
  520. return False
  521. # merge interval below lowpt(e_i) into P.R
  522. self.ref[P.right.low] = Q.right.high
  523. if Q.right.low is not None:
  524. P.right.low = Q.right.low
  525. if P.left.empty(): # topmost interval
  526. P.left = Q.left.copy()
  527. else:
  528. self.ref[P.left.low] = Q.left.high
  529. P.left.low = Q.left.low
  530. if not (P.left.empty() and P.right.empty()):
  531. self.S.append(P)
  532. return True
  533. def remove_back_edges(self, e):
  534. u = e[0]
  535. # trim back edges ending at parent u
  536. # drop entire conflict pairs
  537. while self.S and top_of_stack(self.S).lowest(self) == self.height[u]:
  538. P = self.S.pop()
  539. if P.left.low is not None:
  540. self.side[P.left.low] = -1
  541. if self.S: # one more conflict pair to consider
  542. P = self.S.pop()
  543. # trim left interval
  544. while P.left.high is not None and P.left.high[1] == u:
  545. P.left.high = self.ref[P.left.high]
  546. if P.left.high is None and P.left.low is not None:
  547. # just emptied
  548. self.ref[P.left.low] = P.right.low
  549. self.side[P.left.low] = -1
  550. P.left.low = None
  551. # trim right interval
  552. while P.right.high is not None and P.right.high[1] == u:
  553. P.right.high = self.ref[P.right.high]
  554. if P.right.high is None and P.right.low is not None:
  555. # just emptied
  556. self.ref[P.right.low] = P.left.low
  557. self.side[P.right.low] = -1
  558. P.right.low = None
  559. self.S.append(P)
  560. # side of e is side of a highest return edge
  561. if self.lowpt[e] < self.height[u]: # e has return edge
  562. hl = top_of_stack(self.S).left.high
  563. hr = top_of_stack(self.S).right.high
  564. if hl is not None and (hr is None or self.lowpt[hl] > self.lowpt[hr]):
  565. self.ref[e] = hl
  566. else:
  567. self.ref[e] = hr
  568. def dfs_embedding(self, v):
  569. """Completes the embedding."""
  570. # the recursion stack
  571. dfs_stack = [v]
  572. # index of next edge to handle in adjacency list of each node
  573. ind = defaultdict(lambda: 0)
  574. while dfs_stack:
  575. v = dfs_stack.pop()
  576. for w in self.ordered_adjs[v][ind[v] :]:
  577. ind[v] += 1
  578. ei = (v, w)
  579. if ei == self.parent_edge[w]: # tree edge
  580. self.embedding.add_half_edge_first(w, v)
  581. self.left_ref[v] = w
  582. self.right_ref[v] = w
  583. dfs_stack.append(v) # revisit v after finishing w
  584. dfs_stack.append(w) # visit w next
  585. break # handle next node in dfs_stack (i.e. w)
  586. else: # back edge
  587. if self.side[ei] == 1:
  588. self.embedding.add_half_edge(w, v, ccw=self.right_ref[w])
  589. else:
  590. self.embedding.add_half_edge(w, v, cw=self.left_ref[w])
  591. self.left_ref[w] = v
  592. def dfs_embedding_recursive(self, v):
  593. """Recursive version of :meth:`dfs_embedding`."""
  594. for w in self.ordered_adjs[v]:
  595. ei = (v, w)
  596. if ei == self.parent_edge[w]: # tree edge
  597. self.embedding.add_half_edge_first(w, v)
  598. self.left_ref[v] = w
  599. self.right_ref[v] = w
  600. self.dfs_embedding_recursive(w)
  601. else: # back edge
  602. if self.side[ei] == 1:
  603. # place v directly after right_ref[w] in embed. list of w
  604. self.embedding.add_half_edge(w, v, ccw=self.right_ref[w])
  605. else:
  606. # place v directly before left_ref[w] in embed. list of w
  607. self.embedding.add_half_edge(w, v, cw=self.left_ref[w])
  608. self.left_ref[w] = v
  609. def sign(self, e):
  610. """Resolve the relative side of an edge to the absolute side."""
  611. # the recursion stack
  612. dfs_stack = [e]
  613. # dict to remember reference edges
  614. old_ref = defaultdict(lambda: None)
  615. while dfs_stack:
  616. e = dfs_stack.pop()
  617. if self.ref[e] is not None:
  618. dfs_stack.append(e) # revisit e after finishing self.ref[e]
  619. dfs_stack.append(self.ref[e]) # visit self.ref[e] next
  620. old_ref[e] = self.ref[e] # remember value of self.ref[e]
  621. self.ref[e] = None
  622. else:
  623. self.side[e] *= self.side[old_ref[e]]
  624. return self.side[e]
  625. def sign_recursive(self, e):
  626. """Recursive version of :meth:`sign`."""
  627. if self.ref[e] is not None:
  628. self.side[e] = self.side[e] * self.sign_recursive(self.ref[e])
  629. self.ref[e] = None
  630. return self.side[e]
  631. class PlanarEmbedding(nx.DiGraph):
  632. """Represents a planar graph with its planar embedding.
  633. The planar embedding is given by a `combinatorial embedding
  634. <https://en.wikipedia.org/wiki/Graph_embedding#Combinatorial_embedding>`_.
  635. .. note:: `check_planarity` is the preferred way to check if a graph is planar.
  636. **Neighbor ordering:**
  637. In comparison to a usual graph structure, the embedding also stores the
  638. order of all neighbors for every vertex.
  639. The order of the neighbors can be given in clockwise (cw) direction or
  640. counterclockwise (ccw) direction. This order is stored as edge attributes
  641. in the underlying directed graph. For the edge (u, v) the edge attribute
  642. 'cw' is set to the neighbor of u that follows immediately after v in
  643. clockwise direction.
  644. In order for a PlanarEmbedding to be valid it must fulfill multiple
  645. conditions. It is possible to check if these conditions are fulfilled with
  646. the method :meth:`check_structure`.
  647. The conditions are:
  648. * Edges must go in both directions (because the edge attributes differ)
  649. * Every edge must have a 'cw' and 'ccw' attribute which corresponds to a
  650. correct planar embedding.
  651. As long as a PlanarEmbedding is invalid only the following methods should
  652. be called:
  653. * :meth:`add_half_edge`
  654. * :meth:`connect_components`
  655. Even though the graph is a subclass of nx.DiGraph, it can still be used
  656. for algorithms that require undirected graphs, because the method
  657. :meth:`is_directed` is overridden. This is possible, because a valid
  658. PlanarGraph must have edges in both directions.
  659. **Half edges:**
  660. In methods like `add_half_edge` the term "half-edge" is used, which is
  661. a term that is used in `doubly connected edge lists
  662. <https://en.wikipedia.org/wiki/Doubly_connected_edge_list>`_. It is used
  663. to emphasize that the edge is only in one direction and there exists
  664. another half-edge in the opposite direction.
  665. While conventional edges always have two faces (including outer face) next
  666. to them, it is possible to assign each half-edge *exactly one* face.
  667. For a half-edge (u, v) that is oriented such that u is below v then the
  668. face that belongs to (u, v) is to the right of this half-edge.
  669. See Also
  670. --------
  671. is_planar :
  672. Preferred way to check if an existing graph is planar.
  673. check_planarity :
  674. A convenient way to create a `PlanarEmbedding`. If not planar,
  675. it returns a subgraph that shows this.
  676. Examples
  677. --------
  678. Create an embedding of a star graph (compare `nx.star_graph(3)`):
  679. >>> G = nx.PlanarEmbedding()
  680. >>> G.add_half_edge(0, 1)
  681. >>> G.add_half_edge(0, 2, ccw=1)
  682. >>> G.add_half_edge(0, 3, ccw=2)
  683. >>> G.add_half_edge(1, 0)
  684. >>> G.add_half_edge(2, 0)
  685. >>> G.add_half_edge(3, 0)
  686. Alternatively the same embedding can also be defined in counterclockwise
  687. orientation. The following results in exactly the same PlanarEmbedding:
  688. >>> G = nx.PlanarEmbedding()
  689. >>> G.add_half_edge(0, 1)
  690. >>> G.add_half_edge(0, 3, cw=1)
  691. >>> G.add_half_edge(0, 2, cw=3)
  692. >>> G.add_half_edge(1, 0)
  693. >>> G.add_half_edge(2, 0)
  694. >>> G.add_half_edge(3, 0)
  695. After creating a graph, it is possible to validate that the PlanarEmbedding
  696. object is correct:
  697. >>> G.check_structure()
  698. """
  699. def __init__(self, incoming_graph_data=None, **attr):
  700. super().__init__(incoming_graph_data=incoming_graph_data, **attr)
  701. self.add_edge = self._forbidden
  702. self.add_edges_from = self._forbidden
  703. self.add_weighted_edges_from = self._forbidden
  704. def _forbidden(self, *args, **kwargs):
  705. """Forbidden operation
  706. Any edge additions to a PlanarEmbedding should be done using
  707. method `add_half_edge`.
  708. """
  709. raise NotImplementedError(
  710. "Use `add_half_edge` method to add edges to a PlanarEmbedding."
  711. )
  712. def get_data(self):
  713. """Converts the adjacency structure into a better readable structure.
  714. Returns
  715. -------
  716. embedding : dict
  717. A dict mapping all nodes to a list of neighbors sorted in
  718. clockwise order.
  719. See Also
  720. --------
  721. set_data
  722. """
  723. embedding = {}
  724. for v in self:
  725. embedding[v] = list(self.neighbors_cw_order(v))
  726. return embedding
  727. def set_data(self, data):
  728. """Inserts edges according to given sorted neighbor list.
  729. The input format is the same as the output format of get_data().
  730. Parameters
  731. ----------
  732. data : dict
  733. A dict mapping all nodes to a list of neighbors sorted in
  734. clockwise order.
  735. See Also
  736. --------
  737. get_data
  738. """
  739. for v in data:
  740. ref = None
  741. for w in reversed(data[v]):
  742. self.add_half_edge(v, w, cw=ref)
  743. ref = w
  744. def remove_node(self, n):
  745. """Remove node n.
  746. Removes the node n and all adjacent edges, updating the
  747. PlanarEmbedding to account for any resulting edge removal.
  748. Attempting to remove a non-existent node will raise an exception.
  749. Parameters
  750. ----------
  751. n : node
  752. A node in the graph
  753. Raises
  754. ------
  755. NetworkXError
  756. If n is not in the graph.
  757. See Also
  758. --------
  759. remove_nodes_from
  760. """
  761. try:
  762. for u in self._pred[n]:
  763. succs_u = self._succ[u]
  764. un_cw = succs_u[n]["cw"]
  765. un_ccw = succs_u[n]["ccw"]
  766. del succs_u[n]
  767. del self._pred[u][n]
  768. if n != un_cw:
  769. succs_u[un_cw]["ccw"] = un_ccw
  770. succs_u[un_ccw]["cw"] = un_cw
  771. del self._node[n]
  772. del self._succ[n]
  773. del self._pred[n]
  774. except KeyError as err: # NetworkXError if n not in self
  775. raise nx.NetworkXError(
  776. f"The node {n} is not in the planar embedding."
  777. ) from err
  778. nx._clear_cache(self)
  779. def remove_nodes_from(self, nodes):
  780. """Remove multiple nodes.
  781. Parameters
  782. ----------
  783. nodes : iterable container
  784. A container of nodes (list, dict, set, etc.). If a node
  785. in the container is not in the graph it is silently ignored.
  786. See Also
  787. --------
  788. remove_node
  789. Notes
  790. -----
  791. When removing nodes from an iterator over the graph you are changing,
  792. a `RuntimeError` will be raised with message:
  793. `RuntimeError: dictionary changed size during iteration`. This
  794. happens when the graph's underlying dictionary is modified during
  795. iteration. To avoid this error, evaluate the iterator into a separate
  796. object, e.g. by using `list(iterator_of_nodes)`, and pass this
  797. object to `G.remove_nodes_from`.
  798. """
  799. for n in nodes:
  800. if n in self._node:
  801. self.remove_node(n)
  802. # silently skip non-existing nodes
  803. def neighbors_cw_order(self, v):
  804. """Generator for the neighbors of v in clockwise order.
  805. Parameters
  806. ----------
  807. v : node
  808. Yields
  809. ------
  810. node
  811. """
  812. succs = self._succ[v]
  813. if not succs:
  814. # v has no neighbors
  815. return
  816. start_node = next(reversed(succs))
  817. yield start_node
  818. current_node = succs[start_node]["cw"]
  819. while start_node != current_node:
  820. yield current_node
  821. current_node = succs[current_node]["cw"]
  822. def add_half_edge(self, start_node, end_node, *, cw=None, ccw=None):
  823. """Adds a half-edge from `start_node` to `end_node`.
  824. If the half-edge is not the first one out of `start_node`, a reference
  825. node must be provided either in the clockwise (parameter `cw`) or in
  826. the counterclockwise (parameter `ccw`) direction. Only one of `cw`/`ccw`
  827. can be specified (or neither in the case of the first edge).
  828. Note that specifying a reference in the clockwise (`cw`) direction means
  829. inserting the new edge in the first counterclockwise position with
  830. respect to the reference (and vice-versa).
  831. Parameters
  832. ----------
  833. start_node : node
  834. Start node of inserted edge.
  835. end_node : node
  836. End node of inserted edge.
  837. cw, ccw: node
  838. End node of reference edge.
  839. Omit or pass `None` if adding the first out-half-edge of `start_node`.
  840. Raises
  841. ------
  842. NetworkXException
  843. If the `cw` or `ccw` node is not a successor of `start_node`.
  844. If `start_node` has successors, but neither `cw` or `ccw` is provided.
  845. If both `cw` and `ccw` are specified.
  846. See Also
  847. --------
  848. connect_components
  849. """
  850. succs = self._succ.get(start_node)
  851. if succs:
  852. # there is already some edge out of start_node
  853. leftmost_nbr = next(reversed(self._succ[start_node]))
  854. if cw is not None:
  855. if cw not in succs:
  856. raise nx.NetworkXError("Invalid clockwise reference node.")
  857. if ccw is not None:
  858. raise nx.NetworkXError("Only one of cw/ccw can be specified.")
  859. ref_ccw = succs[cw]["ccw"]
  860. super().add_edge(start_node, end_node, cw=cw, ccw=ref_ccw)
  861. succs[ref_ccw]["cw"] = end_node
  862. succs[cw]["ccw"] = end_node
  863. # when (cw == leftmost_nbr), the newly added neighbor is
  864. # already at the end of dict self._succ[start_node] and
  865. # takes the place of the former leftmost_nbr
  866. move_leftmost_nbr_to_end = cw != leftmost_nbr
  867. elif ccw is not None:
  868. if ccw not in succs:
  869. raise nx.NetworkXError("Invalid counterclockwise reference node.")
  870. ref_cw = succs[ccw]["cw"]
  871. super().add_edge(start_node, end_node, cw=ref_cw, ccw=ccw)
  872. succs[ref_cw]["ccw"] = end_node
  873. succs[ccw]["cw"] = end_node
  874. move_leftmost_nbr_to_end = True
  875. else:
  876. raise nx.NetworkXError(
  877. "Node already has out-half-edge(s), either cw or ccw reference node required."
  878. )
  879. if move_leftmost_nbr_to_end:
  880. # LRPlanarity (via self.add_half_edge_first()) requires that
  881. # we keep track of the leftmost neighbor, which we accomplish
  882. # by keeping it as the last key in dict self._succ[start_node]
  883. succs[leftmost_nbr] = succs.pop(leftmost_nbr)
  884. else:
  885. if cw is not None or ccw is not None:
  886. raise nx.NetworkXError("Invalid reference node.")
  887. # adding the first edge out of start_node
  888. super().add_edge(start_node, end_node, ccw=end_node, cw=end_node)
  889. def check_structure(self):
  890. """Runs without exceptions if this object is valid.
  891. Checks that the following properties are fulfilled:
  892. * Edges go in both directions (because the edge attributes differ).
  893. * Every edge has a 'cw' and 'ccw' attribute which corresponds to a
  894. correct planar embedding.
  895. Running this method verifies that the underlying Graph must be planar.
  896. Raises
  897. ------
  898. NetworkXException
  899. This exception is raised with a short explanation if the
  900. PlanarEmbedding is invalid.
  901. """
  902. # Check fundamental structure
  903. for v in self:
  904. try:
  905. sorted_nbrs = set(self.neighbors_cw_order(v))
  906. except KeyError as err:
  907. msg = f"Bad embedding. Missing orientation for a neighbor of {v}"
  908. raise nx.NetworkXException(msg) from err
  909. unsorted_nbrs = set(self[v])
  910. if sorted_nbrs != unsorted_nbrs:
  911. msg = "Bad embedding. Edge orientations not set correctly."
  912. raise nx.NetworkXException(msg)
  913. for w in self[v]:
  914. # Check if opposite half-edge exists
  915. if not self.has_edge(w, v):
  916. msg = "Bad embedding. Opposite half-edge is missing."
  917. raise nx.NetworkXException(msg)
  918. # Check planarity
  919. counted_half_edges = set()
  920. for component in nx.connected_components(self):
  921. if len(component) == 1:
  922. # Don't need to check single node component
  923. continue
  924. num_nodes = len(component)
  925. num_half_edges = 0
  926. num_faces = 0
  927. for v in component:
  928. for w in self.neighbors_cw_order(v):
  929. num_half_edges += 1
  930. if (v, w) not in counted_half_edges:
  931. # We encountered a new face
  932. num_faces += 1
  933. # Mark all half-edges belonging to this face
  934. self.traverse_face(v, w, counted_half_edges)
  935. num_edges = num_half_edges // 2 # num_half_edges is even
  936. if num_nodes - num_edges + num_faces != 2:
  937. # The result does not match Euler's formula
  938. msg = "Bad embedding. The graph does not match Euler's formula"
  939. raise nx.NetworkXException(msg)
  940. def add_half_edge_ccw(self, start_node, end_node, reference_neighbor):
  941. """Adds a half-edge from start_node to end_node.
  942. The half-edge is added counter clockwise next to the existing half-edge
  943. (start_node, reference_neighbor).
  944. Parameters
  945. ----------
  946. start_node : node
  947. Start node of inserted edge.
  948. end_node : node
  949. End node of inserted edge.
  950. reference_neighbor: node
  951. End node of reference edge.
  952. Raises
  953. ------
  954. NetworkXException
  955. If the reference_neighbor does not exist.
  956. See Also
  957. --------
  958. add_half_edge
  959. add_half_edge_cw
  960. connect_components
  961. """
  962. self.add_half_edge(start_node, end_node, cw=reference_neighbor)
  963. def add_half_edge_cw(self, start_node, end_node, reference_neighbor):
  964. """Adds a half-edge from start_node to end_node.
  965. The half-edge is added clockwise next to the existing half-edge
  966. (start_node, reference_neighbor).
  967. Parameters
  968. ----------
  969. start_node : node
  970. Start node of inserted edge.
  971. end_node : node
  972. End node of inserted edge.
  973. reference_neighbor: node
  974. End node of reference edge.
  975. Raises
  976. ------
  977. NetworkXException
  978. If the reference_neighbor does not exist.
  979. See Also
  980. --------
  981. add_half_edge
  982. add_half_edge_ccw
  983. connect_components
  984. """
  985. self.add_half_edge(start_node, end_node, ccw=reference_neighbor)
  986. def remove_edge(self, u, v):
  987. """Remove the edge between u and v.
  988. Parameters
  989. ----------
  990. u, v : nodes
  991. Remove the half-edges (u, v) and (v, u) and update the
  992. edge ordering around the removed edge.
  993. Raises
  994. ------
  995. NetworkXError
  996. If there is not an edge between u and v.
  997. See Also
  998. --------
  999. remove_edges_from : remove a collection of edges
  1000. """
  1001. try:
  1002. succs_u = self._succ[u]
  1003. succs_v = self._succ[v]
  1004. uv_cw = succs_u[v]["cw"]
  1005. uv_ccw = succs_u[v]["ccw"]
  1006. vu_cw = succs_v[u]["cw"]
  1007. vu_ccw = succs_v[u]["ccw"]
  1008. del succs_u[v]
  1009. del self._pred[v][u]
  1010. del succs_v[u]
  1011. del self._pred[u][v]
  1012. if v != uv_cw:
  1013. succs_u[uv_cw]["ccw"] = uv_ccw
  1014. succs_u[uv_ccw]["cw"] = uv_cw
  1015. if u != vu_cw:
  1016. succs_v[vu_cw]["ccw"] = vu_ccw
  1017. succs_v[vu_ccw]["cw"] = vu_cw
  1018. except KeyError as err:
  1019. raise nx.NetworkXError(
  1020. f"The edge {u}-{v} is not in the planar embedding."
  1021. ) from err
  1022. nx._clear_cache(self)
  1023. def remove_edges_from(self, ebunch):
  1024. """Remove all edges specified in ebunch.
  1025. Parameters
  1026. ----------
  1027. ebunch: list or container of edge tuples
  1028. Each pair of half-edges between the nodes given in the tuples
  1029. will be removed from the graph. The nodes can be passed as:
  1030. - 2-tuples (u, v) half-edges (u, v) and (v, u).
  1031. - 3-tuples (u, v, k) where k is ignored.
  1032. See Also
  1033. --------
  1034. remove_edge : remove a single edge
  1035. Notes
  1036. -----
  1037. Will fail silently if an edge in ebunch is not in the graph.
  1038. Examples
  1039. --------
  1040. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  1041. >>> ebunch = [(1, 2), (2, 3)]
  1042. >>> G.remove_edges_from(ebunch)
  1043. """
  1044. for e in ebunch:
  1045. u, v = e[:2] # ignore edge data
  1046. # assuming that the PlanarEmbedding is valid, if the half_edge
  1047. # (u, v) is in the graph, then so is half_edge (v, u)
  1048. if u in self._succ and v in self._succ[u]:
  1049. self.remove_edge(u, v)
  1050. def connect_components(self, v, w):
  1051. """Adds half-edges for (v, w) and (w, v) at some position.
  1052. This method should only be called if v and w are in different
  1053. components, or it might break the embedding.
  1054. This especially means that if `connect_components(v, w)`
  1055. is called it is not allowed to call `connect_components(w, v)`
  1056. afterwards. The neighbor orientations in both directions are
  1057. all set correctly after the first call.
  1058. Parameters
  1059. ----------
  1060. v : node
  1061. w : node
  1062. See Also
  1063. --------
  1064. add_half_edge
  1065. """
  1066. if v in self._succ and self._succ[v]:
  1067. ref = next(reversed(self._succ[v]))
  1068. else:
  1069. ref = None
  1070. self.add_half_edge(v, w, cw=ref)
  1071. if w in self._succ and self._succ[w]:
  1072. ref = next(reversed(self._succ[w]))
  1073. else:
  1074. ref = None
  1075. self.add_half_edge(w, v, cw=ref)
  1076. def add_half_edge_first(self, start_node, end_node):
  1077. """Add a half-edge and set end_node as start_node's leftmost neighbor.
  1078. The new edge is inserted counterclockwise with respect to the current
  1079. leftmost neighbor, if there is one.
  1080. Parameters
  1081. ----------
  1082. start_node : node
  1083. end_node : node
  1084. See Also
  1085. --------
  1086. add_half_edge
  1087. connect_components
  1088. """
  1089. succs = self._succ.get(start_node)
  1090. # the leftmost neighbor is the last entry in the
  1091. # self._succ[start_node] dict
  1092. leftmost_nbr = next(reversed(succs)) if succs else None
  1093. self.add_half_edge(start_node, end_node, cw=leftmost_nbr)
  1094. def next_face_half_edge(self, v, w):
  1095. """Returns the following half-edge left of a face.
  1096. Parameters
  1097. ----------
  1098. v : node
  1099. w : node
  1100. Returns
  1101. -------
  1102. half-edge : tuple
  1103. """
  1104. new_node = self[w][v]["ccw"]
  1105. return w, new_node
  1106. def traverse_face(self, v, w, mark_half_edges=None):
  1107. """Returns nodes on the face that belong to the half-edge (v, w).
  1108. The face that is traversed lies to the right of the half-edge (in an
  1109. orientation where v is below w).
  1110. Optionally it is possible to pass a set to which all encountered half
  1111. edges are added. Before calling this method, this set must not include
  1112. any half-edges that belong to the face.
  1113. Parameters
  1114. ----------
  1115. v : node
  1116. Start node of half-edge.
  1117. w : node
  1118. End node of half-edge.
  1119. mark_half_edges: set, optional
  1120. Set to which all encountered half-edges are added.
  1121. Returns
  1122. -------
  1123. face : list
  1124. A list of nodes that lie on this face.
  1125. """
  1126. if mark_half_edges is None:
  1127. mark_half_edges = set()
  1128. face_nodes = [v]
  1129. mark_half_edges.add((v, w))
  1130. prev_node = v
  1131. cur_node = w
  1132. # Last half-edge is (incoming_node, v)
  1133. incoming_node = self[v][w]["cw"]
  1134. while cur_node != v or prev_node != incoming_node:
  1135. face_nodes.append(cur_node)
  1136. prev_node, cur_node = self.next_face_half_edge(prev_node, cur_node)
  1137. if (prev_node, cur_node) in mark_half_edges:
  1138. raise nx.NetworkXException("Bad planar embedding. Impossible face.")
  1139. mark_half_edges.add((prev_node, cur_node))
  1140. return face_nodes
  1141. def is_directed(self):
  1142. """A valid PlanarEmbedding is undirected.
  1143. All reverse edges are contained, i.e. for every existing
  1144. half-edge (v, w) the half-edge in the opposite direction (w, v) is also
  1145. contained.
  1146. """
  1147. return False
  1148. def copy(self, as_view=False):
  1149. if as_view is True:
  1150. return nx.graphviews.generic_graph_view(self)
  1151. G = self.__class__()
  1152. G.graph.update(self.graph)
  1153. G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
  1154. super(self.__class__, G).add_edges_from(
  1155. (u, v, datadict.copy())
  1156. for u, nbrs in self._adj.items()
  1157. for v, datadict in nbrs.items()
  1158. )
  1159. return G
  1160. def to_undirected(self, reciprocal=False, as_view=False):
  1161. """
  1162. Returns a non-embedding undirected representation of the graph.
  1163. This method strips the planar embedding information and provides
  1164. a simple undirected graph representation. While creating the undirected graph,
  1165. all edge attributes are retained except the ``"cw"`` and ``"ccw"`` attributes
  1166. which are removed from the edge data. Those attributes are specific to
  1167. the requirements of planar embeddings.
  1168. Parameters
  1169. ----------
  1170. reciprocal : bool (optional)
  1171. Not supported for PlanarEmbedding. This parameter raises an exception
  1172. if used. All valid embeddings include reciprocal half-edges by definition,
  1173. making this parameter unnecessary.
  1174. as_view : bool (optional, default=False)
  1175. Not supported for PlanarEmbedding. This parameter raises an exception
  1176. if used.
  1177. Returns
  1178. -------
  1179. G : Graph
  1180. An undirected graph with the same name and nodes as the PlanarEmbedding.
  1181. Edges are included with their data, except for the ``"cw"`` and ``"ccw"``
  1182. attributes, which are omitted.
  1183. Notes
  1184. -----
  1185. - If edges exist in both directions ``(u, v)`` and ``(v, u)`` in the PlanarEmbedding,
  1186. attributes for the resulting undirected edge will be combined, excluding ``"cw"``
  1187. and ``"ccw"``.
  1188. - A deep copy is made of the other edge attributes as well as the
  1189. node and graph attributes, ensuring independence of the resulting graph.
  1190. - Subclass-specific data structures used in the original graph may not transfer
  1191. to the undirected graph. The resulting graph will be of type ``nx.Graph``.
  1192. """
  1193. if reciprocal:
  1194. raise ValueError(
  1195. "'reciprocal=True' is not supported for PlanarEmbedding.\n"
  1196. "All valid embeddings include reciprocal half-edges by definition,\n"
  1197. "making this parameter unnecessary."
  1198. )
  1199. if as_view:
  1200. raise ValueError("'as_view=True' is not supported for PlanarEmbedding.")
  1201. graph_class = self.to_undirected_class()
  1202. G = graph_class()
  1203. G.graph.update(deepcopy(self.graph))
  1204. G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
  1205. G.add_edges_from(
  1206. (u, v, {k: deepcopy(v) for k, v in d.items() if k not in {"cw", "ccw"}})
  1207. for u, nbrs in self._adj.items()
  1208. for v, d in nbrs.items()
  1209. )
  1210. return G