本文整理汇总了Python中sage.graphs.graph.Graph.add_vertices方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.add_vertices方法的具体用法?Python Graph.add_vertices怎么用?Python Graph.add_vertices使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sage.graphs.graph.Graph
的用法示例。
在下文中一共展示了Graph.add_vertices方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: to_bipartite_graph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def to_bipartite_graph(self, with_partition=False):
r"""
Returns the associated bipartite graph
INPUT:
- with_partition -- boolean (default: False)
OUTPUT:
- a graph or a pair (graph, partition)
EXAMPLES::
sage: H = designs.steiner_triple_system(7).blocks()
sage: H = Hypergraph(H)
sage: g = H.to_bipartite_graph(); g
Graph on 14 vertices
sage: g.is_regular()
True
"""
from sage.graphs.graph import Graph
G = Graph()
domain = list(self.domain())
G.add_vertices(domain)
for s in self._sets:
for i in s:
G.add_edge(s, i)
if with_partition:
return (G, [domain, list(self._sets)])
else:
return G
示例2: coxeter_diagram
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def coxeter_diagram(self):
"""
Return the Coxeter diagram for ``self``.
EXAMPLES::
sage: cd = CartanType("A2xB2xF4").coxeter_diagram()
sage: cd
Graph on 8 vertices
sage: cd.edges()
[(1, 2, 3), (3, 4, 4), (5, 6, 3), (6, 7, 4), (7, 8, 3)]
sage: CartanType("F4xA2").coxeter_diagram().edges()
[(1, 2, 3), (2, 3, 4), (3, 4, 3), (5, 6, 3)]
sage: cd = CartanType("A1xH3").coxeter_diagram(); cd
Graph on 4 vertices
sage: cd.edges()
[(2, 3, 3), (3, 4, 5)]
"""
from sage.graphs.graph import Graph
relabelling = self._index_relabelling
g = Graph(multiedges=False)
g.add_vertices(self.index_set())
for i,t in enumerate(self._types):
for [e1, e2, l] in t.coxeter_diagram().edges():
g.add_edge(relabelling[i,e1], relabelling[i,e2], label=l)
return g
示例3: coxeter_graph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def coxeter_graph(self):
"""
Return the Coxeter graph of ``self``.
EXAMPLES::
sage: W = CoxeterGroup(['H',3], implementation="reflection")
sage: G = W.coxeter_graph(); G
Graph on 3 vertices
sage: G.edges()
[(1, 2, None), (2, 3, 5)]
sage: CoxeterGroup(G) is W
True
sage: G = Graph([(0, 1, 3), (1, 2, oo)])
sage: W = CoxeterGroup(G)
sage: W.coxeter_graph() == G
True
sage: CoxeterGroup(W.coxeter_graph()) is W
True
"""
G = Graph()
G.add_vertices(self.index_set())
for i, row in enumerate(self._matrix.rows()):
for j, val in enumerate(row[i + 1 :]):
if val == 3:
G.add_edge(self._index_set[i], self._index_set[i + 1 + j])
elif val > 3:
G.add_edge(self._index_set[i], self._index_set[i + 1 + j], val)
elif val == -1: # FIXME: Hack because there is no ZZ\cup\{\infty\}
G.add_edge(self._index_set[i], self._index_set[i + 1 + j], infinity)
return G
示例4: coxeter_graph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def coxeter_graph(self):
"""
Return the Coxeter graph of ``self``.
EXAMPLES::
sage: C = CoxeterMatrix(['A',3])
sage: C.coxeter_graph()
Graph on 3 vertices
sage: C = CoxeterMatrix([['A',3],['A',1]])
sage: C.coxeter_graph()
Graph on 4 vertices
"""
n = self.rank()
I = self.index_set()
val = lambda x: infinity if x == -1 else x
G = Graph(
[
(I[i], I[j], val((self._matrix)[i, j]))
for i in range(n)
for j in range(i)
if self._matrix[i, j] not in [1, 2]
]
)
G.add_vertices(I)
return G.copy(immutable=True)
示例5: CircularLadderGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def CircularLadderGraph(n):
"""
Returns a circular ladder graph with 2\*n nodes.
A Circular ladder graph is a ladder graph that is connected at the
ends, i.e.: a ladder bent around so that top meets bottom. Thus it
can be described as two parallel cycle graphs connected at each
corresponding node pair.
This constructor depends on NetworkX numeric labels.
PLOTTING: Upon construction, the position dictionary is filled to
override the spring-layout algorithm. By convention, the circular
ladder graph is displayed as an inner and outer cycle pair, with
the first n nodes drawn on the inner circle. The first (0) node is
drawn at the top of the inner-circle, moving clockwise after that.
The outer circle is drawn with the (n+1)th node at the top, then
counterclockwise as well.
EXAMPLES: Construct and show a circular ladder graph with 26 nodes
::
sage: g = graphs.CircularLadderGraph(13)
sage: g.show() # long time
Create several circular ladder graphs in a Sage graphics array
::
sage: g = []
sage: j = []
sage: for i in range(9):
....: k = graphs.CircularLadderGraph(i+3)
....: g.append(k)
sage: for i in range(3):
....: n = []
....: for m in range(3):
....: n.append(g[3*i + m].plot(vertex_size=50, vertex_labels=False))
....: j.append(n)
sage: G = sage.plot.graphics.GraphicsArray(j)
sage: G.show() # long time
"""
pos_dict = {}
for i in range(n):
x = float(cos((pi/2) + ((2*pi)/n)*i))
y = float(sin((pi/2) + ((2*pi)/n)*i))
pos_dict[i] = [x,y]
for i in range(n,2*n):
x = float(2*(cos((pi/2) + ((2*pi)/n)*(i-n))))
y = float(2*(sin((pi/2) + ((2*pi)/n)*(i-n))))
pos_dict[i] = (x,y)
G = Graph(pos=pos_dict, name="Circular Ladder graph")
G.add_vertices( range(2*n) )
G.add_cycle( range(n) )
G.add_cycle( range(n,2*n) )
G.add_edges( (i,i+n) for i in range(n) )
return G
示例6: create_graph_from_model
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def create_graph_from_model(self, solver, model):
"""
Given a model from the SAT solver, construct the graph.
"""
g = Graph()
on_vertices = solver.get_objects_in_model(model, self, self.internal_graph.vertices())
on_edges = solver.get_objects_in_model(model, self, self.internal_graph.edges(labels=False))
g.add_vertices(on_vertices)
g.add_edges(on_edges)
return g
示例7: LadderGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def LadderGraph(n):
"""
Returns a ladder graph with 2\*n nodes.
A ladder graph is a basic structure that is typically displayed as
a ladder, i.e.: two parallel path graphs connected at each
corresponding node pair.
This constructor depends on NetworkX numeric labels.
PLOTTING: Upon construction, the position dictionary is filled to
override the spring-layout algorithm. By convention, each ladder
graph will be displayed horizontally, with the first n nodes
displayed left to right on the top horizontal line.
EXAMPLES: Construct and show a ladder graph with 14 nodes
::
sage: g = graphs.LadderGraph(7)
sage: g.show() # long time
Create several ladder graphs in a Sage graphics array
::
sage: g = []
sage: j = []
sage: for i in range(9):
....: k = graphs.LadderGraph(i+2)
....: g.append(k)
sage: for i in range(3):
....: n = []
....: for m in range(3):
....: n.append(g[3*i + m].plot(vertex_size=50, vertex_labels=False))
....: j.append(n)
sage: G = sage.plot.graphics.GraphicsArray(j)
sage: G.show() # long time
"""
pos_dict = {}
for i in range(n):
pos_dict[i] = (i,1)
for i in range(n,2*n):
x = i - n
pos_dict[i] = (x,0)
G = Graph(pos=pos_dict, name="Ladder graph")
G.add_vertices( range(2*n) )
G.add_path( range(n) )
G.add_path( range(n,2*n) )
G.add_edges( (i,i+n) for i in range(n) )
return G
示例8: IntersectionGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def IntersectionGraph(S):
r"""
Returns the intersection graph of the family `S`
The intersection graph of a family `S` is a graph `G` with `V(G)=S` such
that two elements `s_1,s_2\in S` are adjacent in `G` if and only if `s_1\cap
s_2\neq \emptyset`.
INPUT:
- ``S`` -- a list of sets/tuples/iterables
.. NOTE::
The elements of `S` must be finite, hashable, and the elements of
any `s\in S` must be hashable too.
EXAMPLE::
sage: graphs.IntersectionGraph([(1,2,3),(3,4,5),(5,6,7)])
Intersection Graph: Graph on 3 vertices
TESTS::
sage: graphs.IntersectionGraph([(1,2,[1])])
Traceback (most recent call last):
...
TypeError: The elements of S must be hashable, and this one is not: (1, 2, [1])
"""
from itertools import combinations
for s in S:
try:
hash(s)
except TypeError:
raise TypeError("The elements of S must be hashable, and this one is not: {}".format(s))
ground_set_to_sets = {}
for s in S:
for x in s:
if x not in ground_set_to_sets:
ground_set_to_sets[x] = []
ground_set_to_sets[x].append(s)
g = Graph(name="Intersection Graph")
g.add_vertices(S)
for clique in ground_set_to_sets.itervalues():
g.add_edges((u,v) for u,v in combinations(clique,2))
return g
示例9: connection_graph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def connection_graph(self):
"""
Return the graph which has the variables of this system as
vertices and edges between two variables if they appear in the
same polynomial.
EXAMPLE::
sage: B.<x,y,z> = BooleanPolynomialRing()
sage: F = Sequence([x*y + y + 1, z + 1])
sage: F.connection_graph()
Graph on 3 vertices
"""
V = sorted(self.variables())
from sage.graphs.graph import Graph
g = Graph()
g.add_vertices(sorted(V))
for f in self:
v = f.variables()
a,tail = v[0],v[1:]
for b in tail:
g.add_edge((a,b))
return g
示例10: apply
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def apply(solver, model, structures):
g = structures[0]
vertices = solver.get_objects_in_model(model, g, g.internal_graph.vertices())
dims = int(math.log(g.order, 2))
#print(vertices)
#print(dims)
edges = solver.get_objects_in_model(model, g, g.internal_graph.edges(labels=False))
#print(edges)
#create temp graph
t = Graph()
t.add_vertices(vertices)
t.add_edges(edges)
for i in range(g.order/2):
antipod = g.order - 1 - i
#print(i, antipod)
if i in vertices and antipod in vertices:
path = t.shortest_path(i, antipod)
if path:
#print(path)
return (True, [g, path])
print("COUNTER")
return (False, [])
示例11: RandomTree
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def RandomTree(n):
"""
Returns a random tree on `n` nodes numbered `0` through `n-1`.
By Cayley's theorem, there are `n^{n-2}` trees with vertex
set `\{0,1,...,n-1\}`. This constructor chooses one of these uniformly
at random.
ALGORITHM:
The algoritm works by generating an `(n-2)`-long
random sequence of numbers chosen independently and uniformly
from `\{0,1,\ldots,n-1\}` and then applies an inverse
Prufer transformation.
INPUT:
- ``n`` - number of vertices in the tree
EXAMPLE::
sage: G = graphs.RandomTree(10)
sage: G.is_tree()
True
sage: G.show() # long
TESTS:
Ensuring that we encounter no unexpected surprise ::
sage: all( graphs.RandomTree(10).is_tree()
....: for i in range(100) )
True
"""
from sage.misc.prandom import randint
g = Graph()
# create random Prufer code
code = [ randint(0,n-1) for i in xrange(n-2) ]
# We count the number of symbols of each type.
# count[k] is the no. of times k appears in code
#
# (count[k] is set to -1 when the corresponding vertex is not
# available anymore)
count = [ 0 for i in xrange(n) ]
for k in code:
count[k] += 1
g.add_vertices(range(n))
for s in code:
for x in range(n):
if count[x] == 0:
break
count[x] = -1
g.add_edge(x,s)
count[s] -= 1
# Adding as an edge the last two available vertices
last_edge = [ v for v in range(n) if count[v] != -1 ]
g.add_edge(last_edge)
return g
示例12: recognize_coxeter_type_from_matrix
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
#.........这里部分代码省略.........
sage: M.coxeter_type()
Coxeter type of ['G', 2, 1] relabelled by {0: 'a', 1: 'b', 2: 'c'}
sage: from sage.combinat.root_system.coxeter_matrix import recognize_coxeter_type_from_matrix
sage: for C in CoxeterMatrix.samples():
....: relabelling_perm = Permutations(C.index_set()).random_element()
....: relabelling_dict = {C.index_set()[i]: relabelling_perm[i] for i in range(C.rank())}
....: relabeled_matrix = C.relabel(relabelling_dict)._matrix
....: recognized_type = recognize_coxeter_type_from_matrix(relabeled_matrix, relabelling_perm)
....: if C.is_finite() or C.is_affine():
....: assert recognized_type == C.coxeter_type()
We check the rank 2 cases (:trac:`20419`)::
sage: for i in range(2, 10):
....: M = matrix([[1,i],[i,1]])
....: CoxeterMatrix(M).coxeter_type()
Coxeter type of A1xA1 relabelled by {1: 2}
Coxeter type of ['A', 2]
Coxeter type of ['B', 2]
Coxeter type of ['I', 5]
Coxeter type of ['G', 2]
Coxeter type of ['I', 7]
Coxeter type of ['I', 8]
Coxeter type of ['I', 9]
sage: CoxeterMatrix(matrix([[1,-1],[-1,1]]), index_set=[0,1]).coxeter_type()
Coxeter type of ['A', 1, 1]
"""
# First, we build the Coxeter graph of the group without the edge labels
n = ZZ(coxeter_matrix.nrows())
G = Graph(
[
[index_set[i], index_set[j], coxeter_matrix[i, j]]
for i in range(n)
for j in range(i, n)
if coxeter_matrix[i, j] not in [1, 2]
]
)
G.add_vertices(index_set)
types = []
for S in G.connected_components_subgraphs():
r = S.num_verts()
# Handle the special cases first
if r == 1:
types.append(CoxeterType(["A", 1]).relabel({1: S.vertices()[0]}))
continue
if r == 2: # Type B2, G2, or I_2(p)
e = S.edge_labels()[0]
if e == 3: # Can't be 2 because it is connected
ct = CoxeterType(["A", 2])
elif e == 4:
ct = CoxeterType(["B", 2])
elif e == 6:
ct = CoxeterType(["G", 2])
elif e > 0 and e < float("inf"): # Remaining non-affine types
ct = CoxeterType(["I", e])
else: # Otherwise it is infinite dihedral group Z_2 \ast Z_2
ct = CoxeterType(["A", 1, 1])
if not ct.is_affine():
types.append(ct.relabel({1: S.vertices()[0], 2: S.vertices()[1]}))
else:
types.append(ct.relabel({0: S.vertices()[0], 1: S.vertices()[1]}))
continue
test = [["A", r], ["B", r], ["A", r - 1, 1]]
if r >= 3:
if r == 3:
test += [["G", 2, 1], ["H", 3]]
test.append(["C", r - 1, 1])
if r >= 4:
if r == 4:
test += [["F", 4], ["H", 4]]
test += [["D", r], ["B", r - 1, 1]]
if r >= 5:
if r == 5:
test.append(["F", 4, 1])
test.append(["D", r - 1, 1])
if r == 6:
test.append(["E", 6])
elif r == 7:
test += [["E", 7], ["E", 6, 1]]
elif r == 8:
test += [["E", 8], ["E", 7, 1]]
elif r == 9:
test.append(["E", 8, 1])
found = False
for ct in test:
ct = CoxeterType(ct)
T = ct.coxeter_graph()
iso, match = T.is_isomorphic(S, certify=True, edge_labels=True)
if iso:
types.append(ct.relabel(match))
found = True
break
if not found:
return None
return CoxeterType(types)
示例13: AffineOrthogonalPolarGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def AffineOrthogonalPolarGraph(d,q,sign="+"):
r"""
Returns the affine polar graph `VO^+(d,q),VO^-(d,q)` or `VO(d,q)`.
Affine Polar graphs are built from a `d`-dimensional vector space over
`F_q`, and a quadratic form which is hyperbolic, elliptic or parabolic
according to the value of ``sign``.
Note that `VO^+(d,q),VO^-(d,q)` are strongly regular graphs, while `VO(d,q)`
is not.
For more information on Affine Polar graphs, see `Affine Polar
Graphs page of Andries Brouwer's website
<http://www.win.tue.nl/~aeb/graphs/VO.html>`_.
INPUT:
- ``d`` (integer) -- ``d`` must be even if ``sign != None``, and odd
otherwise.
- ``q`` (integer) -- a power of a prime number, as `F_q` must exist.
- ``sign`` -- must be equal to ``"+"``, ``"-"``, or ``None`` to compute
(respectively) `VO^+(d,q),VO^-(d,q)` or `VO(d,q)`. By default
``sign="+"``.
.. NOTE::
The graph `VO^\epsilon(d,q)` is the graph induced by the
non-neighbors of a vertex in an :meth:`Orthogonal Polar Graph
<OrthogonalPolarGraph>` `O^\epsilon(d+2,q)`.
EXAMPLES:
The :meth:`Brouwer-Haemers graph <BrouwerHaemersGraph>` is isomorphic to
`VO^-(4,3)`::
sage: g = graphs.AffineOrthogonalPolarGraph(4,3,"-")
sage: g.is_isomorphic(graphs.BrouwerHaemersGraph())
True
Some examples from `Brouwer's table or strongly regular graphs
<http://www.win.tue.nl/~aeb/graphs/srg/srgtab.html>`_::
sage: g = graphs.AffineOrthogonalPolarGraph(6,2,"-"); g
Affine Polar Graph VO^-(6,2): Graph on 64 vertices
sage: g.is_strongly_regular(parameters=True)
(64, 27, 10, 12)
sage: g = graphs.AffineOrthogonalPolarGraph(6,2,"+"); g
Affine Polar Graph VO^+(6,2): Graph on 64 vertices
sage: g.is_strongly_regular(parameters=True)
(64, 35, 18, 20)
When ``sign is None``::
sage: g = graphs.AffineOrthogonalPolarGraph(5,2,None); g
Affine Polar Graph VO^-(5,2): Graph on 32 vertices
sage: g.is_strongly_regular(parameters=True)
False
sage: g.is_regular()
True
sage: g.is_vertex_transitive()
True
"""
if sign in ["+","-"]:
s = 1 if sign == "+" else -1
if d%2 == 1:
raise ValueError("d must be even when sign!=None")
else:
if d%2 == 0:
raise ValueError("d must be odd when sign==None")
s = 0
from sage.interfaces.gap import gap
from sage.modules.free_module import VectorSpace
from sage.matrix.constructor import Matrix
from sage.libs.gap.libgap import libgap
from itertools import combinations
M = Matrix(libgap.InvariantQuadraticForm(libgap.GeneralOrthogonalGroup(s,d,q))['matrix'])
F = libgap.GF(q).sage()
V = list(VectorSpace(F,d))
G = Graph()
G.add_vertices([tuple(_) for _ in V])
for x,y in combinations(V,2):
if not (x-y)*M*(x-y):
G.add_edge(tuple(x),tuple(y))
G.name("Affine Polar Graph VO^"+str('+' if s == 1 else '-')+"("+str(d)+","+str(q)+")")
G.relabel()
return G
示例14: RandomBipartite
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
def RandomBipartite(n1,n2, p):
r"""
Returns a bipartite graph with `n1+n2` vertices
such that any edge from `[n1]` to `[n2]` exists
with probability `p`.
INPUT:
- ``n1,n2`` : Cardinalities of the two sets
- ``p`` : Probability for an edge to exist
EXAMPLE::
sage: g=graphs.RandomBipartite(5,2,0.5)
sage: g.vertices()
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1)]
TESTS::
sage: g=graphs.RandomBipartite(5,-3,0.5)
Traceback (most recent call last):
...
ValueError: n1 and n2 should be integers strictly greater than 0
sage: g=graphs.RandomBipartite(5,3,1.5)
Traceback (most recent call last):
...
ValueError: Parameter p is a probability, and so should be a real value between 0 and 1
Trac ticket #12155::
sage: graphs.RandomBipartite(5,6,.2).complement()
complement(Random bipartite graph of size 5+6 with edge probability 0.200000000000000): Graph on 11 vertices
"""
if not (p>=0 and p<=1):
raise ValueError, "Parameter p is a probability, and so should be a real value between 0 and 1"
if not (n1>0 and n2>0):
raise ValueError, "n1 and n2 should be integers strictly greater than 0"
from numpy.random import uniform
g=Graph(name="Random bipartite graph of size "+str(n1) +"+"+str(n2)+" with edge probability "+str(p))
S1=[(0,i) for i in range(n1)]
S2=[(1,i) for i in range(n2)]
g.add_vertices(S1)
g.add_vertices(S2)
for w in range(n2):
for v in range(n1):
if uniform()<=p :
g.add_edge((0,v),(1,w))
pos = {}
for i in range(n1):
pos[(0,i)] = (0, i/(n1-1.0))
for i in range(n2):
pos[(1,i)] = (1, i/(n2-1.0))
g.set_pos(pos)
return g
示例15: PermutationGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_vertices [as 别名]
#.........这里部分代码省略.........
.. SEEALSO:
- Recognition of Permutation graphs in the :mod:`comparability module
<sage.graphs.comparability>`.
- Drawings of permutation graphs as intersection graphs of segments is
possible through the
:meth:`~sage.combinat.permutation.Permutation.show` method of
:class:`~sage.combinat.permutation.Permutation` objects.
The correct argument to use in this case is ``show(representation =
"braid")``.
- :meth:`~sage.combinat.permutation.Permutation.inversions`
EXAMPLES::
sage: p = Permutations(5).random_element()
sage: PG = graphs.PermutationGraph(p)
sage: edges = PG.edges(labels=False)
sage: set(edges) == set(p.inverse().inversions())
True
sage: PG = graphs.PermutationGraph([3,4,5,1,2])
sage: sorted(PG.edges())
[(1, 3, None),
(1, 4, None),
(1, 5, None),
(2, 3, None),
(2, 4, None),
(2, 5, None)]
sage: PG = graphs.PermutationGraph([3,4,5,1,2], [1,4,2,5,3])
sage: sorted(PG.edges())
[(1, 3, None),
(1, 4, None),
(1, 5, None),
(2, 3, None),
(2, 5, None),
(3, 4, None),
(3, 5, None)]
sage: PG = graphs.PermutationGraph([1,4,2,5,3], [3,4,5,1,2])
sage: sorted(PG.edges())
[(1, 3, None),
(1, 4, None),
(1, 5, None),
(2, 3, None),
(2, 5, None),
(3, 4, None),
(3, 5, None)]
sage: PG = graphs.PermutationGraph(Permutation([1,3,2]), Permutation([1,2,3]))
sage: sorted(PG.edges())
[(2, 3, None)]
sage: graphs.PermutationGraph([]).edges()
[]
sage: graphs.PermutationGraph([], []).edges()
[]
sage: PG = graphs.PermutationGraph("graph", "phrag")
sage: sorted(PG.edges())
[('a', 'g', None),
('a', 'h', None),
('a', 'p', None),
('g', 'h', None),
('g', 'p', None),
('g', 'r', None),
('h', 'r', None),
('p', 'r', None)]
TESTS::
sage: graphs.PermutationGraph([1, 2, 3], [4, 5, 6])
Traceback (most recent call last):
...
ValueError: The two permutations do not contain the same set of elements ...
"""
if first_permutation is None:
first_permutation = sorted(second_permutation)
else:
if set(second_permutation) != set(first_permutation):
raise ValueError("The two permutations do not contain the same "+
"set of elements ! It is going to be pretty "+
"hard to define a permutation graph from that !")
vertex_to_index = {}
for i, v in enumerate(first_permutation):
vertex_to_index[v] = i+1
from sage.combinat.permutation import Permutation
p2 = Permutation([vertex_to_index[x] for x in second_permutation])
p2 = p2.inverse()
g = Graph(name="Permutation graph for "+str(second_permutation))
g.add_vertices(second_permutation)
for u,v in p2.inversions():
g.add_edge(first_permutation[u-1], first_permutation[v-1])
return g