本文整理汇总了Python中sage.graphs.digraph.DiGraph.add_edge方法的典型用法代码示例。如果您正苦于以下问题:Python DiGraph.add_edge方法的具体用法?Python DiGraph.add_edge怎么用?Python DiGraph.add_edge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sage.graphs.digraph.DiGraph
的用法示例。
在下文中一共展示了DiGraph.add_edge方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Circuit
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def Circuit(self,n):
r"""
Returns the circuit on `n` vertices
The circuit is an oriented ``CycleGraph``
EXAMPLE:
A circuit is the smallest strongly connected digraph::
sage: circuit = digraphs.Circuit(15)
sage: len(circuit.strongly_connected_components()) == 1
True
"""
g = DiGraph(n)
g.name("Circuit")
if n==0:
return g
elif n == 1:
g.allow_loops(True)
g.add_edge(0,0)
return g
else:
g.add_edges([(i,i+1) for i in xrange(n-1)])
g.add_edge(n-1,0)
return g
示例2: Circuit
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def Circuit(self,n):
r"""
Returns the circuit on `n` vertices
The circuit is an oriented ``CycleGraph``
EXAMPLE:
A circuit is the smallest strongly connected digraph::
sage: circuit = digraphs.Circuit(15)
sage: len(circuit.strongly_connected_components()) == 1
True
"""
if n<0:
raise ValueError("The number of vertices must be a positive integer.")
g = DiGraph()
g.name("Circuit on "+str(n)+" vertices")
if n==0:
return g
elif n == 1:
g.allow_loops(True)
g.add_edge(0,0)
return g
else:
g.add_edges([(i,i+1) for i in xrange(n-1)])
g.add_edge(n-1,0)
return g
示例3: RandomDirectedGNP
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def RandomDirectedGNP(self, n, p):
r"""
Returns a random digraph on `n` nodes. Each edge is
inserted independently with probability `p`.
REFERENCES:
- [1] P. Erdos and A. Renyi, On Random Graphs, Publ. Math. 6,
290 (1959).
- [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30,
1141 (1959).
PLOTTING: When plotting, this graph will use the default
spring-layout algorithm, unless a position dictionary is
specified.
EXAMPLE::
sage: D = digraphs.RandomDirectedGNP(10, .2)
sage: D.num_verts()
10
sage: D.edges(labels=False)
[(0, 1), (0, 3), (0, 6), (0, 8), (1, 4), (3, 7), (4, 1), (4, 8), (5, 2), (5, 6), (5, 8), (6, 4), (7, 6), (8, 4), (8, 5), (8, 7), (8, 9), (9, 3), (9, 4), (9, 6)]
"""
from sage.misc.prandom import random
D = DiGraph(n)
for i in xrange(n):
for j in xrange(i):
if random() < p:
D.add_edge(i,j)
for j in xrange(i+1,n):
if random() < p:
D.add_edge(i,j)
return D
示例4: inclusion_digraph
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def inclusion_digraph(self):
r"""
Returns the class inclusion digraph
Upon the first call, this loads the database from the local
XML file. Subsequent calls are cached.
EXAMPLES::
sage: g = graph_classes.inclusion_digraph(); g
Digraph on ... vertices
"""
classes = self.classes()
inclusions = self.inclusions()
from sage.graphs.digraph import DiGraph
inclusion_digraph = DiGraph()
inclusion_digraph.add_vertices(classes.keys())
for edge in inclusions:
if edge.get("confidence","") == "unpublished":
continue
inclusion_digraph.add_edge(edge['super'], edge['sub'])
return inclusion_digraph
示例5: Tournament
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def Tournament(self,n):
r"""
Returns a tournament on `n` vertices.
In this tournament there is an edge from `i` to `j` if `i<j`.
INPUT:
- ``n`` (integer) -- number of vertices in the tournament.
EXAMPLES::
sage: g = digraphs.Tournament(5)
sage: g.vertices()
[0, 1, 2, 3, 4]
sage: g.size()
10
sage: g.automorphism_group().cardinality()
1
"""
if n<0:
raise ValueError("The number of vertices must be a positive integer.")
g = DiGraph()
g.name("Tournament on "+str(n)+" vertices")
for i in range(n-1):
for j in range(i+1, n):
g.add_edge(i,j)
if n:
from sage.graphs.graph_plot import _circle_embedding
_circle_embedding(g, range(n))
return g
示例6: basis_of_simple_closed_curves
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def basis_of_simple_closed_curves(self):
from sage.graphs.digraph import DiGraph
from sage.all import randint
n = self._origami.nb_squares()
C = self.chain_space()
G = DiGraph(multiedges=True,loops=True,implementation='c_graph')
for i in xrange(2*n):
G.add_edge(self._starts[i], self._ends[i], i)
waiting = [0]
gens = []
reps = [None] * G.num_verts()
reps[0] = C.zero()
while waiting:
x = waiting.pop(randint(0,len(waiting)-1))
for v0,v1,e in G.outgoing_edges(x):
if reps[v1] is not None:
gens.append(reps[v0] + C.gen(e) - reps[v1])
else:
reps[v1] = reps[v0] + C.gen(e)
waiting.append(v1)
return gens
示例7: random_orientation
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def random_orientation(G):
r"""
Return a random orientation of a graph `G`.
An *orientation* of an undirected graph is a directed graph such that every
edge is assigned a direction. Hence there are `2^m` oriented digraphs for a
simple graph with `m` edges.
INPUT:
- ``G`` -- a Graph.
EXAMPLES::
sage: from sage.graphs.orientations import random_orientation
sage: G = graphs.PetersenGraph()
sage: D = random_orientation(G)
sage: D.order() == G.order(), D.size() == G.size()
(True, True)
TESTS:
Giving anything else than a Graph::
sage: random_orientation([])
Traceback (most recent call last):
...
ValueError: the input parameter must be a Graph
.. SEEALSO::
- :meth:`~Graph.orientations`
"""
from sage.graphs.graph import Graph
if not isinstance(G, Graph):
raise ValueError("the input parameter must be a Graph")
D = DiGraph(data=[G.vertices(), []],
format='vertices_and_edges',
multiedges=G.allows_multiple_edges(),
loops=G.allows_loops(),
weighted=G.weighted(),
pos=G.get_pos(),
name="Random orientation of {}".format(G.name()) )
if hasattr(G, '_embedding'):
D._embedding = copy(G._embedding)
from sage.misc.prandom import getrandbits
rbits = getrandbits(G.size())
for u,v,l in G.edge_iterator():
if rbits % 2:
D.add_edge(u, v, l)
else:
D.add_edge(v, u, l)
rbits >>= 1
return D
示例8: as_graph
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def as_graph(self):
r"""
Return the graph associated to self
"""
from sage.graphs.digraph import DiGraph
G = DiGraph(multiedges=True,loops=True)
d = self.degree()
g = [self.g_tuple(i) for i in xrange(4)]
for i in xrange(d):
for j in xrange(4):
G.add_edge(i,g[j][i],j)
return G
示例9: uncompactify
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def uncompactify(self):
r"""
Returns the tree obtained from self by splitting edges so that they
are labelled by exactly one letter. The resulting tree is
isomorphic to the suffix trie.
EXAMPLES::
sage: from sage.combinat.words.suffix_trees import ImplicitSuffixTree, SuffixTrie
sage: abbab = Words("ab")("abbab")
sage: s = SuffixTrie(abbab)
sage: t = ImplicitSuffixTree(abbab)
sage: t.uncompactify().is_isomorphic(s.to_digraph())
True
"""
tree = self.to_digraph(word_labels=True)
newtree = DiGraph()
newtree.add_vertices(range(tree.order()))
new_node = tree.order() + 1
for (u,v,label) in tree.edge_iterator():
if len(label) == 1:
newtree.add_edge(u,v)
else:
newtree.add_edge(u,new_node,label[0]);
for w in label[1:-1]:
newtree.add_edge(new_node,new_node+1,w)
new_node += 1
newtree.add_edge(new_node,v,label[-1])
new_node += 1
return newtree
示例10: digraph
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def digraph(self):
r"""
Return the :class:`DiGraph` associated to ``self``.
EXAMPLES::
sage: B = crystals.Letters(['A', [1,3]])
sage: G = B.digraph(); G
Multi-digraph on 6 vertices
sage: Q = crystals.Letters(['Q',3])
sage: G = Q.digraph(); G
Multi-digraph on 3 vertices
sage: G.edges()
[(1, 2, -1), (1, 2, 1), (2, 3, -2), (2, 3, 2)]
The edges of the crystal graph are by default colored using
blue for edge 1, red for edge 2, green for edge 3, and dashed with
the corresponding color for barred edges. Edge 0 is dotted black::
sage: view(G) # optional - dot2tex graphviz, not tested (opens external window)
"""
from sage.graphs.digraph import DiGraph
from sage.misc.latex import LatexExpr
from sage.combinat.root_system.cartan_type import CartanType
G = DiGraph(multiedges=True)
G.add_vertices(self)
for i in self.index_set():
for x in G:
y = x.f(i)
if y is not None:
G.add_edge(x, y, i)
def edge_options(data):
u, v, l = data
edge_opts = { 'edge_string': '->', 'color': 'black' }
if l > 0:
edge_opts['color'] = CartanType._colors.get(l, 'black')
edge_opts['label'] = LatexExpr(str(l))
elif l < 0:
edge_opts['color'] = "dashed," + CartanType._colors.get(-l, 'black')
edge_opts['label'] = LatexExpr("\\overline{%s}" % str(-l))
else:
edge_opts['color'] = "dotted," + CartanType._colors.get(l, 'black')
edge_opts['label'] = LatexExpr(str(l))
return edge_opts
G.set_latex_options(format="dot2tex", edge_labels=True, edge_options=edge_options)
return G
示例11: add_edge
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def add_edge(self, i, j, label=1):
"""
EXAMPLES::
sage: from sage.combinat.root_system.dynkin_diagram import DynkinDiagram_class
sage: d = DynkinDiagram_class(CartanType(['A',3]))
sage: list(sorted(d.edges()))
[]
sage: d.add_edge(2, 3)
sage: list(sorted(d.edges()))
[(2, 3, 1), (3, 2, 1)]
"""
DiGraph.add_edge(self, i, j, label)
if not self.has_edge(j,i):
self.add_edge(j,i,1)
示例12: plot
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def plot(self, **kwds):
"""
EXAMPLES::
sage: X = gauge_theories.threeSU(3)
sage: print X.plot().description()
"""
g = DiGraph(loops=True, sparse=True, multiedges=True)
for G in self._gauge_groups:
g.add_vertex(G)
for field in self._fields:
if isinstance(field, FieldBifundamental):
g.add_edge(field.src, field.dst, field)
if isinstance(field, FieldAdjoint):
g.add_edge(field.node, field.node, field)
return g.plot(vertex_labels=True, edge_labels=True, graph_border=True)
示例13: quiver_v2
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def quiver_v2(self):
#if hasattr(self, "_quiver_cache"):
# return self._quiver_cache
from sage.combinat.subset import Subsets
from sage.graphs.digraph import DiGraph
Q = DiGraph(multiedges=True)
Q.add_vertices(self.j_transversal())
g = self.associated_graph()
for U in Subsets(g.vertices()):
for W in Subsets(U):
h = g.subgraph(U.difference(W))
n = h.connected_components_number() - 1
if n > 0:
u = self.j_class_representative(self.j_class_index(self(''.join(U))))
w = self.j_class_representative(self.j_class_index(self(''.join(W))))
for i in range(n):
Q.add_edge(w, u, i)
return Q
示例14: plot
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def plot(self, **kwargs):
"""
Return a graphics object representing the Kontsevich graph.
INPUT:
- ``edge_labels`` (boolean, default True) -- if True, show edge labels.
- ``indices`` (boolean, default False) -- if True, show indices as
edge labels instead of L and R; see :meth:`._latex_`.
- ``upright`` (boolean, default False) -- if True, try to plot the
graph with the ground vertices on the bottom and the rest on top.
"""
if not 'edge_labels' in kwargs:
kwargs['edge_labels'] = True # show edge labels by default
if 'indices' in kwargs:
del kwargs['indices']
KG = DiGraph(self)
for (k,e) in enumerate(self.edges()):
KG.delete_edge(e)
KG.add_edge((e[0], e[1], chr(97 + k)))
return KG.plot(**kwargs)
if len(self.ground_vertices()) == 2 and 'upright' in kwargs:
del kwargs['upright']
kwargs['save_pos'] = True
DiGraph.plot(self, **kwargs)
positions = self.get_pos()
# translate F to origin:
F_pos = vector(positions[self.ground_vertices()[0]])
for p in positions:
positions[p] = list(vector(positions[p]) - F_pos)
# scale F - G distance to 1:
G_len = abs(vector(positions[self.ground_vertices()[1]]))
for p in positions:
positions[p] = list(vector(positions[p])/G_len)
# rotate the vector F - G to (1,0)
from math import atan2
theta = -atan2(positions[self.ground_vertices()[1]][1], positions[self.ground_vertices()[1]][0])
for p in positions:
positions[p] = list(matrix([[cos(theta),-(sin(theta))],[sin(theta),cos(theta)]]) * vector(positions[p]))
# flip if most things are below the x-axis:
if len([(x,y) for (x,y) in positions.values() if y < 0])/len(self.internal_vertices()) > 0.5:
for p in positions:
positions[p] = [positions[p][0], -positions[p][1]]
return DiGraph.plot(self, **kwargs)
示例15: RandomTournament
# 需要导入模块: from sage.graphs.digraph import DiGraph [as 别名]
# 或者: from sage.graphs.digraph.DiGraph import add_edge [as 别名]
def RandomTournament(self, n):
r"""
Returns a random tournament on `n` vertices.
For every pair of vertices, the tournament has an edge from
`i` to `j` with probability `1/2`, otherwise it has an edge
from `j` to `i`.
See :wikipedia:`Tournament_(graph_theory)`
INPUT:
- ``n`` (integer) -- number of vertices.
EXAMPLES::
sage: T = digraphs.RandomTournament(10); T
Random Tournament: Digraph on 10 vertices
sage: T.size() == binomial(10, 2)
True
sage: digraphs.RandomTournament(-1)
Traceback (most recent call last):
...
ValueError: The number of vertices cannot be strictly negative!
"""
from sage.misc.prandom import random
g = DiGraph(n)
g.name("Random Tournament")
for i in range(n - 1):
for j in range(i + 1, n):
if random() <= 0.5:
g.add_edge(i, j)
else:
g.add_edge(j, i)
if n:
from sage.graphs.graph_plot import _circle_embedding
_circle_embedding(g, range(n))
return g