本文整理汇总了Python中sage.graphs.graph.Graph.add_edges方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.add_edges方法的具体用法?Python Graph.add_edges怎么用?Python Graph.add_edges使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sage.graphs.graph.Graph
的用法示例。
在下文中一共展示了Graph.add_edges方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: cluster_in_box
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [as 别名]
def cluster_in_box(self, m, pt=None):
r"""
Return the cluster (as a list) in the primal box [-m,m]^d
containing the point pt.
INPUT:
- ``m`` - integer
- ``pt`` - tuple, point in Z^d. If None, pt=zero is considered.
EXAMPLES::
sage: from slabbe import BondPercolationSample
sage: S = BondPercolationSample(0.3,2)
sage: S.cluster_in_box(2) # random
[(-2, -2), (-2, -1), (-1, -2), (-1, -1), (-1, 0), (0, 0)]
"""
G = Graph()
G.add_edges(self.edges_in_box(m))
if pt is None:
pt = self.zero()
if pt in G:
return G.connected_component_containing_vertex(pt)
else:
return []
示例2: CircularLadderGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [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
示例3: create_graph_from_model
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [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
示例4: _polar_graph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [as 别名]
def _polar_graph(m, q, g, intersection_size=None):
r"""
The helper function to build graphs `(D)U(m,q)` and `(D)Sp(m,q)`
Building a graph on an orbit of a group `g` of `m\times m` matrices over `GF(q)` on
the points (or subspaces of dimension ``m//2``) isotropic w.r.t. the form `F`
left invariant by the group `g`.
The only constraint is that the first ``m//2`` elements of the standard
basis must generate a totally isotropic w.r.t. `F` subspace; this is the case with
these groups coming from GAP; namely, `F` has the anti-diagonal all-1 matrix.
INPUT:
- ``m`` -- the dimension of the underlying vector space
- ``q`` -- the size of the field
- ``g`` -- the group acting
- ``intersection_size`` -- if ``None``, build the graph on the isotropic points, with
adjacency being orthogonality w.r.t. `F`. Otherwise, build the graph on the maximal
totally isotropic subspaces, with adjacency specified by ``intersection_size`` being
as given.
TESTS::
sage: from sage.graphs.generators.classical_geometries import _polar_graph
sage: _polar_graph(4, 4, libgap.GeneralUnitaryGroup(4, 2))
Graph on 45 vertices
sage: _polar_graph(4, 4, libgap.GeneralUnitaryGroup(4, 2), intersection_size=1)
Graph on 27 vertices
"""
from sage.libs.gap.libgap import libgap
from itertools import combinations
W=libgap.FullRowSpace(libgap.GF(q), m) # F_q^m
B=libgap.Elements(libgap.Basis(W)) # the standard basis of W
V = libgap.Orbit(g,B[0],libgap.OnLines) # orbit on isotropic points
gp = libgap.Action(g,V,libgap.OnLines) # make a permutation group
s = libgap.Subspace(W,[B[i] for i in range(m//2)]) # a totally isotropic subspace
# and the points there
sp = [libgap.Elements(libgap.Basis(x))[0] for x in libgap.Elements(s.Subspaces(1))]
h = libgap.Set(map(lambda x: libgap.Position(V, x), sp)) # indices of the points in s
L = libgap.Orbit(gp, h, libgap.OnSets) # orbit on these subspaces
if intersection_size == None:
G = Graph()
for x in L: # every pair of points in the subspace is adjacent to each other in G
G.add_edges(combinations(x, 2))
return G
else:
return Graph([L, lambda i,j: libgap.Size(libgap.Intersection(i,j))==intersection_size],
loops=False)
示例5: CircularLadderGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [as 别名]
def CircularLadderGraph(n):
r"""
Return 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.
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.
When `n == 2`, we rotate the outer circle by an angle of `\pi/8` to ensure
that all edges are visible (otherwise the 4 vertices of the graph would be
placed on a single line).
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
"""
G = Graph(2 * n, name="Circular Ladder graph")
G._circle_embedding(list(range(n)), radius=1, angle=pi/2)
if n == 2:
G._circle_embedding(list(range(4)), radius=1, angle=pi/2 + pi/8)
else:
G._circle_embedding(list(range(n, 2*n)), radius=2, angle=pi/2)
G.add_cycle(list(range(n)))
G.add_cycle(list(range(n, 2 * n)))
G.add_edges( (i,i+n) for i in range(n) )
return G
示例6: LadderGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [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
示例7: IntersectionGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [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
示例8: read_mtx
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [as 别名]
def read_mtx(f):
contents = f.readlines()
edges = []
first = 0
for i in range(len(contents)):
words = contents[i].split()
if words[0][0] != '%':
if first == 0:
first = 1
else:
if(len(words) == 3):
edges.append((int(words[0]), int(words[1]), float(words[2])))
else:
edges.append((int(words[0]), int(words[1]), None))
g = Graph()
g.add_edges(edges)
return g
示例9: _check_pbd
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [as 别名]
def _check_pbd(B,v,S):
r"""
Checks that ``B`` is a PBD on `v` points with given block sizes.
INPUT:
- ``bibd`` -- a list of blocks
- ``v`` (integer) -- number of points
- ``S`` -- list of integers
EXAMPLE::
sage: designs.BalancedIncompleteBlockDesign(40,4).blocks() # indirect doctest
[[0, 1, 2, 12], [0, 3, 6, 9], [0, 4, 8, 10],
[0, 5, 7, 11], [0, 13, 26, 39], [0, 14, 25, 28],
[0, 15, 27, 38], [0, 16, 22, 32], [0, 17, 23, 34],
...
"""
from itertools import combinations
from sage.graphs.graph import Graph
if not all(len(X) in S for X in B):
raise RuntimeError("This is not a nice honest PBD from the good old days !")
g = Graph()
m = 0
for X in B:
g.add_edges(list(combinations(X,2)))
if g.size() != m+binomial(len(X),2):
raise RuntimeError("This is not a nice honest PBD from the good old days !")
m = g.size()
if not (g.is_clique() and g.vertices() == range(v)):
raise RuntimeError("This is not a nice honest PBD from the good old days !")
return B
示例10: apply
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [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: NonisotropicUnitaryPolarGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [as 别名]
def NonisotropicUnitaryPolarGraph(m, q):
r"""
Returns the Graph `NU(m,q)`.
Returns the graph on nonisotropic, with respect to a nondegenerate
Hermitean form, points of the `(m-1)`-dimensional projective space over `F_q`,
with points adjacent whenever they lie on a tangent (to the set of isotropic points)
line.
For more information, see Sect. 9.9 of [BH12]_ and series C14 in [Hu75]_.
INPUT:
- ``m,q`` (integers) -- `q` must be a prime power.
EXAMPLES::
sage: g=graphs.NonisotropicUnitaryPolarGraph(5,2); g
NU(5, 2): Graph on 176 vertices
sage: g.is_strongly_regular(parameters=True)
(176, 135, 102, 108)
TESTS::
sage: graphs.NonisotropicUnitaryPolarGraph(4,2).is_strongly_regular(parameters=True)
(40, 27, 18, 18)
sage: graphs.NonisotropicUnitaryPolarGraph(4,3).is_strongly_regular(parameters=True) # long time
(540, 224, 88, 96)
sage: graphs.NonisotropicUnitaryPolarGraph(6,6)
Traceback (most recent call last):
...
ValueError: q must be a prime power
REFERENCE:
.. [Hu75] \X. L. Hubaut.
Strongly regular graphs.
Disc. Math. 13(1975), pp 357--381.
http://dx.doi.org/10.1016/0012-365X(75)90057-6
"""
p, k = is_prime_power(q,get_data=True)
if k==0:
raise ValueError('q must be a prime power')
from sage.libs.gap.libgap import libgap
from itertools import combinations
F=libgap.GF(q**2) # F_{q^2}
W=libgap.FullRowSpace(F, m) # F_{q^2}^m
B=libgap.Elements(libgap.Basis(W)) # the standard basis of W
if m % 2 != 0:
point = B[(m-1)/2]
else:
if p==2:
point = B[m/2] + F.PrimitiveRoot()*B[(m-2)/2]
else:
point = B[(m-2)/2] + B[m/2]
g = libgap.GeneralUnitaryGroup(m,q)
V = libgap.Orbit(g,point,libgap.OnLines) # orbit on nonisotropic points
gp = libgap.Action(g,V,libgap.OnLines) # make a permutation group
s = libgap.Subspace(W,[point, point+B[0]]) # a tangent line on point
# and the points there
sp = [libgap.Elements(libgap.Basis(x))[0] for x in libgap.Elements(s.Subspaces(1))]
h = libgap.Set(map(lambda x: libgap.Position(V, x), libgap.Intersection(V,sp))) # indices
L = libgap.Orbit(gp, h, libgap.OnSets) # orbit on the tangent lines
G = Graph()
for x in L: # every pair of points in the subspace is adjacent to each other in G
G.add_edges(combinations(x, 2))
G.relabel()
G.name("NU" + str((m, q)))
return G
示例12: NonisotropicOrthogonalPolarGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [as 别名]
#.........这里部分代码省略.........
sage: g=graphs.NonisotropicOrthogonalPolarGraph(8,2,'+')
sage: g.is_strongly_regular(parameters=True)
(120, 63, 30, 36)
Wilbrink's graphs for `q=5`::
sage: graphs.NonisotropicOrthogonalPolarGraph(5,5,perp=1).is_strongly_regular(parameters=True) # long time
(325, 60, 15, 10)
sage: graphs.NonisotropicOrthogonalPolarGraph(5,5,'-',perp=1).is_strongly_regular(parameters=True) # long time
(300, 65, 10, 15)
Wilbrink's graphs::
sage: g=graphs.NonisotropicOrthogonalPolarGraph(5,4,'+')
sage: g.is_strongly_regular(parameters=True)
(136, 75, 42, 40)
sage: g=graphs.NonisotropicOrthogonalPolarGraph(5,4,'-')
sage: g.is_strongly_regular(parameters=True)
(120, 51, 18, 24)
sage: g=graphs.NonisotropicOrthogonalPolarGraph(7,4,'+'); g # not tested (long time)
NO^+(7, 4): Graph on 2080 vertices
sage: g.is_strongly_regular(parameters=True) # not tested (long time)
(2080, 1071, 558, 544)
TESTS::
sage: g=graphs.NonisotropicOrthogonalPolarGraph(4,2); g
NO^+(4, 2): Graph on 6 vertices
sage: graphs.NonisotropicOrthogonalPolarGraph(4,3,'-').is_strongly_regular(parameters=True)
(15, 6, 1, 3)
sage: g=graphs.NonisotropicOrthogonalPolarGraph(3,5,'-',perp=1); g
NO^-,perp(3, 5): Graph on 10 vertices
sage: g.is_strongly_regular(parameters=True)
(10, 3, 0, 1)
sage: g=graphs.NonisotropicOrthogonalPolarGraph(6,3,'+') # long time
sage: g.is_strongly_regular(parameters=True) # long time
(117, 36, 15, 9)
sage: g=graphs.NonisotropicOrthogonalPolarGraph(6,3,'-'); g # long time
NO^-(6, 3): Graph on 126 vertices
sage: g.is_strongly_regular(parameters=True) # long time
(126, 45, 12, 18)
sage: g=graphs.NonisotropicOrthogonalPolarGraph(5,5,'-') # long time
sage: g.is_strongly_regular(parameters=True) # long time
(300, 104, 28, 40)
sage: g=graphs.NonisotropicOrthogonalPolarGraph(5,5,'+') # long time
sage: g.is_strongly_regular(parameters=True) # long time
(325, 144, 68, 60)
sage: g=graphs.NonisotropicOrthogonalPolarGraph(6,4,'+')
Traceback (most recent call last):
...
ValueError: for m even q must be 2 or 3
"""
from sage.graphs.generators.classical_geometries import _orthogonal_polar_graph
p, k = is_prime_power(q,get_data=True)
if k==0:
raise ValueError('q must be a prime power')
dec = ''
if m % 2 == 0:
if q in [2,3]:
G = _orthogonal_polar_graph(m, q, sign=sign, point_type=[1])
else:
raise ValueError("for m even q must be 2 or 3")
elif not perp is None:
if q == 5:
G = _orthogonal_polar_graph(m, q, point_type=\
[-1,1] if sign=='+' else [2,3] if sign=='-' else [])
dec = ",perp"
else:
raise ValueError("for perp not None q must be 5")
else:
if not sign in ['+','-']:
raise ValueError("sign must be '+' or '-'")
from sage.libs.gap.libgap import libgap
g0 = libgap.GeneralOrthogonalGroup(m,q)
g = libgap.Group(libgap.List(g0.GeneratorsOfGroup(),libgap.TransposedMat))
F=libgap.GF(q) # F_q
W=libgap.FullRowSpace(F, m) # F_q^m
e = 1 if sign=='+' else -1
n = (m-1)/2
# we build (q^n(q^n+e)/2, (q^n-e)(q^(n-1)+e), 2(q^(2n-2)-1)+eq^(n-1)(q-1),
# 2q^(n-1)(q^(n-1)+e))-srg
# **use** v and k to select appropriate orbit and orbital
nvert = (q**n)*(q**n+e)/2 # v
deg = (q**n-e)*(q**(n-1)+e) # k
S=map(lambda x: libgap.Elements(libgap.Basis(x))[0], \
libgap.Elements(libgap.Subspaces(W,1)))
V = filter(lambda x: len(x)==nvert, libgap.Orbits(g,S,libgap.OnLines))
assert len(V)==1
V = V[0]
gp = libgap.Action(g,V,libgap.OnLines) # make a permutation group
h = libgap.Stabilizer(gp,1)
Vh = filter(lambda x: len(x)==deg, libgap.Orbits(h,libgap.Orbit(gp,1)))
assert len(Vh)==1
Vh = Vh[0][0]
L = libgap.Orbit(gp, [1, Vh], libgap.OnSets)
G = Graph()
G.add_edges(L)
G.name("NO^" + sign + dec + str((m, q)))
return G
示例13: CompleteBipartiteGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [as 别名]
#.........这里部分代码省略.........
spring-layout algorithm vs. the position dictionary used in this
constructor. The position dictionary flattens the graph and separates the
partitioned nodes, making it clear which nodes an edge is connected to. The
Complete Bipartite graph plotted with the spring-layout algorithm tends to
center the nodes in n1 (see spring_med in examples below), thus overlapping
its nodes and edges, making it typically hard to decipher.
Filling the position dictionary in advance adds `O(n)` to the constructor.
Feel free to race the constructors below in the examples section. The much
larger difference is the time added by the spring-layout algorithm when
plotting. (Also shown in the example below). The spring model is typically
described as `O(n^3)`, as appears to be the case in the NetworkX source
code.
EXAMPLES:
Two ways of constructing the complete bipartite graph, using different
layout algorithms::
sage: import networkx
sage: n = networkx.complete_bipartite_graph(389, 157); spring_big = Graph(n) # long time
sage: posdict_big = graphs.CompleteBipartiteGraph(389, 157) # long time
Compare the plotting::
sage: n = networkx.complete_bipartite_graph(11, 17)
sage: spring_med = Graph(n)
sage: posdict_med = graphs.CompleteBipartiteGraph(11, 17)
Notice here how the spring-layout tends to center the nodes of `n1`::
sage: spring_med.show() # long time
sage: posdict_med.show() # long time
View many complete bipartite graphs with a Sage Graphics Array, with this
constructor (i.e., the position dictionary filled)::
sage: g = []
sage: j = []
sage: for i in range(9):
....: k = graphs.CompleteBipartiteGraph(i+1,4)
....: 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
We compare to plotting with the spring-layout algorithm::
sage: g = []
sage: j = []
sage: for i in range(9):
....: spr = networkx.complete_bipartite_graph(i+1,4)
....: k = Graph(spr)
....: 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
:trac:`12155`::
sage: graphs.CompleteBipartiteGraph(5,6).complement()
complement(Complete bipartite graph of order 5+6): Graph on 11 vertices
TESTS:
Prevent negative dimensions (:trac:`18530`)::
sage: graphs.CompleteBipartiteGraph(-1,1)
Traceback (most recent call last):
...
ValueError: the arguments n1(=-1) and n2(=1) must be positive integers
sage: graphs.CompleteBipartiteGraph(1,-1)
Traceback (most recent call last):
...
ValueError: the arguments n1(=1) and n2(=-1) must be positive integers
"""
if n1<0 or n2<0:
raise ValueError('the arguments n1(={}) and n2(={}) must be positive integers'.format(n1,n2))
G = Graph(n1+n2, name="Complete bipartite graph of order {}+{}".format(n1, n2))
G.add_edges((i,j) for i in range(n1) for j in range(n1,n1+n2))
# We now assign positions to vertices:
# - vertices 0,..,n1-1 are placed on the line (0, 1) to (max(n1, n2), 1)
# - vertices n1,..,n1+n2-1 are placed on the line (0, 0) to (max(n1, n2), 0)
# If n1 (or n2) is 1, the vertex is centered in the line.
if set_position:
nmax = max(n1, n2)
G._line_embedding(list(range(n1)), first=(0, 1), last=(nmax, 1))
G._line_embedding(list(range(n1, n1+n2)), first=(0, 0), last=(nmax, 0))
return G
示例14: root_graph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [as 别名]
#.........这里部分代码省略.........
# If a vertex of G has an odd number of neighbors among the vertices
# of S, then the triangle is odd. We compute the list of such
# vertices by taking the symmetric difference of the neighborhood of
# our three vertices.
#
# Note that the elements of S do not appear in this set as they are
# all seen exactly twice.
odd_neighbors = set(G.neighbors(S[0]))
odd_neighbors.symmetric_difference_update(G.neighbors(S[1]))
odd_neighbors.symmetric_difference_update(G.neighbors(S[2]))
# Even triangles
if not odd_neighbors:
even_triangles.append(tuple(S))
continue
# We manage odd triangles the same way we manage other cliques ...
# We now associate the clique to all the vertices it contains.
for v in S:
if len(v_cliques[v]) == 2:
raise ValueError("This graph is not a line graph !")
v_cliques[v].append(tuple(S))
if verbose:
print("Added clique", S)
# Deal with even triangles
for u,v,w in even_triangles:
# According to Beineke, we must go through all even triangles, and for
# each triangle uvw consider its three pairs of adjacent verties uv, vw,
# wu. For all pairs xy among those such that xy do not appear together
# in any clique we have found so far, we add xy to the list of cliques
# describing our covering.
for x,y in [(u,v), (v,w), (w,u)]:
# If edge xy does not appear in any of the cliques associated with y
if all([not x in C for C in v_cliques[y]]):
if len(v_cliques[y]) >= 2 or len(v_cliques[x]) >= 2:
raise ValueError("This graph is not a line graph !")
v_cliques[x].append((x,y))
v_cliques[y].append((x,y))
if verbose:
print("Adding pair", (x, y),
"appearing in the even triangle", (u, v, w))
# Deal with vertices contained in only one clique. All edges must be defined
# by TWO endpoints, so we add a fake clique.
for x, clique_list in iteritems(v_cliques):
if len(clique_list) == 1:
clique_list.append((x,))
# We now have all our cliques. Let's build the root graph to check that it
# all fits !
from sage.graphs.graph import Graph
R = Graph()
# Associates an integer to each clique
relabel = {}
# Associates to each vertex of G its pair of coordinates in R
vertex_to_map = {}
for v, L in iteritems(v_cliques):
# Add cliques to relabel dictionary
for S in L:
if not S in relabel:
relabel[S] = len(relabel)
# The coordinates of edge v
vertex_to_map[v] = relabel[L[0]], relabel[L[1]]
if verbose:
print("Final associations :")
for v, L in iteritems(v_cliques):
print(v, L)
# We now build R
R.add_edges(vertex_to_map.values())
# Even if whatever is written above is complete nonsense, here we
# make sure that we do not return gibberish. Is the line graph of
# R isomorphic to the input ? If so, we return R, and the
# isomorphism. Else, we panic and scream.
#
# It's actually "just to make sure twice". This can be removed later if it
# turns out to be too costly.
is_isom, isom = g.is_isomorphic(R.line_graph(labels = False), certificate = True)
if not is_isom:
raise Exception(error_message)
return R, isom
示例15: OrthogonalArrayBlockGraph
# 需要导入模块: from sage.graphs.graph import Graph [as 别名]
# 或者: from sage.graphs.graph.Graph import add_edges [as 别名]
#.........这里部分代码省略.........
- ``OA`` -- An orthogonal array. If set to ``None`` (default) then
:func:`~sage.combinat.designs.orthogonal_arrays.orthogonal_array` is
called to compute an `OA(k,n)`.
EXAMPLES::
sage: G = graphs.OrthogonalArrayBlockGraph(5,5); G
OA(5,5): Graph on 25 vertices
sage: G.is_strongly_regular(parameters=True)
(25, 20, 15, 20)
sage: G = graphs.OrthogonalArrayBlockGraph(4,10); G
OA(4,10): Graph on 100 vertices
sage: G.is_strongly_regular(parameters=True)
(100, 36, 14, 12)
Two graphs built from different orthogonal arrays are also different::
sage: k=4;n=10
sage: OAa = designs.orthogonal_arrays.build(k,n)
sage: OAb = [[(x+1)%n for x in R] for R in OAa]
sage: set(map(tuple,OAa)) == set(map(tuple,OAb))
False
sage: Ga = graphs.OrthogonalArrayBlockGraph(k,n,OAa)
sage: Gb = graphs.OrthogonalArrayBlockGraph(k,n,OAb)
sage: Ga == Gb
False
As ``OAb`` was obtained from ``OAa`` by a relabelling the two graphs are
isomorphic::
sage: Ga.is_isomorphic(Gb)
True
But there are examples of `OA(k,n)` for which the resulting graphs are not
isomorphic::
sage: oa0 = [[0, 0, 1], [0, 1, 3], [0, 2, 0], [0, 3, 2],
....: [1, 0, 3], [1, 1, 1], [1, 2, 2], [1, 3, 0],
....: [2, 0, 0], [2, 1, 2], [2, 2, 1], [2, 3, 3],
....: [3, 0, 2], [3, 1, 0], [3, 2, 3], [3, 3, 1]]
sage: oa1 = [[0, 0, 1], [0, 1, 0], [0, 2, 3], [0, 3, 2],
....: [1, 0, 3], [1, 1, 2], [1, 2, 0], [1, 3, 1],
....: [2, 0, 0], [2, 1, 1], [2, 2, 2], [2, 3, 3],
....: [3, 0, 2], [3, 1, 3], [3, 2, 1], [3, 3, 0]]
sage: g0 = graphs.OrthogonalArrayBlockGraph(3,4,oa0)
sage: g1 = graphs.OrthogonalArrayBlockGraph(3,4,oa1)
sage: g0.is_isomorphic(g1)
False
But nevertheless isospectral::
sage: g0.spectrum()
[9, 1, 1, 1, 1, 1, 1, 1, 1, 1, -3, -3, -3, -3, -3, -3]
sage: g1.spectrum()
[9, 1, 1, 1, 1, 1, 1, 1, 1, 1, -3, -3, -3, -3, -3, -3]
Note that the graph ``g0`` is actually isomorphic to the affine polar graph
`VO^+(4,2)`::
sage: graphs.AffineOrthogonalPolarGraph(4,2,'+').is_isomorphic(g0)
True
TESTS::
sage: G = graphs.OrthogonalArrayBlockGraph(4,6)
Traceback (most recent call last):
...
NotImplementedError: I don't know how to build an OA(4,6)!
sage: G = graphs.OrthogonalArrayBlockGraph(8,2)
Traceback (most recent call last):
...
ValueError: There is no OA(8,2). Beware, Brouwer's website uses OA(n,k) instead of OA(k,n) !
"""
if n>1 and k>=n+2:
raise ValueError("There is no OA({},{}). Beware, Brouwer's website uses OA(n,k) instead of OA(k,n) !".format(k,n))
from itertools import combinations
if OA is None:
from sage.combinat.designs.orthogonal_arrays import orthogonal_array
OA = orthogonal_array(k,n)
else:
assert len(OA) == n**2
assert n == 0 or k == len(OA[0])
OA = map(tuple,OA)
d = [[[] for j in range(n)] for i in range(k)]
for R in OA:
for i,x in enumerate(R):
d[i][x].append(R)
g = Graph()
for l in d:
for ll in l:
g.add_edges(combinations(ll,2))
g.name("OA({},{})".format(k,n))
return g