passagemath-graphs 10.5.43__cp39-cp39-musllinux_1_2_aarch64.whl

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.
Files changed (258) hide show
  1. passagemath_graphs-10.5.43.dist-info/METADATA +293 -0
  2. passagemath_graphs-10.5.43.dist-info/RECORD +258 -0
  3. passagemath_graphs-10.5.43.dist-info/WHEEL +5 -0
  4. passagemath_graphs-10.5.43.dist-info/top_level.txt +2 -0
  5. passagemath_graphs.libs/libgcc_s-69c45f16.so.1 +0 -0
  6. passagemath_graphs.libs/libgmp-8e78bd9b.so.10.5.0 +0 -0
  7. passagemath_graphs.libs/libstdc++-1f1a71be.so.6.0.33 +0 -0
  8. sage/all__sagemath_graphs.py +39 -0
  9. sage/combinat/abstract_tree.py +2552 -0
  10. sage/combinat/all__sagemath_graphs.py +34 -0
  11. sage/combinat/binary_tree.py +5306 -0
  12. sage/combinat/cluster_algebra_quiver/all.py +22 -0
  13. sage/combinat/cluster_algebra_quiver/cluster_seed.py +5208 -0
  14. sage/combinat/cluster_algebra_quiver/interact.py +125 -0
  15. sage/combinat/cluster_algebra_quiver/mutation_class.py +625 -0
  16. sage/combinat/cluster_algebra_quiver/mutation_type.py +1556 -0
  17. sage/combinat/cluster_algebra_quiver/quiver.py +2262 -0
  18. sage/combinat/cluster_algebra_quiver/quiver_mutation_type.py +2468 -0
  19. sage/combinat/designs/MOLS_handbook_data.py +570 -0
  20. sage/combinat/designs/all.py +58 -0
  21. sage/combinat/designs/bibd.py +1655 -0
  22. sage/combinat/designs/block_design.py +1071 -0
  23. sage/combinat/designs/covering_array.py +269 -0
  24. sage/combinat/designs/covering_design.py +534 -0
  25. sage/combinat/designs/database.py +5614 -0
  26. sage/combinat/designs/design_catalog.py +122 -0
  27. sage/combinat/designs/designs_pyx.cpython-39-aarch64-linux-gnu.so +0 -0
  28. sage/combinat/designs/designs_pyx.pxd +21 -0
  29. sage/combinat/designs/designs_pyx.pyx +993 -0
  30. sage/combinat/designs/difference_family.py +3951 -0
  31. sage/combinat/designs/difference_matrices.py +279 -0
  32. sage/combinat/designs/evenly_distributed_sets.cpython-39-aarch64-linux-gnu.so +0 -0
  33. sage/combinat/designs/evenly_distributed_sets.pyx +661 -0
  34. sage/combinat/designs/ext_rep.py +1064 -0
  35. sage/combinat/designs/gen_quadrangles_with_spread.cpython-39-aarch64-linux-gnu.so +0 -0
  36. sage/combinat/designs/gen_quadrangles_with_spread.pyx +339 -0
  37. sage/combinat/designs/group_divisible_designs.py +361 -0
  38. sage/combinat/designs/incidence_structures.py +2357 -0
  39. sage/combinat/designs/latin_squares.py +548 -0
  40. sage/combinat/designs/orthogonal_arrays.py +2243 -0
  41. sage/combinat/designs/orthogonal_arrays_build_recursive.py +1780 -0
  42. sage/combinat/designs/orthogonal_arrays_find_recursive.cpython-39-aarch64-linux-gnu.so +0 -0
  43. sage/combinat/designs/orthogonal_arrays_find_recursive.pyx +966 -0
  44. sage/combinat/designs/resolvable_bibd.py +781 -0
  45. sage/combinat/designs/steiner_quadruple_systems.py +1306 -0
  46. sage/combinat/designs/subhypergraph_search.cpython-39-aarch64-linux-gnu.so +0 -0
  47. sage/combinat/designs/subhypergraph_search.pyx +530 -0
  48. sage/combinat/designs/twographs.py +306 -0
  49. sage/combinat/finite_state_machine.py +14874 -0
  50. sage/combinat/finite_state_machine_generators.py +2006 -0
  51. sage/combinat/graph_path.py +448 -0
  52. sage/combinat/interval_posets.py +3908 -0
  53. sage/combinat/nu_tamari_lattice.py +269 -0
  54. sage/combinat/ordered_tree.py +1446 -0
  55. sage/combinat/posets/all.py +46 -0
  56. sage/combinat/posets/cartesian_product.py +493 -0
  57. sage/combinat/posets/d_complete.py +182 -0
  58. sage/combinat/posets/elements.py +273 -0
  59. sage/combinat/posets/forest.py +30 -0
  60. sage/combinat/posets/hasse_cython.cpython-39-aarch64-linux-gnu.so +0 -0
  61. sage/combinat/posets/hasse_cython.pyx +174 -0
  62. sage/combinat/posets/hasse_diagram.py +3678 -0
  63. sage/combinat/posets/incidence_algebras.py +796 -0
  64. sage/combinat/posets/lattices.py +5119 -0
  65. sage/combinat/posets/linear_extension_iterator.cpython-39-aarch64-linux-gnu.so +0 -0
  66. sage/combinat/posets/linear_extension_iterator.pyx +292 -0
  67. sage/combinat/posets/linear_extensions.py +1039 -0
  68. sage/combinat/posets/mobile.py +275 -0
  69. sage/combinat/posets/moebius_algebra.py +776 -0
  70. sage/combinat/posets/poset_examples.py +2131 -0
  71. sage/combinat/posets/posets.py +9169 -0
  72. sage/combinat/rooted_tree.py +1070 -0
  73. sage/combinat/shard_order.py +239 -0
  74. sage/combinat/tamari_lattices.py +384 -0
  75. sage/combinat/yang_baxter_graph.py +923 -0
  76. sage/databases/all__sagemath_graphs.py +1 -0
  77. sage/databases/knotinfo_db.py +1230 -0
  78. sage/ext_data/all__sagemath_graphs.py +1 -0
  79. sage/ext_data/graphs/graph_plot_js.html +330 -0
  80. sage/ext_data/kenzo/CP2.txt +45 -0
  81. sage/ext_data/kenzo/CP3.txt +349 -0
  82. sage/ext_data/kenzo/CP4.txt +4774 -0
  83. sage/ext_data/kenzo/README.txt +49 -0
  84. sage/ext_data/kenzo/S4.txt +20 -0
  85. sage/graphs/all.py +42 -0
  86. sage/graphs/asteroidal_triples.cpython-39-aarch64-linux-gnu.so +0 -0
  87. sage/graphs/asteroidal_triples.pyx +299 -0
  88. sage/graphs/base/all.py +1 -0
  89. sage/graphs/base/boost_graph.cpython-39-aarch64-linux-gnu.so +0 -0
  90. sage/graphs/base/boost_graph.pxd +106 -0
  91. sage/graphs/base/boost_graph.pyx +3045 -0
  92. sage/graphs/base/c_graph.cpython-39-aarch64-linux-gnu.so +0 -0
  93. sage/graphs/base/c_graph.pxd +106 -0
  94. sage/graphs/base/c_graph.pyx +5096 -0
  95. sage/graphs/base/dense_graph.cpython-39-aarch64-linux-gnu.so +0 -0
  96. sage/graphs/base/dense_graph.pxd +26 -0
  97. sage/graphs/base/dense_graph.pyx +757 -0
  98. sage/graphs/base/graph_backends.cpython-39-aarch64-linux-gnu.so +0 -0
  99. sage/graphs/base/graph_backends.pxd +5 -0
  100. sage/graphs/base/graph_backends.pyx +797 -0
  101. sage/graphs/base/overview.py +85 -0
  102. sage/graphs/base/sparse_graph.cpython-39-aarch64-linux-gnu.so +0 -0
  103. sage/graphs/base/sparse_graph.pxd +90 -0
  104. sage/graphs/base/sparse_graph.pyx +1653 -0
  105. sage/graphs/base/static_dense_graph.cpython-39-aarch64-linux-gnu.so +0 -0
  106. sage/graphs/base/static_dense_graph.pxd +5 -0
  107. sage/graphs/base/static_dense_graph.pyx +1032 -0
  108. sage/graphs/base/static_sparse_backend.cpython-39-aarch64-linux-gnu.so +0 -0
  109. sage/graphs/base/static_sparse_backend.pxd +27 -0
  110. sage/graphs/base/static_sparse_backend.pyx +1580 -0
  111. sage/graphs/base/static_sparse_graph.cpython-39-aarch64-linux-gnu.so +0 -0
  112. sage/graphs/base/static_sparse_graph.pxd +37 -0
  113. sage/graphs/base/static_sparse_graph.pyx +1304 -0
  114. sage/graphs/bipartite_graph.py +2709 -0
  115. sage/graphs/centrality.cpython-39-aarch64-linux-gnu.so +0 -0
  116. sage/graphs/centrality.pyx +965 -0
  117. sage/graphs/cographs.py +519 -0
  118. sage/graphs/comparability.cpython-39-aarch64-linux-gnu.so +0 -0
  119. sage/graphs/comparability.pyx +813 -0
  120. sage/graphs/connectivity.cpython-39-aarch64-linux-gnu.so +0 -0
  121. sage/graphs/connectivity.pxd +157 -0
  122. sage/graphs/connectivity.pyx +4813 -0
  123. sage/graphs/convexity_properties.cpython-39-aarch64-linux-gnu.so +0 -0
  124. sage/graphs/convexity_properties.pxd +16 -0
  125. sage/graphs/convexity_properties.pyx +827 -0
  126. sage/graphs/digraph.py +4410 -0
  127. sage/graphs/digraph_generators.py +1921 -0
  128. sage/graphs/distances_all_pairs.cpython-39-aarch64-linux-gnu.so +0 -0
  129. sage/graphs/distances_all_pairs.pxd +12 -0
  130. sage/graphs/distances_all_pairs.pyx +2938 -0
  131. sage/graphs/domination.py +1363 -0
  132. sage/graphs/dot2tex_utils.py +100 -0
  133. sage/graphs/edge_connectivity.cpython-39-aarch64-linux-gnu.so +0 -0
  134. sage/graphs/edge_connectivity.pyx +1215 -0
  135. sage/graphs/generators/all.py +1 -0
  136. sage/graphs/generators/basic.py +1769 -0
  137. sage/graphs/generators/chessboard.py +538 -0
  138. sage/graphs/generators/classical_geometries.py +1611 -0
  139. sage/graphs/generators/degree_sequence.py +235 -0
  140. sage/graphs/generators/distance_regular.cpython-39-aarch64-linux-gnu.so +0 -0
  141. sage/graphs/generators/distance_regular.pyx +2846 -0
  142. sage/graphs/generators/families.py +4749 -0
  143. sage/graphs/generators/intersection.py +565 -0
  144. sage/graphs/generators/platonic_solids.py +262 -0
  145. sage/graphs/generators/random.py +2623 -0
  146. sage/graphs/generators/smallgraphs.py +5741 -0
  147. sage/graphs/generators/world_map.py +724 -0
  148. sage/graphs/generic_graph.py +26395 -0
  149. sage/graphs/generic_graph_pyx.cpython-39-aarch64-linux-gnu.so +0 -0
  150. sage/graphs/generic_graph_pyx.pxd +34 -0
  151. sage/graphs/generic_graph_pyx.pyx +1626 -0
  152. sage/graphs/genus.cpython-39-aarch64-linux-gnu.so +0 -0
  153. sage/graphs/genus.pyx +623 -0
  154. sage/graphs/graph.py +9362 -0
  155. sage/graphs/graph_coloring.cpython-39-aarch64-linux-gnu.so +0 -0
  156. sage/graphs/graph_coloring.pyx +2284 -0
  157. sage/graphs/graph_database.py +1122 -0
  158. sage/graphs/graph_decompositions/all.py +1 -0
  159. sage/graphs/graph_decompositions/bandwidth.cpython-39-aarch64-linux-gnu.so +0 -0
  160. sage/graphs/graph_decompositions/bandwidth.pyx +428 -0
  161. sage/graphs/graph_decompositions/clique_separators.cpython-39-aarch64-linux-gnu.so +0 -0
  162. sage/graphs/graph_decompositions/clique_separators.pyx +595 -0
  163. sage/graphs/graph_decompositions/cutwidth.cpython-39-aarch64-linux-gnu.so +0 -0
  164. sage/graphs/graph_decompositions/cutwidth.pyx +753 -0
  165. sage/graphs/graph_decompositions/fast_digraph.cpython-39-aarch64-linux-gnu.so +0 -0
  166. sage/graphs/graph_decompositions/fast_digraph.pxd +13 -0
  167. sage/graphs/graph_decompositions/fast_digraph.pyx +212 -0
  168. sage/graphs/graph_decompositions/graph_products.cpython-39-aarch64-linux-gnu.so +0 -0
  169. sage/graphs/graph_decompositions/graph_products.pyx +462 -0
  170. sage/graphs/graph_decompositions/modular_decomposition.cpython-39-aarch64-linux-gnu.so +0 -0
  171. sage/graphs/graph_decompositions/modular_decomposition.pxd +27 -0
  172. sage/graphs/graph_decompositions/modular_decomposition.pyx +1536 -0
  173. sage/graphs/graph_decompositions/slice_decomposition.cpython-39-aarch64-linux-gnu.so +0 -0
  174. sage/graphs/graph_decompositions/slice_decomposition.pxd +18 -0
  175. sage/graphs/graph_decompositions/slice_decomposition.pyx +1080 -0
  176. sage/graphs/graph_decompositions/tree_decomposition.cpython-39-aarch64-linux-gnu.so +0 -0
  177. sage/graphs/graph_decompositions/tree_decomposition.pxd +17 -0
  178. sage/graphs/graph_decompositions/tree_decomposition.pyx +1996 -0
  179. sage/graphs/graph_decompositions/vertex_separation.cpython-39-aarch64-linux-gnu.so +0 -0
  180. sage/graphs/graph_decompositions/vertex_separation.pxd +5 -0
  181. sage/graphs/graph_decompositions/vertex_separation.pyx +1963 -0
  182. sage/graphs/graph_editor.py +82 -0
  183. sage/graphs/graph_generators.py +3301 -0
  184. sage/graphs/graph_generators_pyx.cpython-39-aarch64-linux-gnu.so +0 -0
  185. sage/graphs/graph_generators_pyx.pyx +95 -0
  186. sage/graphs/graph_input.py +812 -0
  187. sage/graphs/graph_latex.py +2064 -0
  188. sage/graphs/graph_list.py +367 -0
  189. sage/graphs/graph_plot.py +1749 -0
  190. sage/graphs/graph_plot_js.py +338 -0
  191. sage/graphs/hyperbolicity.cpython-39-aarch64-linux-gnu.so +0 -0
  192. sage/graphs/hyperbolicity.pyx +1702 -0
  193. sage/graphs/hypergraph_generators.py +364 -0
  194. sage/graphs/independent_sets.cpython-39-aarch64-linux-gnu.so +0 -0
  195. sage/graphs/independent_sets.pxd +13 -0
  196. sage/graphs/independent_sets.pyx +402 -0
  197. sage/graphs/isgci.py +1033 -0
  198. sage/graphs/isoperimetric_inequalities.cpython-39-aarch64-linux-gnu.so +0 -0
  199. sage/graphs/isoperimetric_inequalities.pyx +453 -0
  200. sage/graphs/line_graph.cpython-39-aarch64-linux-gnu.so +0 -0
  201. sage/graphs/line_graph.pyx +627 -0
  202. sage/graphs/lovasz_theta.py +77 -0
  203. sage/graphs/matching.py +1633 -0
  204. sage/graphs/matching_covered_graph.py +3566 -0
  205. sage/graphs/orientations.py +1504 -0
  206. sage/graphs/partial_cube.py +459 -0
  207. sage/graphs/path_enumeration.cpython-39-aarch64-linux-gnu.so +0 -0
  208. sage/graphs/path_enumeration.pyx +2040 -0
  209. sage/graphs/pq_trees.py +1129 -0
  210. sage/graphs/print_graphs.py +201 -0
  211. sage/graphs/schnyder.py +865 -0
  212. sage/graphs/spanning_tree.cpython-39-aarch64-linux-gnu.so +0 -0
  213. sage/graphs/spanning_tree.pyx +1457 -0
  214. sage/graphs/strongly_regular_db.cpython-39-aarch64-linux-gnu.so +0 -0
  215. sage/graphs/strongly_regular_db.pyx +3340 -0
  216. sage/graphs/traversals.cpython-39-aarch64-linux-gnu.so +0 -0
  217. sage/graphs/traversals.pxd +9 -0
  218. sage/graphs/traversals.pyx +1871 -0
  219. sage/graphs/trees.cpython-39-aarch64-linux-gnu.so +0 -0
  220. sage/graphs/trees.pxd +15 -0
  221. sage/graphs/trees.pyx +310 -0
  222. sage/graphs/tutte_polynomial.py +713 -0
  223. sage/graphs/views.cpython-39-aarch64-linux-gnu.so +0 -0
  224. sage/graphs/views.pyx +794 -0
  225. sage/graphs/weakly_chordal.cpython-39-aarch64-linux-gnu.so +0 -0
  226. sage/graphs/weakly_chordal.pyx +562 -0
  227. sage/groups/all__sagemath_graphs.py +1 -0
  228. sage/groups/perm_gps/all__sagemath_graphs.py +1 -0
  229. sage/groups/perm_gps/partn_ref/all__sagemath_graphs.py +1 -0
  230. sage/groups/perm_gps/partn_ref/refinement_graphs.cpython-39-aarch64-linux-gnu.so +0 -0
  231. sage/groups/perm_gps/partn_ref/refinement_graphs.pxd +38 -0
  232. sage/groups/perm_gps/partn_ref/refinement_graphs.pyx +1666 -0
  233. sage/knots/all.py +6 -0
  234. sage/knots/free_knotinfo_monoid.py +507 -0
  235. sage/knots/gauss_code.py +291 -0
  236. sage/knots/knot.py +682 -0
  237. sage/knots/knot_table.py +284 -0
  238. sage/knots/knotinfo.py +2880 -0
  239. sage/knots/link.py +4682 -0
  240. sage/sandpiles/all.py +13 -0
  241. sage/sandpiles/examples.py +225 -0
  242. sage/sandpiles/sandpile.py +6365 -0
  243. sage/topology/all.py +22 -0
  244. sage/topology/cell_complex.py +1214 -0
  245. sage/topology/cubical_complex.py +1977 -0
  246. sage/topology/delta_complex.py +1806 -0
  247. sage/topology/filtered_simplicial_complex.py +744 -0
  248. sage/topology/moment_angle_complex.py +823 -0
  249. sage/topology/simplicial_complex.py +5161 -0
  250. sage/topology/simplicial_complex_catalog.py +86 -0
  251. sage/topology/simplicial_complex_examples.py +1692 -0
  252. sage/topology/simplicial_complex_homset.py +205 -0
  253. sage/topology/simplicial_complex_morphism.py +836 -0
  254. sage/topology/simplicial_set.py +4102 -0
  255. sage/topology/simplicial_set_catalog.py +55 -0
  256. sage/topology/simplicial_set_constructions.py +2954 -0
  257. sage/topology/simplicial_set_examples.py +865 -0
  258. sage/topology/simplicial_set_morphism.py +1464 -0
@@ -0,0 +1,1749 @@
1
+ # sage_setup: distribution = sagemath-graphs
2
+ # sage.doctest: needs sage.plot
3
+ r"""
4
+ Graph plotting
5
+
6
+ *(For LaTeX drawings of graphs, see the* :mod:`~sage.graphs.graph_latex` *module.)*
7
+
8
+ All graphs have an associated Sage graphics object, which you can display::
9
+
10
+ sage: G = graphs.WheelGraph(15)
11
+ sage: P = G.plot()
12
+ sage: P.show() # long time
13
+
14
+ .. PLOT::
15
+
16
+ sphinx_plot(graphs.WheelGraph(15))
17
+
18
+ When plotting a graph created using Sage's ``Graph`` command,
19
+ node positions are determined using the spring-layout algorithm.
20
+ Special graphs available from ``graphs.*`` have preset positions.
21
+ For example, compare the two plots of the Petersen graph,
22
+ as obtained using ``Graph`` or as obtained from that database::
23
+
24
+ sage: petersen_spring = Graph(':I`ES@obGkqegW~')
25
+ sage: petersen_spring.show() # long time
26
+
27
+ .. PLOT::
28
+
29
+ petersen_spring = Graph(':I`ES@obGkqegW~')
30
+ sphinx_plot(petersen_spring)
31
+
32
+ ::
33
+
34
+ sage: petersen_database = graphs.PetersenGraph()
35
+ sage: petersen_database.show() # long time
36
+
37
+ .. PLOT::
38
+
39
+ petersen_database = graphs.PetersenGraph()
40
+ sphinx_plot(petersen_database)
41
+
42
+ All constructors in this database (except some random graphs) prefill
43
+ the position dictionary, bypassing the spring-layout positioning algorithm.
44
+
45
+ **Plot options**
46
+
47
+ Here is the list of options accepted by
48
+ :meth:`~sage.graphs.generic_graph.GenericGraph.plot` and the constructor of
49
+ :class:`GraphPlot`. Those two functions also accept all options of
50
+ :meth:`sage.plot.graphics.Graphics.show`.
51
+
52
+ .. csv-table::
53
+ :class: contentstable
54
+ :widths: 30, 70
55
+ :delim: |
56
+
57
+ {PLOT_OPTIONS_TABLE}
58
+
59
+ **Default options**
60
+
61
+ This module defines two dictionaries containing default options for the
62
+ :meth:`~sage.graphs.generic_graph.GenericGraph.plot` and
63
+ :meth:`~sage.graphs.generic_graph.GenericGraph.show` methods. These two
64
+ dictionaries are ``sage.graphs.graph_plot.DEFAULT_PLOT_OPTIONS`` and
65
+ ``sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS``, respectively.
66
+
67
+ Obviously, these values are overruled when arguments are given explicitly.
68
+
69
+ Here is how to define the default size of a graph drawing to be ``(6, 6)``.
70
+ The first two calls to :meth:`~sage.graphs.generic_graph.GenericGraph.show`
71
+ use this option, while the third does not (a value for ``figsize``
72
+ is explicitly given)::
73
+
74
+ sage: import sage.graphs.graph_plot
75
+ sage: sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS['figsize'] = (6, 6)
76
+ sage: graphs.PetersenGraph().show() # long time
77
+ sage: graphs.ChvatalGraph().show() # long time
78
+ sage: graphs.PetersenGraph().show(figsize=(4, 4)) # long time
79
+
80
+ We can now reset the default to its initial value, and now display graphs as
81
+ previously::
82
+
83
+ sage: sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS['figsize'] = (4, 4)
84
+ sage: graphs.PetersenGraph().show() # long time
85
+ sage: graphs.ChvatalGraph().show() # long time
86
+
87
+ .. NOTE::
88
+
89
+ * While ``DEFAULT_PLOT_OPTIONS`` affects both ``G.show()`` and ``G.plot()``,
90
+ settings from ``DEFAULT_SHOW_OPTIONS`` only affects ``G.show()``.
91
+
92
+ * In order to define a default value permanently, you can add a couple of
93
+ lines to `Sage's startup scripts <../../../repl/startup.html>`_. Example::
94
+
95
+ sage: import sage.graphs.graph_plot
96
+ sage: sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS['figsize'] = (4, 4)
97
+
98
+ **Index of methods and functions**
99
+
100
+ .. csv-table::
101
+ :class: contentstable
102
+ :widths: 30, 70
103
+ :delim: |
104
+
105
+ :meth:`GraphPlot.set_pos` | Set the position plotting parameters for this GraphPlot.
106
+ :meth:`GraphPlot.set_vertices` | Set the vertex plotting parameters for this GraphPlot.
107
+ :meth:`GraphPlot.set_edges` | Set the edge (or arrow) plotting parameters for the GraphPlot object.
108
+ :meth:`GraphPlot.show` | Show the (Di)Graph associated with this GraphPlot object.
109
+ :meth:`GraphPlot.plot` | Return a graphics object representing the (di)graph.
110
+ :meth:`GraphPlot.layout_tree` | Compute a nice layout of a tree.
111
+ """
112
+
113
+ # ****************************************************************************
114
+ # Copyright (C) 2009 Emily Kirkman
115
+ # 2009 Robert L. Miller <rlmillster@gmail.com>
116
+ #
117
+ # Distributed under the terms of the GNU General Public License (GPL)
118
+ #
119
+ # This code is distributed in the hope that it will be useful,
120
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
121
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
122
+ # General Public License for more details.
123
+ #
124
+ # The full text of the GPL is available at:
125
+ #
126
+ # https://www.gnu.org/licenses/
127
+ # ****************************************************************************
128
+
129
+ from collections import defaultdict
130
+ from math import sqrt, cos, sin, atan, pi
131
+ from sage.structure.sage_object import SageObject
132
+ from sage.misc.lazy_import import lazy_import
133
+ lazy_import("sage.plot.all", [
134
+ "Graphics", "scatter_plot", "bezier_path", "line", "arrow", "text", "circle"])
135
+
136
+
137
+ layout_options = {
138
+ 'layout':
139
+ 'A layout algorithm -- one of : "acyclic", "circular" (plots the '
140
+ 'graph with vertices evenly distributed on a circle), "ranked", '
141
+ '"graphviz", "planar", "spring" (traditional spring layout, using '
142
+ 'the graph\'s current positions as initial positions), or "tree" '
143
+ '(the tree will be plotted in levels, depending on minimum distance '
144
+ 'for the root).',
145
+ 'iterations':
146
+ 'The number of times to execute the spring layout algorithm.',
147
+ 'heights':
148
+ 'A dictionary mapping heights to the list of vertices at this height.',
149
+ 'spring':
150
+ 'Use spring layout to finalize the current layout.',
151
+ 'tree_root':
152
+ 'A vertex designation for drawing trees. A vertex of the tree to '
153
+ 'be used as the root for the ``layout=\'tree\'`` option. If no root '
154
+ 'is specified, then one is chosen close to the center of the tree. '
155
+ 'Ignored unless ``layout=\'tree\'``.',
156
+ 'forest_roots':
157
+ 'An iterable specifying which vertices to use as roots for the '
158
+ '``layout=\'forest\'`` option. If no root is specified for a tree, '
159
+ 'then one is chosen close to the center of the tree. '
160
+ 'Ignored unless ``layout=\'forest\'``.',
161
+ 'tree_orientation':
162
+ 'The direction of tree branches -- \'up\', \'down\', '
163
+ '\'left\' or \'right\'.',
164
+ 'save_pos':
165
+ 'Whether or not to save the computed position for the graph.',
166
+ 'dim':
167
+ 'The dimension of the layout -- 2 or 3.',
168
+ 'prog':
169
+ 'Which graphviz layout program to use -- one of '
170
+ '"circo", "dot", "fdp", "neato", or "twopi".',
171
+ 'by_component':
172
+ 'Whether to do the spring layout by connected component -- boolean.'}
173
+
174
+ graphplot_options = layout_options.copy()
175
+
176
+ graphplot_options.update({
177
+ 'pos':
178
+ 'The position dictionary of vertices.',
179
+ 'vertex_labels':
180
+ 'Vertex labels to draw. This can be ``True``/``False`` to indicate '
181
+ 'whether to print the vertex string representation of not, '
182
+ 'a dictionary keyed by vertices and associating to each vertex '
183
+ 'a label string, or a function taking as input a vertex and returning '
184
+ 'a label string.',
185
+ 'vertex_label_shift':
186
+ 'If layout is circular and we have vertex labels, will shift vertices '
187
+ 'away from center of circle in coordinate fashion `(x, y)`.',
188
+ 'vertex_color':
189
+ 'Default color for vertices not listed '
190
+ 'in vertex_colors dictionary.',
191
+ 'vertex_colors':
192
+ 'A dictionary specifying vertex colors: '
193
+ 'each key is a color recognizable by matplotlib, '
194
+ 'and each corresponding value is a list of vertices.',
195
+ 'vertex_size':
196
+ 'The size to draw the vertices.',
197
+ 'vertex_shape':
198
+ 'The shape to draw the vertices. '
199
+ 'Currently unavailable for Multi-edged DiGraphs.',
200
+ 'edge_labels':
201
+ 'Whether or not to draw edge labels.',
202
+ 'edge_style':
203
+ 'The linestyle of the edges. It should be '
204
+ 'one of "solid", "dashed", "dotted", "dashdot", '
205
+ 'or "-", "--", ":", "-.", respectively. ',
206
+ 'edge_styles':
207
+ 'A dictionary specifying edge styles: '
208
+ 'each key is an edge or a label (all same) and value is the linestyle '
209
+ 'of the edge. It should be one of "solid", "dashed", "dotted", '
210
+ '"dashdot", or "-", "--", ":", "-.", respectively.',
211
+ 'edge_thickness':
212
+ 'The thickness of the edges.',
213
+ 'edge_thicknesses':
214
+ 'A dictionary specifying edge thicknesses: '
215
+ 'each key is an edge or a label (all same) and thickness of the '
216
+ 'corresponding edge.',
217
+ 'edge_color':
218
+ 'The default color for edges not listed in edge_colors.',
219
+ 'edge_colors':
220
+ 'A dictionary specifying edge colors: '
221
+ 'each key is a color recognized by matplotlib, '
222
+ 'and each corresponding value is a list of edges.',
223
+ 'color_by_label':
224
+ 'Whether to color the edges according to their labels. This also '
225
+ 'accepts a function or dictionary mapping labels to colors.',
226
+ 'partition':
227
+ 'A partition of the vertex set. If specified, plot will show each '
228
+ 'cell in a different color; vertex_colors takes precedence.',
229
+ 'loop_size':
230
+ 'The radius of the smallest loop.',
231
+ 'arrowsize':
232
+ 'Size of arrows.',
233
+ 'dist':
234
+ 'The distance between multiedges.',
235
+ 'max_dist':
236
+ 'The max distance range to allow multiedges.',
237
+ 'talk':
238
+ 'Whether to display the vertices in talk mode (larger and white).',
239
+ 'label_fontsize':
240
+ 'font size of all labels',
241
+ 'graph_border':
242
+ 'Whether or not to draw a frame around the graph.',
243
+ 'edge_labels_background':
244
+ 'The color of the background of the edge labels.'})
245
+
246
+ _PLOT_OPTIONS_TABLE = ""
247
+
248
+ for key, value in graphplot_options.items():
249
+ _PLOT_OPTIONS_TABLE += f" ``{key}`` | {value}\n"
250
+
251
+ __doc__ = __doc__.format(PLOT_OPTIONS_TABLE=_PLOT_OPTIONS_TABLE)
252
+
253
+ DEFAULT_SHOW_OPTIONS = {'figsize': (4, 4)}
254
+
255
+ DEFAULT_PLOT_OPTIONS = {
256
+ 'vertex_size' : 200,
257
+ 'vertex_labels' : True,
258
+ 'vertex_label_shift' : None,
259
+ 'layout' : None,
260
+ 'edge_style' : 'solid',
261
+ 'edge_styles' : None,
262
+ 'edge_thickness' : 1,
263
+ 'edge_thicknesses' : None,
264
+ 'edge_color' : 'black',
265
+ 'edge_colors' : None,
266
+ 'edge_labels' : False,
267
+ 'iterations' : 50,
268
+ 'tree_orientation' : 'down',
269
+ 'heights' : None,
270
+ 'graph_border' : False,
271
+ 'talk' : False,
272
+ 'color_by_label' : False,
273
+ 'partition' : None,
274
+ 'dist' : .075,
275
+ 'max_dist' : 1.5,
276
+ 'label_fontsize' : 10,
277
+ 'loop_size' : .075,
278
+ 'edge_labels_background' : 'white'}
279
+
280
+
281
+ class GraphPlot(SageObject):
282
+ def __init__(self, graph, options):
283
+ """
284
+ Return a ``GraphPlot`` object, which stores all the parameters needed
285
+ for plotting (Di)Graphs.
286
+
287
+ A ``GraphPlot`` has a plot and show function, as well as some functions
288
+ to set parameters for vertices and edges. This constructor assumes
289
+ default options are set. Defaults are shown in the example below.
290
+
291
+ EXAMPLES::
292
+
293
+ sage: from sage.graphs.graph_plot import GraphPlot
294
+ sage: options = {
295
+ ....: 'vertex_size': 200,
296
+ ....: 'vertex_labels': True,
297
+ ....: 'layout': None,
298
+ ....: 'edge_style': 'solid',
299
+ ....: 'edge_color': 'black',
300
+ ....: 'edge_colors': None,
301
+ ....: 'edge_labels': False,
302
+ ....: 'iterations': 50,
303
+ ....: 'tree_orientation': 'down',
304
+ ....: 'heights': None,
305
+ ....: 'graph_border': False,
306
+ ....: 'talk': False,
307
+ ....: 'color_by_label': False,
308
+ ....: 'partition': None,
309
+ ....: 'dist': .075,
310
+ ....: 'max_dist': 1.5,
311
+ ....: 'loop_size': .075,
312
+ ....: 'edge_labels_background': 'transparent'}
313
+ sage: g = Graph({0: [1, 2], 2: [3], 4: [0, 1]})
314
+ sage: GP = GraphPlot(g, options)
315
+ """
316
+ # Setting the default values if needed
317
+ for k, value in DEFAULT_PLOT_OPTIONS.items():
318
+ if k not in options:
319
+ options[k] = value
320
+ self._plot_components = {}
321
+ self._nodelist = list(graph)
322
+ self._graph = graph
323
+ self._options = options # contains both plot and show options
324
+ self._arcs = self._graph.has_multiple_edges(to_undirected=True)
325
+ self._loops = self._graph.has_loops()
326
+ self._arcdigraph = self._graph.is_directed() and self._arcs
327
+
328
+ self.set_pos()
329
+ self.set_vertices()
330
+ self.set_edges()
331
+
332
+ def _repr_(self):
333
+ """
334
+ Return a string representation of a ``GraphPlot`` object.
335
+
336
+ EXAMPLES:
337
+
338
+ This function is called implicitly by the code below::
339
+
340
+ sage: g = Graph({0: [1, 2], 2: [3], 4: [0, 1]})
341
+ sage: g.graphplot() # indirect doctest
342
+ GraphPlot object for Graph on 5 vertices
343
+ """
344
+ return f"GraphPlot object for {self._graph}"
345
+
346
+ def set_pos(self):
347
+ """
348
+ Set the position plotting parameters for this GraphPlot.
349
+
350
+ EXAMPLES:
351
+
352
+ This function is called implicitly by the code below::
353
+
354
+ sage: g = Graph({0: [1, 2], 2: [3], 4: [0, 1]})
355
+ sage: g.graphplot(save_pos=True, layout='circular') # indirect doctest
356
+ GraphPlot object for Graph on 5 vertices
357
+
358
+ The following illustrates the format of a position dictionary, but due
359
+ to numerical noise we do not check the values themselves::
360
+
361
+ sage: g.get_pos()
362
+ {0: (0.0, 1.0),
363
+ 1: (-0.951..., 0.309...),
364
+ 2: (-0.587..., -0.809...),
365
+ 3: (0.587..., -0.809...),
366
+ 4: (0.951..., 0.309...)}
367
+
368
+ ::
369
+
370
+ sage: T = list(graphs.trees(7))
371
+ sage: t = T[3]
372
+ sage: t.plot(heights={0: [0], 1: [4, 5, 1], 2: [2], 3: [3, 6]})
373
+ Graphics object consisting of 14 graphics primitives
374
+
375
+ .. PLOT::
376
+
377
+ g = Graph({0: [1, 2], 2: [3], 4: [0, 1]})
378
+ g.graphplot(save_pos=True, layout='circular') # indirect doctest
379
+ T = list(graphs.trees(7))
380
+ t = T[3]
381
+ P = t.plot(heights={0: [0], 1: [4, 5, 1], 2: [2], 3: [3, 6]})
382
+ sphinx_plot(P)
383
+
384
+ TESTS:
385
+
386
+ Make sure that vertex locations are floats. Not being floats isn't
387
+ a bug in itself but made it too easy to accidentally introduce a bug
388
+ elsewhere, such as in :meth:`set_edges` (:issue:`10124`), via silent
389
+ truncating division of Python 2 integers::
390
+
391
+ sage: g = graphs.FruchtGraph()
392
+ sage: gp = g.graphplot()
393
+ sage: set(map(type, flatten(gp._pos.values())))
394
+ {<... 'float'>}
395
+ sage: g = graphs.BullGraph()
396
+ sage: gp = g.graphplot(save_pos=True)
397
+ sage: set(map(type, flatten(gp._pos.values())))
398
+ {<... 'float'>}
399
+
400
+ Non-ascii labels are also possible using unicode (:issue:`21008`)::
401
+
402
+ sage: Graph({u'où': [u'là', u'ici']}).plot()
403
+ Graphics object consisting of 6 graphics primitives
404
+ """
405
+ self._pos = self._graph.layout(**self._options)
406
+ # Make sure the positions are floats (trac #10124)
407
+ self._pos = {k: (float(v[0]), float(v[1]))
408
+ for k, v in self._pos.items()}
409
+
410
+ def set_vertices(self, **vertex_options):
411
+ """
412
+ Set the vertex plotting parameters for this ``GraphPlot``.
413
+
414
+ This function is called by the constructor but can also be
415
+ called to make updates to the vertex options of an existing
416
+ ``GraphPlot`` object. Note that the changes are cumulative.
417
+
418
+ EXAMPLES::
419
+
420
+ sage: g = Graph({}, loops=True, multiedges=True, sparse=True)
421
+ sage: g.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
422
+ ....: (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
423
+ ....: (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
424
+ sage: GP = g.graphplot(vertex_size=100, edge_labels=True,
425
+ ....: color_by_label=True, edge_style='dashed')
426
+ sage: GP.set_vertices(talk=True)
427
+ sage: GP.plot()
428
+ Graphics object consisting of 22 graphics primitives
429
+ sage: GP.set_vertices(vertex_color='green', vertex_shape='^')
430
+ sage: GP.plot()
431
+ Graphics object consisting of 22 graphics primitives
432
+
433
+ .. PLOT::
434
+
435
+ g = Graph({}, loops=True, multiedges=True, sparse=True)
436
+ g.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
437
+ (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
438
+ (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
439
+ GP = g.graphplot(vertex_size=100, edge_labels=True,
440
+ color_by_label=True, edge_style='dashed')
441
+ GP.set_vertices(talk=True)
442
+ sphinx_plot(GP)
443
+
444
+ .. PLOT::
445
+
446
+ g = Graph({}, loops=True, multiedges=True, sparse=True)
447
+ g.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
448
+ (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
449
+ (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
450
+ GP = g.graphplot(vertex_size=100, edge_labels=True,
451
+ color_by_label=True, edge_style='dashed')
452
+ GP.set_vertices(talk=True)
453
+ GP.set_vertices(vertex_color='green', vertex_shape='^')
454
+ sphinx_plot(GP)
455
+
456
+ Vertex labels are flexible::
457
+
458
+ sage: g = graphs.PathGraph(4)
459
+ sage: g.plot(vertex_labels=False)
460
+ Graphics object consisting of 4 graphics primitives
461
+
462
+ .. PLOT::
463
+
464
+ g = graphs.PathGraph(4)
465
+ P = g.graphplot(vertex_labels=False)
466
+ sphinx_plot(P)
467
+
468
+ ::
469
+
470
+ sage: g = graphs.PathGraph(4)
471
+ sage: g.plot(vertex_labels=True)
472
+ Graphics object consisting of 8 graphics primitives
473
+
474
+ .. PLOT::
475
+
476
+ g = graphs.PathGraph(4)
477
+ P = g.graphplot(vertex_labels=True)
478
+ sphinx_plot(P)
479
+
480
+ ::
481
+
482
+ sage: g = graphs.PathGraph(4)
483
+ sage: g.plot(vertex_labels=dict(zip(g, ['+', '-', '/', '*'])))
484
+ Graphics object consisting of 8 graphics primitives
485
+
486
+ .. PLOT::
487
+
488
+ g = graphs.PathGraph(4)
489
+ P = g.graphplot(vertex_labels=dict(zip(g, ['+', '-', '/', '*'])))
490
+ sphinx_plot(P)
491
+
492
+ ::
493
+
494
+ sage: g = graphs.PathGraph(4)
495
+ sage: g.plot(vertex_labels=lambda x: str(x % 2))
496
+ Graphics object consisting of 8 graphics primitives
497
+
498
+ .. PLOT::
499
+
500
+ g = graphs.PathGraph(4)
501
+ P = g.graphplot(vertex_labels=lambda x: str(x % 2))
502
+ sphinx_plot(P)
503
+ """
504
+ # Handle base vertex options
505
+ voptions = {}
506
+
507
+ for arg in vertex_options:
508
+ self._options[arg] = vertex_options[arg]
509
+
510
+ # First set defaults for styles
511
+ vertex_colors = None
512
+ if self._options['talk']:
513
+ voptions['markersize'] = 500
514
+ if self._options['partition'] is None:
515
+ vertex_colors = '#ffffff'
516
+ else:
517
+ voptions['markersize'] = self._options['vertex_size']
518
+
519
+ if ('vertex_color' not in self._options
520
+ or self._options['vertex_color'] is None):
521
+ vertex_color = '#fec7b8'
522
+ else:
523
+ vertex_color = self._options['vertex_color']
524
+
525
+ if ('vertex_colors' not in self._options
526
+ or self._options['vertex_colors'] is None):
527
+ if self._options['partition'] is not None:
528
+ from sage.plot.colors import rainbow
529
+ partition = self._options['partition']
530
+ length = len(partition)
531
+ R = rainbow(length)
532
+ vertex_colors = {R[i]: partition[i] for i in range(length)}
533
+ elif not vertex_colors:
534
+ vertex_colors = vertex_color
535
+ else:
536
+ vertex_colors = self._options['vertex_colors']
537
+
538
+ if 'vertex_shape' in self._options:
539
+ voptions['marker'] = self._options['vertex_shape']
540
+
541
+ if self._graph.is_directed():
542
+ self._vertex_radius = sqrt(voptions['markersize'] / pi)
543
+ self._arrowshorten = 2 * self._vertex_radius
544
+ if self._arcdigraph:
545
+ self._vertex_radius = sqrt(voptions['markersize'] / (20500 * pi))
546
+
547
+ voptions['zorder'] = 7
548
+
549
+ if not isinstance(vertex_colors, dict):
550
+ voptions['facecolor'] = vertex_colors
551
+ pos = list(self._pos.values())
552
+ if self._arcdigraph:
553
+ self._plot_components['vertices'] = [
554
+ circle(p, self._vertex_radius, fill=True, clip=False,
555
+ edgecolor='black', facecolor=vertex_colors)
556
+ for p in pos]
557
+ else:
558
+ self._plot_components['vertices'] = (
559
+ scatter_plot(pos, clip=False, **voptions))
560
+ else:
561
+ # Color list must be ordered:
562
+ pos = []
563
+ colors = []
564
+ for i in vertex_colors:
565
+ pos.extend([self._pos[j] for j in vertex_colors[i]])
566
+ colors.extend([i] * len(vertex_colors[i]))
567
+
568
+ # If all the vertices have not been assigned a color
569
+ if len(self._pos) != len(pos):
570
+ leftovers = [j for j in self._pos.values() if j not in pos]
571
+ pos.extend(leftovers)
572
+ colors.extend([vertex_color] * len(leftovers))
573
+
574
+ if self._arcdigraph:
575
+ self._plot_components['vertices'] = [
576
+ circle(p, self._vertex_radius, fill=True, clip=False,
577
+ facecolor=colors[i], edgecolor='black')
578
+ for i, p in enumerate(pos)]
579
+ else:
580
+ self._plot_components['vertices'] = scatter_plot(
581
+ pos, facecolor=colors, clip=False, **voptions)
582
+
583
+ vlabels = self._options['vertex_labels']
584
+ if vlabels:
585
+ if vlabels is True:
586
+ vfun = str
587
+ elif isinstance(vlabels, dict):
588
+ def vfun(x):
589
+ return vlabels.get(x, "")
590
+ else:
591
+ vfun = vlabels
592
+
593
+ # TODO: allow text options
594
+ if self._options['layout'] == 'circular' and self._options['vertex_label_shift'] is not None:
595
+ def pos_shift(v, shift):
596
+ return (v[0] + (v[0] * shift[0])/100, v[1] + (v[1] * shift[1])/100)
597
+ self._plot_components['vertex_labels'] = [
598
+ text(
599
+ vfun(v),
600
+ pos_shift(self._pos[v], self._options['vertex_label_shift']),
601
+ fontsize=self._options['label_fontsize'],
602
+ color='black',
603
+ zorder=8
604
+ )
605
+ for v in self._nodelist
606
+ ]
607
+ else:
608
+ self._plot_components['vertex_labels'] = [
609
+ text(vfun(v), self._pos[v], color='black', zorder=8, fontsize=self._options['label_fontsize'])
610
+ for v in self._nodelist
611
+ ]
612
+
613
+ def set_edges(self, **edge_options):
614
+ """
615
+ Set edge plotting parameters for the ``GraphPlot`` object.
616
+
617
+ This function is called by the constructor but can also be called to
618
+ update the edge options of an existing ``GraphPlot`` object.
619
+ Note that the changes are cumulative.
620
+
621
+ EXAMPLES::
622
+
623
+ sage: g = Graph(loops=True, multiedges=True, sparse=True)
624
+ sage: g.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
625
+ ....: (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
626
+ ....: (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
627
+ sage: GP = g.graphplot(vertex_size=100, edge_labels=True,
628
+ ....: color_by_label=True, edge_style='dashed')
629
+ sage: GP.set_edges(edge_style='solid')
630
+ sage: GP.plot()
631
+ Graphics object consisting of 22 graphics primitives
632
+
633
+ .. PLOT::
634
+
635
+ g = Graph(loops=True, multiedges=True, sparse=True)
636
+ g.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
637
+ (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
638
+ (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
639
+ GP = g.graphplot(vertex_size=100, edge_labels=True,
640
+ color_by_label=True, edge_style='dashed')
641
+ GP.set_edges(edge_style='solid')
642
+ sphinx_plot(GP)
643
+
644
+ ::
645
+
646
+ sage: GP.set_edges(edge_color='black')
647
+ sage: GP.plot()
648
+ Graphics object consisting of 22 graphics primitives
649
+
650
+ .. PLOT::
651
+
652
+ g = Graph(loops=True, multiedges=True, sparse=True)
653
+ g.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
654
+ (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
655
+ (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
656
+ GP = g.graphplot(vertex_size=100, edge_labels=True,
657
+ color_by_label=True, edge_style='dashed')
658
+ GP.set_edges(edge_style='solid')
659
+ GP.set_edges(edge_color='black')
660
+ sphinx_plot(GP)
661
+
662
+ ::
663
+
664
+ sage: d = DiGraph(loops=True, multiedges=True, sparse=True)
665
+ sage: d.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
666
+ ....: (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
667
+ ....: (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
668
+ sage: GP = d.graphplot(vertex_size=100, edge_labels=True,
669
+ ....: color_by_label=True, edge_style='dashed')
670
+ sage: GP.set_edges(edge_style='solid')
671
+ sage: GP.plot()
672
+ Graphics object consisting of 24 graphics primitives
673
+
674
+ .. PLOT::
675
+
676
+ d = DiGraph(loops=True, multiedges=True, sparse=True)
677
+ d.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
678
+ (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
679
+ (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
680
+ GP = d.graphplot(vertex_size=100, edge_labels=True,
681
+ color_by_label=True, edge_style='dashed')
682
+ GP.set_edges(edge_style='solid')
683
+ sphinx_plot(GP)
684
+
685
+ ::
686
+
687
+ sage: GP.set_edges(edge_color='black')
688
+ sage: GP.plot()
689
+ Graphics object consisting of 24 graphics primitives
690
+
691
+ .. PLOT::
692
+
693
+ d = DiGraph(loops=True, multiedges=True, sparse=True)
694
+ d.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
695
+ (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
696
+ (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
697
+ GP = d.graphplot(vertex_size=100, edge_labels=True,
698
+ color_by_label=True, edge_style='dashed')
699
+ GP.set_edges(edge_style='solid')
700
+ GP.set_edges(edge_color='black')
701
+ sphinx_plot(GP)
702
+
703
+ TESTS::
704
+
705
+ sage: G = Graph("Fooba")
706
+ sage: G.show(edge_colors={'red':[(3, 6), (2, 5)]})
707
+
708
+ Check default edge labels are pretty close to halfway between
709
+ the vertices in some cases where they weren't due to Python 2
710
+ truncating division (:issue:`10124`)::
711
+
712
+ sage: test_graphs = graphs.FruchtGraph(), graphs.BullGraph()
713
+ sage: tol = 0.001
714
+ sage: for G in test_graphs:
715
+ ....: E = G.edges(sort=True)
716
+ ....: for e0, e1, elab in E:
717
+ ....: G.set_edge_label(e0, e1, '%d %d' % (e0, e1))
718
+ ....: gp = G.graphplot(save_pos=True, edge_labels=True)
719
+ ....: vx = gp._plot_components['vertices'][0].xdata
720
+ ....: vy = gp._plot_components['vertices'][0].ydata
721
+ ....: for elab in gp._plot_components['edge_labels']:
722
+ ....: textobj = elab[0]
723
+ ....: x, y, s = textobj.x, textobj.y, textobj.string
724
+ ....: v0, v1 = map(int, s.split())
725
+ ....: m = sum(vector((vx[v], vy[v])) for v in (v0, v1))/2
726
+ ....: assert (vector((x, y)) - m).norm() < tol
727
+
728
+ Issue :issue:`24051` is fixed::
729
+
730
+ sage: G = Graph([(0, 1), (0, 1)], multiedges=True)
731
+ sage: G.plot(edge_colors={"red": [(1, 0)]})
732
+ Graphics object consisting of 5 graphics primitives
733
+
734
+ Issue :issue:`31542` is fixed::
735
+
736
+ sage: s = 'ABCCCCDABCDABCDA'
737
+ sage: g = DiGraph({}, loops=True, multiedges=True)
738
+ sage: for a, b in [(s[i], u) for i, u in enumerate(s[1:])]:
739
+ ....: g.add_edge(a, b, b)
740
+ sage: g.plot(color_by_label=True, layout='circular')
741
+ Graphics object consisting of 23 graphics primitives
742
+ """
743
+ for arg in edge_options:
744
+ self._options[arg] = edge_options[arg]
745
+ if 'edge_colors' in edge_options:
746
+ self._options['color_by_label'] = False
747
+ if self._options['edge_labels_background'] == "transparent":
748
+ self._options['edge_labels_background'] = "None"
749
+
750
+ # Whether a key is an edge or not:
751
+ # None => edge_x is not set
752
+ # True => keys are edges
753
+ # False => keys are labels
754
+ style_key_edges = None
755
+ thickness_key_edges = None
756
+ if isinstance(self._options['edge_styles'], dict):
757
+ style_key_edges = next(iter(self._options['edge_styles'])) in self._graph.edges()
758
+ if isinstance(self._options['edge_thicknesses'], dict):
759
+ thickness_key_edges = next(iter(self._options['edge_thicknesses'])) in self._graph.edges()
760
+
761
+ eoptions = {}
762
+ if 'arrowsize' in self._options:
763
+ eoptions['arrowsize'] = self._options['arrowsize']
764
+
765
+ # Set labels param to add labels on the fly
766
+ labels = False
767
+ if self._options['edge_labels']:
768
+ labels = True
769
+ self._plot_components['edge_labels'] = []
770
+
771
+ # Make dict collection of all edges (keep label and edge color)
772
+ edges_to_draw = defaultdict(list)
773
+
774
+ v_to_int = {v: i for i, v in enumerate(self._graph)}
775
+
776
+ if (self._options['color_by_label']
777
+ or isinstance(self._options['edge_colors'], dict)):
778
+ if self._options['color_by_label']:
779
+ edge_colors = self._graph._color_by_label(
780
+ format=self._options['color_by_label'])
781
+ else:
782
+ edge_colors = self._options['edge_colors']
783
+ edges_drawn = []
784
+ for color in edge_colors:
785
+ for edge in edge_colors[color]:
786
+ a, b = edge[0], edge[1]
787
+ if v_to_int[a] < v_to_int[b]:
788
+ key = (a, b)
789
+ head = 1
790
+ else:
791
+ key = (b, a)
792
+ head = 0
793
+ if len(edge) < 3:
794
+ label = self._graph.edge_label(a, b)
795
+ if isinstance(label, list):
796
+ edges_to_draw[key].append((label[-1], color, head))
797
+ edges_drawn.append((a, b, label[-1]))
798
+ for lab in label[:-1]:
799
+ edges_to_draw[key].append((lab, color, head))
800
+ edges_drawn.append((a, b, lab))
801
+ else:
802
+ edges_to_draw[key].append((label, color, head))
803
+ edges_drawn.append((a, b, label))
804
+ else:
805
+ label = edge[2]
806
+ edges_to_draw[key].append((label, color, head))
807
+ edges_drawn.append((a, b, label))
808
+
809
+ # Add unspecified edges (default color black set in DEFAULT_PLOT_OPTIONS)
810
+ for a, b, c in self._graph.edge_iterator():
811
+ if ((a, b, c) not in edges_drawn
812
+ and (self._graph.is_directed()
813
+ or (b, a, c) not in edges_drawn)):
814
+ if v_to_int[a] < v_to_int[b]:
815
+ key = (a, b)
816
+ head = 1
817
+ else:
818
+ key = (b, a)
819
+ head = 0
820
+ edges_to_draw[key].append((c, self._options['edge_color'], head))
821
+
822
+ else:
823
+ for a, b, c in self._graph.edge_iterator():
824
+ if v_to_int[a] < v_to_int[b]:
825
+ key = (a, b)
826
+ head = 1
827
+ else:
828
+ key = (b, a)
829
+ head = 0
830
+ edges_to_draw[key].append((c, self._options['edge_color'], head))
831
+
832
+ if edges_to_draw:
833
+ self._plot_components['edges'] = []
834
+ else:
835
+ return
836
+
837
+ # Check for multi-edges or loops
838
+ if self._arcs or self._loops:
839
+ tmp = edges_to_draw.copy()
840
+ dist = self._options['dist'] * 2
841
+ min_loop_size = self._options['loop_size']
842
+ max_dist = self._options['max_dist']
843
+ from sage.misc.functional import sqrt
844
+ for a, b in tmp:
845
+ if a == b:
846
+ # Multiple loops need varying loop radius starting at
847
+ # minimum loop size and respecting other distances
848
+ loop_size = min_loop_size # current loop radius
849
+ distance = dist
850
+ local_labels = edges_to_draw.pop((a, b))
851
+ len_local_labels = len(local_labels)
852
+ if len_local_labels * dist > max_dist:
853
+ distance = float(max_dist) / len_local_labels
854
+ loop_size_increment = distance / 4
855
+ # Now add all the loops at this vertex, varying their size
856
+ for lab, col, _ in local_labels:
857
+ x, y = self._pos[a][0], self._pos[a][1] - loop_size
858
+
859
+ estyle = self._options['edge_style']
860
+ ethickness = self._options['edge_thickness']
861
+ if (style_key_edges is not None
862
+ and ((style_key_edges and (x, y) in self._options['edge_styles'])
863
+ or (not style_key_edges and lab in self._options['edge_styles']))):
864
+ estyle = style_key_edges and self._options['edge_styles'][(x, y)] or self._options['edge_styles'][lab]
865
+ if (thickness_key_edges is not None
866
+ and ((thickness_key_edges and (x, y) in self._options['edge_thicknesses'])
867
+ or (not thickness_key_edges and lab in self._options['edge_thicknesses']))):
868
+ ethickness = thickness_key_edges and self._options['edge_thicknesses'][(x, y)] or self._options['edge_thicknesses'][lab]
869
+
870
+ c = circle((x, y), loop_size, rgbcolor=col, linestyle=estyle, thickness=ethickness)
871
+ self._plot_components['edges'].append(c)
872
+ if labels:
873
+ bg = self._options['edge_labels_background']
874
+ y -= loop_size # place label at bottom of loop
875
+ t = text(lab, (x, y), background_color=bg, fontsize=self._options['label_fontsize'])
876
+ self._plot_components['edge_labels'].append(t)
877
+ loop_size += loop_size_increment
878
+ elif len(edges_to_draw[a, b]) > 1:
879
+ # Multi-edge
880
+ local_labels = edges_to_draw.pop((a, b))
881
+
882
+ # Compute perpendicular bisector
883
+ p1 = self._pos[a]
884
+ p2 = self._pos[b]
885
+ m = ((p1[0] + p2[0]) / 2., (p1[1] + p2[1]) / 2.) # midpoint
886
+ if not p1[1] == p2[1]:
887
+ s = (p1[0] - p2[0]) / (p2[1] - p1[1]) # perp slope
888
+
889
+ def y(x):
890
+ return s * (x - m[0]) + m[1] # perp bisector line
891
+
892
+ # f, g are functions to determine x-values of point
893
+ # on line y at distance d from point m (on each side)
894
+ def f(d):
895
+ return sqrt(d**2 / (1. + s**2)) + m[0]
896
+
897
+ def g(d):
898
+ return -sqrt(d**2 / (1. + s**2)) + m[0]
899
+
900
+ odd_x = f
901
+ even_x = g
902
+ if p1[0] == p2[0]:
903
+ def odd_y(d):
904
+ return m[1]
905
+
906
+ even_y = odd_y
907
+ else:
908
+ def odd_y(x):
909
+ return y(f(x))
910
+
911
+ def even_y(x):
912
+ return y(g(x))
913
+ else:
914
+ def odd_x(d):
915
+ return m[0]
916
+
917
+ even_x = odd_x
918
+
919
+ def odd_y(d):
920
+ return m[1] + d
921
+
922
+ def even_y(d):
923
+ return m[1] - d
924
+
925
+ def odd_xy(d):
926
+ return (odd_x(d), odd_y(d))
927
+
928
+ def even_xy(d):
929
+ return (even_x(d), even_y(d))
930
+
931
+ # We now have the control points for each Bezier curve
932
+ # in terms of distance parameter d.
933
+ # Also note each edge label should be drawn at d/2.
934
+ # (This is because we're using the perp bisectors).
935
+ distance = dist
936
+ len_local_labels = len(local_labels)
937
+ if len_local_labels * dist > max_dist:
938
+ distance = float(max_dist) / len_local_labels
939
+ for i in range(len_local_labels // 2):
940
+ k = (i + 1.0) * distance
941
+ estyle = self._options['edge_style']
942
+ ethickness = self._options['edge_thickness']
943
+
944
+ if self._arcdigraph:
945
+ vr = self._vertex_radius
946
+ ph = self._polar_hack_for_multidigraph
947
+ odd_start = ph(p1, odd_xy(k), vr)[0]
948
+ odd_end = ph(odd_xy(k), p2, vr)[1]
949
+ even_start = ph(p1, even_xy(k), vr)[0]
950
+ even_end = ph(even_xy(k), p2, vr)[1]
951
+
952
+ self._plot_components['edges'].append(
953
+ arrow(path=[[odd_start, odd_xy(k), odd_end]],
954
+ head=local_labels[2 * i][2], zorder=1,
955
+ rgbcolor=local_labels[2 * i][1],
956
+ linestyle=estyle,
957
+ width=ethickness,
958
+ **eoptions
959
+ ))
960
+ self._plot_components['edges'].append(
961
+ arrow(path=[[even_start, even_xy(k), even_end]],
962
+ head=local_labels[2 * i + 1][2], zorder=1,
963
+ rgbcolor=local_labels[2 * i + 1][1],
964
+ linestyle=estyle,
965
+ width=ethickness,
966
+ **eoptions
967
+ ))
968
+ else:
969
+ self._plot_components['edges'].append(
970
+ bezier_path([[p1, odd_xy(k), p2]], zorder=1,
971
+ rgbcolor=local_labels[2 * i][1],
972
+ linestyle=estyle,
973
+ thickness=ethickness
974
+ ))
975
+ self._plot_components['edges'].append(
976
+ bezier_path([[p1, even_xy(k), p2]], zorder=1,
977
+ rgbcolor=local_labels[2 * i + 1][1],
978
+ linestyle=estyle,
979
+ thickness=ethickness
980
+ ))
981
+ if labels:
982
+ j = k / 2.0
983
+ bg = self._options['edge_labels_background']
984
+ self._plot_components['edge_labels'].append(
985
+ text(local_labels[2 * i][0], odd_xy(j),
986
+ background_color=bg, fontsize=self._options['label_fontsize']))
987
+ self._plot_components['edge_labels'].append(
988
+ text(local_labels[2 * i + 1][0], even_xy(j),
989
+ background_color=bg, fontsize=self._options['label_fontsize']))
990
+ if len_local_labels % 2:
991
+ # draw line for last odd
992
+ edges_to_draw[a, b] = [local_labels[-1]]
993
+
994
+ is_directed = self._graph.is_directed()
995
+ for a, b in edges_to_draw:
996
+ elabel = edges_to_draw[a, b][0][0]
997
+ ecolor = edges_to_draw[a, b][0][1]
998
+ ehead = edges_to_draw[a, b][0][2]
999
+ e = (a, b, elabel)
1000
+
1001
+ estyle = self._options['edge_style']
1002
+ ethickness = self._options['edge_thickness']
1003
+ if (style_key_edges is not None
1004
+ and ((style_key_edges and e in self._options['edge_styles'])
1005
+ or (not style_key_edges and elabel in self._options['edge_styles']))):
1006
+ estyle = style_key_edges and self._options['edge_styles'][e] or self._options['edge_styles'][elabel]
1007
+ if (thickness_key_edges is not None
1008
+ and ((thickness_key_edges and e in self._options['edge_thicknesses'])
1009
+ or (not thickness_key_edges and elabel in self._options['edge_thicknesses']))):
1010
+ ethickness = thickness_key_edges and self._options['edge_thicknesses'][e] or self._options['edge_thicknesses'][elabel]
1011
+
1012
+ if self._arcdigraph:
1013
+ ph = self._polar_hack_for_multidigraph
1014
+ C, D = ph(self._pos[a], self._pos[b], self._vertex_radius)
1015
+ self._plot_components['edges'].append(
1016
+ arrow(C, D,
1017
+ rgbcolor=ecolor,
1018
+ head=ehead,
1019
+ linestyle=estyle,
1020
+ width=ethickness,
1021
+ **eoptions
1022
+ ))
1023
+ if labels:
1024
+ bg = self._options['edge_labels_background']
1025
+ self._plot_components['edge_labels'].append(
1026
+ text(str(elabel),
1027
+ [(C[0] + D[0]) / 2., (C[1] + D[1]) / 2.],
1028
+ background_color=bg,
1029
+ fontsize=self._options['label_fontsize']
1030
+ ))
1031
+ elif is_directed:
1032
+ self._plot_components['edges'].append(
1033
+ arrow(self._pos[a], self._pos[b],
1034
+ rgbcolor=ecolor,
1035
+ arrowshorten=self._arrowshorten,
1036
+ head=ehead,
1037
+ linestyle=estyle,
1038
+ width=ethickness,
1039
+ **eoptions
1040
+ ))
1041
+ else:
1042
+ self._plot_components['edges'].append(
1043
+ line([self._pos[a], self._pos[b]],
1044
+ rgbcolor=ecolor,
1045
+ linestyle=estyle,
1046
+ thickness=ethickness
1047
+ ))
1048
+ if labels and not self._arcdigraph:
1049
+ bg = self._options['edge_labels_background']
1050
+ self._plot_components['edge_labels'].append(
1051
+ text(str(edges_to_draw[a, b][0][0]),
1052
+ [(self._pos[a][0] + self._pos[b][0]) / 2.,
1053
+ (self._pos[a][1] + self._pos[b][1]) / 2.],
1054
+ background_color=bg,
1055
+ fontsize=self._options['label_fontsize']
1056
+ ))
1057
+
1058
+ def _polar_hack_for_multidigraph(self, A, B, VR):
1059
+ """
1060
+ Helper function to quickly compute the two points of intersection
1061
+ of a line segment from ``A`` to ``B`` (provided as xy pairs) and
1062
+ circles centered at ``A`` and ``B``, both with radius ``VR``.
1063
+ Returns a pair of xy pairs representing the two points.
1064
+
1065
+ EXAMPLES::
1066
+
1067
+ sage: d = DiGraph(loops=True, multiedges=True, sparse=True)
1068
+ sage: d.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
1069
+ ....: (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
1070
+ ....: (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
1071
+ sage: GP = d.graphplot(vertex_size=100, edge_labels=True,
1072
+ ....: color_by_label=True, edge_style='dashed')
1073
+ sage: GP._polar_hack_for_multidigraph((0, 1), (1, 1), .1)
1074
+ ([0.10..., 1.00...], [0.90..., 1.00...])
1075
+
1076
+ TESTS:
1077
+
1078
+ Make sure that Python ints are acceptable arguments (:issue:`10124`)::
1079
+
1080
+ sage: GP = DiGraph().graphplot()
1081
+ sage: GP._polar_hack_for_multidigraph((0, 1), (2, 2), .1)
1082
+ ([0.08..., 1.04...], [1.91..., 1.95...])
1083
+ sage: GP._polar_hack_for_multidigraph((int(0), int(1)),
1084
+ ....: (int(2), int(2)), .1)
1085
+ ([0.08..., 1.04...], [1.91..., 1.95...])
1086
+ """
1087
+ D = [float(B[i] - A[i]) for i in range(2)]
1088
+ R = sqrt(D[0]**2 + D[1]**2)
1089
+ theta = 3 * pi / 2
1090
+ if D[0] > 0:
1091
+ theta = atan(D[1] / D[0])
1092
+ if D[1] < 0:
1093
+ theta += 2 * pi
1094
+ elif D[0] < 0:
1095
+ theta = atan(D[1] / D[0]) + pi
1096
+ elif D[1] > 0:
1097
+ theta = pi / 2
1098
+ cos_theta = cos(theta)
1099
+ sin_theta = sin(theta)
1100
+ return ([VR * cos_theta + A[0], VR * sin_theta + A[1]],
1101
+ [(R - VR) * cos_theta + A[0], (R - VR) * sin_theta + A[1]])
1102
+
1103
+ def show(self, **kwds):
1104
+ """
1105
+ Show the (di)graph associated with this ``GraphPlot`` object.
1106
+
1107
+ INPUT:
1108
+
1109
+ This method accepts all parameters of
1110
+ :meth:`sage.plot.graphics.Graphics.show`.
1111
+
1112
+ .. NOTE::
1113
+
1114
+ - See :mod:`the module's documentation <sage.graphs.graph_plot>`
1115
+ for information on default values of this method.
1116
+
1117
+ - Any options not used by plot will be passed on to the
1118
+ :meth:`~sage.plot.graphics.Graphics.show` method.
1119
+
1120
+ EXAMPLES::
1121
+
1122
+ sage: C = graphs.CubeGraph(8)
1123
+ sage: P = C.graphplot(vertex_labels=False, vertex_size=0,
1124
+ ....: graph_border=True)
1125
+ sage: P.show()
1126
+
1127
+ .. PLOT::
1128
+
1129
+ C = graphs.CubeGraph(8)
1130
+ P = C.graphplot(vertex_labels=False, vertex_size=0,
1131
+ graph_border=True)
1132
+ sphinx_plot(P)
1133
+ """
1134
+ # Setting the default values if needed
1135
+ for k, value in DEFAULT_SHOW_OPTIONS.items():
1136
+ if k not in kwds:
1137
+ kwds[k] = value
1138
+
1139
+ self.plot().show(**kwds)
1140
+
1141
+ def plot(self, **kwds):
1142
+ """
1143
+ Return a graphics object representing the (di)graph.
1144
+
1145
+ INPUT:
1146
+
1147
+ The options accepted by this method are to be found in the
1148
+ documentation of the :mod:`sage.graphs.graph_plot` module,
1149
+ and the :meth:`~sage.plot.graphics.Graphics.show` method.
1150
+
1151
+ .. NOTE::
1152
+
1153
+ See :mod:`the module's documentation <sage.graphs.graph_plot>` for
1154
+ information on default values of this method.
1155
+
1156
+ We can specify some pretty precise plotting of familiar graphs::
1157
+
1158
+ sage: from math import sin, cos, pi
1159
+ sage: P = graphs.PetersenGraph()
1160
+ sage: d = {'#FF0000': [0, 5], '#FF9900': [1, 6], '#FFFF00': [2, 7],
1161
+ ....: '#00FF00': [3, 8], '#0000FF': [4,9]}
1162
+ sage: pos_dict = {}
1163
+ sage: for i in range(5):
1164
+ ....: x = float(cos(pi/2 + ((2*pi)/5)*i))
1165
+ ....: y = float(sin(pi/2 + ((2*pi)/5)*i))
1166
+ ....: pos_dict[i] = [x,y]
1167
+ ...
1168
+ sage: for i in range(5, 10):
1169
+ ....: x = float(0.5*cos(pi/2 + ((2*pi)/5)*i))
1170
+ ....: y = float(0.5*sin(pi/2 + ((2*pi)/5)*i))
1171
+ ....: pos_dict[i] = [x,y]
1172
+ ...
1173
+ sage: pl = P.graphplot(pos=pos_dict, vertex_colors=d)
1174
+ sage: pl.show()
1175
+
1176
+ .. PLOT::
1177
+
1178
+ from math import sin, cos, pi
1179
+ P = graphs.PetersenGraph()
1180
+ d = {'#FF0000': [0, 5], '#FF9900': [1, 6], '#FFFF00': [2, 7],
1181
+ '#00FF00': [3, 8], '#0000FF': [4,9]}
1182
+ pos_dict = {}
1183
+ for i in range(5):
1184
+ x = float(cos(pi/2 + ((2*pi)/5)*i))
1185
+ y = float(sin(pi/2 + ((2*pi)/5)*i))
1186
+ pos_dict[i] = [x,y]
1187
+
1188
+ for i in range(5, 10):
1189
+ x = float(0.5*cos(pi/2 + ((2*pi)/5)*i))
1190
+ y = float(0.5*sin(pi/2 + ((2*pi)/5)*i))
1191
+ pos_dict[i] = [x,y]
1192
+
1193
+ pl = P.graphplot(pos=pos_dict, vertex_colors=d)
1194
+ sphinx_plot(pl)
1195
+
1196
+ Here are some more common graphs with typical options::
1197
+
1198
+ sage: C = graphs.CubeGraph(8)
1199
+ sage: P = C.graphplot(vertex_labels=False, vertex_size=0,
1200
+ ....: graph_border=True)
1201
+ sage: P.show()
1202
+
1203
+ .. PLOT::
1204
+
1205
+ C = graphs.CubeGraph(8)
1206
+ P = C.graphplot(vertex_labels=False, vertex_size=0,
1207
+ graph_border=True)
1208
+ sphinx_plot(P)
1209
+
1210
+ ::
1211
+
1212
+ sage: G = graphs.HeawoodGraph().copy(sparse=True)
1213
+ sage: for u, v, l in G.edges(sort=True):
1214
+ ....: G.set_edge_label(u, v, f'({u},{v})')
1215
+ sage: G.graphplot(edge_labels=True).show()
1216
+
1217
+ .. PLOT::
1218
+
1219
+ G = graphs.HeawoodGraph().copy(sparse=True)
1220
+ for u, v, l in G.edges(sort=True):
1221
+ G.set_edge_label(u, v, f'({u},{v})')
1222
+ sphinx_plot(G.graphplot(edge_labels=True))
1223
+
1224
+ The options for plotting also work with directed graphs::
1225
+
1226
+ sage: D = DiGraph({
1227
+ ....: 0: [1, 10, 19], 1: [8, 2], 2: [3, 6], 3: [19, 4],
1228
+ ....: 4: [17, 5], 5: [6, 15], 6: [7], 7: [8, 14], 8: [9],
1229
+ ....: 9: [10, 13], 10: [11], 11: [12, 18], 12: [16, 13],
1230
+ ....: 13: [14], 14: [15], 15: [16], 16: [17], 17: [18],
1231
+ ....: 18: [19], 19: []})
1232
+ sage: for u, v, l in D.edges(sort=True):
1233
+ ....: D.set_edge_label(u, v, f'({u},{v})')
1234
+ sage: D.graphplot(edge_labels=True, layout='circular').show()
1235
+
1236
+ .. PLOT::
1237
+
1238
+ D = DiGraph({
1239
+ 0: [1, 10, 19], 1: [8, 2], 2: [3, 6], 3: [19, 4],
1240
+ 4: [17, 5], 5: [6, 15], 6: [7], 7: [8, 14], 8: [9],
1241
+ 9: [10, 13], 10: [11], 11: [12, 18], 12: [16, 13],
1242
+ 13: [14], 14: [15], 15: [16], 16: [17], 17: [18],
1243
+ 18: [19], 19: []})
1244
+ for u, v, l in D.edges(sort=True):
1245
+ D.set_edge_label(u, v, f'({u},{v})')
1246
+ sphinx_plot(D.graphplot(edge_labels=True, layout='circular'))
1247
+
1248
+ For graphs with ``circular`` layouts, one may shift the vertex labels by
1249
+ specifying coordinates to shift by::
1250
+
1251
+ sage: D = DiGraph({
1252
+ ....: 0: [1, 10, 19], 1: [8, 2], 2: [3, 6], 3: [19, 4],
1253
+ ....: 4: [17, 5], 5: [6, 15], 6: [7], 7: [8, 14], 8: [9],
1254
+ ....: 9: [10, 13], 10: [11], 11: [12, 18], 12: [16, 13],
1255
+ ....: 13: [14], 14: [15], 15: [16], 16: [17], 17: [18],
1256
+ ....: 18: [19], 19: []})
1257
+ sage: for u, v, l in D.edges(sort=True):
1258
+ ....: D.set_edge_label(u, v, f'({u},{v})')
1259
+ sage: D.graphplot(edge_labels=True, layout='circular', vertex_label_shift=(15,10)).show()
1260
+
1261
+ .. PLOT::
1262
+
1263
+ D = DiGraph({
1264
+ 0: [1, 10, 19], 1: [8, 2], 2: [3, 6], 3: [19, 4],
1265
+ 4: [17, 5], 5: [6, 15], 6: [7], 7: [8, 14], 8: [9],
1266
+ 9: [10, 13], 10: [11], 11: [12, 18], 12: [16, 13],
1267
+ 13: [14], 14: [15], 15: [16], 16: [17], 17: [18],
1268
+ 18: [19], 19: []})
1269
+ for u, v, l in D.edges(sort=True):
1270
+ D.set_edge_label(u, v, f'({u},{v})')
1271
+ sphinx_plot(D.graphplot(edge_labels=True, layout='circular', vertex_label_shift=(15,10)))
1272
+
1273
+ This example shows off the coloring of edges::
1274
+
1275
+ sage: from sage.plot.colors import rainbow
1276
+ sage: C = graphs.CubeGraph(5)
1277
+ sage: R = rainbow(5)
1278
+ sage: edge_colors = {}
1279
+ sage: for i in range(5):
1280
+ ....: edge_colors[R[i]] = []
1281
+ sage: for u, v, l in C.edges(sort=True):
1282
+ ....: for i in range(5):
1283
+ ....: if u[i] != v[i]:
1284
+ ....: edge_colors[R[i]].append((u, v, l))
1285
+ sage: C.graphplot(vertex_labels=False, vertex_size=0,
1286
+ ....: edge_colors=edge_colors).show()
1287
+
1288
+ .. PLOT::
1289
+
1290
+ from sage.plot.colors import rainbow
1291
+ C = graphs.CubeGraph(5)
1292
+ R = rainbow(5)
1293
+ edge_colors = {}
1294
+ for i in range(5):
1295
+ edge_colors[R[i]] = []
1296
+ for u, v, l in C.edges(sort=True):
1297
+ for i in range(5):
1298
+ if u[i] != v[i]:
1299
+ edge_colors[R[i]].append((u, v, l))
1300
+ sphinx_plot(C.graphplot(vertex_labels=False, vertex_size=0,
1301
+ edge_colors=edge_colors))
1302
+
1303
+ With the ``partition`` option, we can separate out same-color groups
1304
+ of vertices::
1305
+
1306
+ sage: D = graphs.DodecahedralGraph()
1307
+ sage: Pi = [[6, 5, 15, 14, 7], [16, 13, 8, 2, 4],
1308
+ ....: [12, 17, 9, 3, 1], [0, 19, 18, 10, 11]]
1309
+ sage: D.show(partition=Pi)
1310
+
1311
+ .. PLOT::
1312
+
1313
+ D = graphs.DodecahedralGraph()
1314
+ Pi = [[6, 5, 15, 14, 7], [16, 13, 8, 2, 4],
1315
+ [12, 17, 9, 3, 1], [0, 19, 18, 10, 11]]
1316
+ sphinx_plot(D.plot(partition=Pi))
1317
+
1318
+ Loops are also plotted correctly::
1319
+
1320
+ sage: G = graphs.PetersenGraph()
1321
+ sage: G.allow_loops(True)
1322
+ sage: G.add_edge(0,0)
1323
+ sage: G.show()
1324
+
1325
+ .. PLOT::
1326
+
1327
+ G = graphs.PetersenGraph()
1328
+ G.allow_loops(True)
1329
+ G.add_edge(0,0)
1330
+ sphinx_plot(G)
1331
+
1332
+ ::
1333
+
1334
+ sage: D = DiGraph({0:[0,1], 1:[2], 2:[3]}, loops=True)
1335
+ sage: D.show()
1336
+ sage: D.show(edge_colors={(0, 1, 0): [(0, 1, None), (1, 2, None)],
1337
+ ....: (0, 0, 0): [(2, 3, None)]})
1338
+
1339
+ .. PLOT::
1340
+
1341
+ D = DiGraph({0:[0,1], 1:[2], 2:[3]}, loops=True)
1342
+ P = D.plot(edge_colors={(0, 1, 0): [(0, 1, None), (1, 2, None)],
1343
+ (0, 0, 0): [(2, 3, None)]})
1344
+ sphinx_plot(P)
1345
+
1346
+ More options::
1347
+
1348
+ sage: pos = {0: [0.0, 1.5], 1: [-0.8, 0.3], 2: [-0.6, -0.8],
1349
+ ....: 3:[0.6, -0.8], 4:[0.8, 0.3]}
1350
+ sage: g = Graph({0: [1], 1: [2], 2: [3], 3: [4], 4: [0]})
1351
+ sage: g.graphplot(pos=pos, layout='spring', iterations=0).plot()
1352
+ Graphics object consisting of 11 graphics primitives
1353
+
1354
+ .. PLOT::
1355
+
1356
+ pos = {0: [0.0, 1.5], 1: [-0.8, 0.3], 2: [-0.6, -0.8],
1357
+ 3: [0.6, -0.8], 4:[0.8, 0.3]}
1358
+ g = Graph({0: [1], 1: [2], 2: [3], 3: [4], 4: [0]})
1359
+ P = g.graphplot(pos=pos, layout='spring', iterations=0).plot()
1360
+ sphinx_plot(P)
1361
+
1362
+ ::
1363
+
1364
+ sage: D = graphs.CubeGraph(3)
1365
+ sage: D.graphplot(layout='planar').plot() # needs planarity
1366
+ Graphics object consisting of 21 graphics primitives
1367
+
1368
+ .. PLOT::
1369
+
1370
+ D = graphs.CubeGraph(3)
1371
+ sphinx_plot(D.graphplot(layout='planar'))
1372
+
1373
+ ::
1374
+
1375
+ sage: G = Graph()
1376
+ sage: P = G.graphplot().plot()
1377
+ sage: P.axes()
1378
+ False
1379
+ sage: G = DiGraph()
1380
+ sage: P = G.graphplot().plot()
1381
+ sage: P.axes()
1382
+ False
1383
+
1384
+ We can plot multiple graphs::
1385
+
1386
+ sage: T = list(graphs.trees(7))
1387
+ sage: t = T[3]
1388
+ sage: t.graphplot(heights={0: [0], 1: [4, 5, 1],
1389
+ ....: 2: [2], 3: [3, 6]}
1390
+ ....: ).plot()
1391
+ Graphics object consisting of 14 graphics primitives
1392
+
1393
+ .. PLOT::
1394
+
1395
+ T = list(graphs.trees(7))
1396
+ t = T[3]
1397
+ sphinx_plot(t.graphplot(heights={0: [0], 1: [4, 5, 1],
1398
+ 2: [2], 3: [3, 6]}))
1399
+
1400
+ ::
1401
+
1402
+ sage: T = list(graphs.trees(7))
1403
+ sage: t = T[3]
1404
+ sage: t.graphplot(heights={0: [0], 1: [4, 5, 1],
1405
+ ....: 2: [2], 3: [3, 6]}
1406
+ ....: ).plot()
1407
+ Graphics object consisting of 14 graphics primitives
1408
+
1409
+ .. PLOT::
1410
+
1411
+ T = list(graphs.trees(7))
1412
+ t = T[3]
1413
+ sphinx_plot(t.graphplot(heights={0: [0], 1: [4, 5, 1],
1414
+ 2: [2], 3: [3, 6]}))
1415
+
1416
+ ::
1417
+
1418
+ sage: t.set_edge_label(0, 1, -7)
1419
+ sage: t.set_edge_label(0, 5, 3)
1420
+ sage: t.set_edge_label(0, 5, 99)
1421
+ sage: t.set_edge_label(1, 2, 1000)
1422
+ sage: t.set_edge_label(3, 2, 'spam')
1423
+ sage: t.set_edge_label(2, 6, 3/2)
1424
+ sage: t.set_edge_label(0, 4, 66)
1425
+ sage: t.graphplot(heights={0: [0], 1: [4, 5, 1],
1426
+ ....: 2: [2], 3: [3, 6]},
1427
+ ....: edge_labels=True
1428
+ ....: ).plot()
1429
+ Graphics object consisting of 20 graphics primitives
1430
+
1431
+ .. PLOT::
1432
+
1433
+ T = list(graphs.trees(7))
1434
+ t = T[3]
1435
+ t.set_edge_label(0, 1, -7)
1436
+ t.set_edge_label(0, 5, 3)
1437
+ t.set_edge_label(0, 5, 99)
1438
+ t.set_edge_label(1, 2, 1000)
1439
+ t.set_edge_label(3, 2, 'spam')
1440
+ t.set_edge_label(2, 6, 3/2)
1441
+ t.set_edge_label(0, 4, 66)
1442
+ sphinx_plot(t.graphplot(heights={0: [0], 1: [4, 5, 1],
1443
+ 2: [2], 3: [3, 6]},
1444
+ edge_labels=True))
1445
+
1446
+ ::
1447
+
1448
+ sage: T = list(graphs.trees(7))
1449
+ sage: t = T[3]
1450
+ sage: t.graphplot(layout='tree').show()
1451
+
1452
+ .. PLOT::
1453
+
1454
+ T = list(graphs.trees(7))
1455
+ t = T[3]
1456
+ sphinx_plot(t.graphplot(layout='tree'))
1457
+
1458
+ The tree layout is also useful::
1459
+
1460
+ sage: t = DiGraph('JCC???@A??GO??CO??GO??')
1461
+ sage: t.graphplot(layout='tree', tree_root=0,
1462
+ ....: tree_orientation="up"
1463
+ ....: ).show()
1464
+
1465
+ .. PLOT::
1466
+
1467
+ t = DiGraph('JCC???@A??GO??CO??GO??')
1468
+ sphinx_plot(t.graphplot(layout='tree', tree_root=0,
1469
+ tree_orientation='up'))
1470
+
1471
+ More examples::
1472
+
1473
+ sage: D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]})
1474
+ sage: D.graphplot().show()
1475
+
1476
+ .. PLOT::
1477
+
1478
+ D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]})
1479
+ sphinx_plot(D.graphplot())
1480
+
1481
+ ::
1482
+
1483
+ sage: D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]})
1484
+ sage: D.graphplot(label_fontsize=20, arrowsize=10).show()
1485
+
1486
+ .. PLOT::
1487
+
1488
+ D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]})
1489
+ sphinx_plot(D.graphplot(label_fontsize=20, arrowsize=10))
1490
+
1491
+
1492
+ ::
1493
+
1494
+ sage: D = DiGraph(multiedges=True, sparse=True)
1495
+ sage: for i in range(5):
1496
+ ....: D.add_edge((i, i + 1, 'a'))
1497
+ ....: D.add_edge((i, i - 1, 'b'))
1498
+ sage: D.graphplot(edge_labels=True,
1499
+ ....: edge_colors=D._color_by_label()
1500
+ ....: ).plot()
1501
+ Graphics object consisting of 34 graphics primitives
1502
+
1503
+ .. PLOT::
1504
+
1505
+ D = DiGraph(multiedges=True, sparse=True)
1506
+ for i in range(5):
1507
+ D.add_edge((i, i + 1, 'a'))
1508
+ D.add_edge((i, i - 1, 'b'))
1509
+ sphinx_plot(D.graphplot(edge_labels=True,
1510
+ edge_colors=D._color_by_label()))
1511
+
1512
+ ::
1513
+
1514
+ sage: g = Graph({}, loops=True, multiedges=True, sparse=True)
1515
+ sage: g.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
1516
+ ....: (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
1517
+ ....: (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
1518
+ sage: g.graphplot(edge_labels=True,
1519
+ ....: color_by_label=True,
1520
+ ....: edge_style='dashed'
1521
+ ....: ).plot()
1522
+ Graphics object consisting of 22 graphics primitives
1523
+
1524
+ .. PLOT::
1525
+
1526
+ g = Graph({}, loops=True, multiedges=True, sparse=True)
1527
+ g.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
1528
+ (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
1529
+ (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
1530
+ sphinx_plot(g.graphplot(edge_labels=True,
1531
+ color_by_label=True,
1532
+ edge_style='dashed'))
1533
+
1534
+ The ``edge_style`` option may be provided in the short format too::
1535
+
1536
+
1537
+ sage: g.graphplot(edge_labels=True,
1538
+ ....: color_by_label=True,
1539
+ ....: edge_style='--'
1540
+ ....: ).plot()
1541
+ Graphics object consisting of 22 graphics primitives
1542
+
1543
+ The ``edge_styles`` option may be provided if you need only certain edges
1544
+ to have certain styles::
1545
+
1546
+ sage: g = Graph(loops=True, multiedges=True, sparse=True)
1547
+ sage: g.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
1548
+ ....: (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
1549
+ ....: (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
1550
+ sage: GP = g.graphplot(vertex_size=100, edge_labels=True,
1551
+ ....: color_by_label=True, edge_style='dashed')
1552
+ sage: GP.set_edges(edge_styles={'a':'dashed', 'g':'dotted'})
1553
+ sage: GP.plot()
1554
+ Graphics object consisting of 22 graphics primitives
1555
+
1556
+ .. PLOT::
1557
+
1558
+ g = Graph(loops=True, multiedges=True, sparse=True)
1559
+ g.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
1560
+ (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
1561
+ (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
1562
+ GP = g.graphplot(vertex_size=100, edge_labels=True,
1563
+ color_by_label=True, edge_style='dashed')
1564
+ GP.set_edges(edge_style='solid')
1565
+ GP.set_edges(edge_color='black')
1566
+ GP.set_edges(edge_styles={'a':'dashed', 'g':'dotted'})
1567
+ sphinx_plot(GP)
1568
+
1569
+ ::
1570
+
1571
+ sage: g = Graph(loops=True, multiedges=True, sparse=True)
1572
+ sage: g.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
1573
+ ....: (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
1574
+ ....: (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
1575
+ sage: GP = g.graphplot(vertex_size=100, edge_labels=True,
1576
+ ....: color_by_label=True, edge_thickness=3)
1577
+ sage: GP.set_edges(edge_thicknesses={'a':1, 'g':5})
1578
+ sage: GP.plot()
1579
+ Graphics object consisting of 22 graphics primitives
1580
+
1581
+ .. PLOT::
1582
+
1583
+ g = Graph(loops=True, multiedges=True, sparse=True)
1584
+ g.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
1585
+ (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
1586
+ (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
1587
+ GP = g.graphplot(vertex_size=100, edge_labels=True,
1588
+ color_by_label=True, edge_thickness=3)
1589
+ GP.set_edges(edge_style='solid')
1590
+ GP.set_edges(edge_color='black')
1591
+ GP.set_edges(edge_thicknesses={'a':1, 'g':5})
1592
+ sphinx_plot(GP)
1593
+
1594
+ TESTS:
1595
+
1596
+ Make sure that show options work with plot also::
1597
+
1598
+ sage: g = Graph({})
1599
+ sage: g.plot(title='empty graph', axes=True)
1600
+ Graphics object consisting of 0 graphics primitives
1601
+
1602
+ Check for invalid inputs::
1603
+
1604
+ sage: p = graphs.PetersenGraph().plot(egabrag='garbage')
1605
+ Traceback (most recent call last):
1606
+ ...
1607
+ ValueError: invalid input 'egabrag=garbage'
1608
+
1609
+ Make sure that no graphics primitive is clipped::
1610
+
1611
+ sage: tadpole = Graph({0: [0, 1]}).plot()
1612
+ sage: bbox = tadpole.get_minmax_data()
1613
+ sage: for part in tadpole:
1614
+ ....: part_bbox = part.get_minmax_data()
1615
+ ....: assert (bbox['xmin'] <= part_bbox['xmin']
1616
+ ....: <= part_bbox['xmax'] <= bbox['xmax'])
1617
+ ....: assert (bbox['ymin'] <= part_bbox['ymin']
1618
+ ....: <= part_bbox['ymax'] <= bbox['ymax'])
1619
+
1620
+ Check that one can plot immutable graphs (:issue:`17340`)::
1621
+
1622
+ sage: Graph({0: [0]}, immutable=True).plot()
1623
+ Graphics object consisting of 3 graphics primitives
1624
+ """
1625
+ G = Graphics()
1626
+ options = self._options.copy()
1627
+ options.update(kwds)
1628
+ G._set_extra_kwds(Graphics._extract_kwds_for_show(options))
1629
+
1630
+ # Check the arguments
1631
+ for o in options:
1632
+ if o not in graphplot_options and o not in G._extra_kwds:
1633
+ raise ValueError("invalid input '{}={}'".format(o, options[o]))
1634
+
1635
+ for comp in self._plot_components.values():
1636
+ if not isinstance(comp, list):
1637
+ G += comp
1638
+ else:
1639
+ for item in comp:
1640
+ G += item
1641
+
1642
+ if self._options['graph_border']:
1643
+ xmin = G.xmin()
1644
+ xmax = G.xmax()
1645
+ ymin = G.ymin()
1646
+ ymax = G.ymax()
1647
+ dx = (xmax - xmin) / 10.0
1648
+ dy = (ymax - ymin) / 10.0
1649
+ border = (line([(xmin - dx, ymin - dy), (xmin - dx, ymax + dy),
1650
+ (xmax + dx, ymax + dy), (xmax + dx, ymin - dy),
1651
+ (xmin - dx, ymin - dy)], thickness=1.3))
1652
+ border.axes_range(xmin=(xmin - dx), xmax=(xmax + dx),
1653
+ ymin=(ymin - dy), ymax=(ymax + dy))
1654
+ G += border
1655
+ G.set_aspect_ratio(1)
1656
+ G.axes(False)
1657
+ return G
1658
+
1659
+ def layout_tree(self, root, orientation):
1660
+ """
1661
+ Compute a nice layout of a tree.
1662
+
1663
+ INPUT:
1664
+
1665
+ - ``root`` -- the root vertex
1666
+
1667
+ - ``orientation`` -- whether to place the root at the top or at the
1668
+ bottom:
1669
+
1670
+ * ``orientation="down"`` -- children are placed below their parent
1671
+ * ``orientation="top"`` -- children are placed above their parent
1672
+
1673
+ EXAMPLES::
1674
+
1675
+ sage: from sage.graphs.graph_plot import GraphPlot
1676
+ sage: G = graphs.HoffmanSingletonGraph()
1677
+ sage: T = Graph()
1678
+ sage: T.add_edges(G.min_spanning_tree(starting_vertex=0))
1679
+ sage: T.show(layout='tree', tree_root=0) # indirect doctest
1680
+ """
1681
+ T = self._graph
1682
+
1683
+ if not self._graph.is_tree():
1684
+ raise RuntimeError("cannot use tree layout on this graph: "
1685
+ "self.is_tree() returns False")
1686
+
1687
+ children = {root: T.neighbors(root)}
1688
+
1689
+ # Always make a copy of the children because they get eaten
1690
+ stack = [list(children[root])]
1691
+ stick = [root]
1692
+ parent = {u: root for u in children[root]}
1693
+ pos = {}
1694
+ obstruction = [0.0] * T.num_verts()
1695
+ if orientation == 'down':
1696
+ o = -1
1697
+ else:
1698
+ o = 1
1699
+
1700
+ def slide(v, dx):
1701
+ """
1702
+ Shift the vertex v and its descendants to the right by dx.
1703
+
1704
+ Precondition: v and its descendents have already had their
1705
+ positions computed.
1706
+ """
1707
+ level = [v]
1708
+ while level:
1709
+ nextlevel = []
1710
+ for u in level:
1711
+ x, y = pos[u]
1712
+ x += dx
1713
+ obstruction[y] = max(x + 1, obstruction[y])
1714
+ pos[u] = x, y
1715
+ nextlevel += children[u]
1716
+ level = nextlevel
1717
+
1718
+ while stack:
1719
+ C = stack[-1]
1720
+ if not C:
1721
+ p = stick.pop()
1722
+ stack.pop()
1723
+ cp = children[p]
1724
+ y = o * len(stack)
1725
+ if not cp:
1726
+ x = obstruction[y]
1727
+ pos[p] = x, y
1728
+ else:
1729
+ x = sum([pos[c][0] for c in cp]) / float(len(cp))
1730
+ pos[p] = x, y
1731
+ ox = obstruction[y]
1732
+ if x < ox:
1733
+ slide(p, ox - x)
1734
+ x = ox
1735
+ obstruction[y] = x + 1
1736
+ continue
1737
+
1738
+ t = C.pop()
1739
+ pt = parent[t]
1740
+
1741
+ ct = [u for u in T.neighbors(t) if u != pt]
1742
+ for c in ct:
1743
+ parent[c] = t
1744
+ children[t] = ct
1745
+
1746
+ stack.append(ct)
1747
+ stick.append(t)
1748
+
1749
+ return pos