ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Tue, 23 Mar 2021 00:17:54 +0100Plot "color_by_label" produces SQUARED number of lines in digraphhttps://ask.sagemath.org/question/56324/plot-color_by_label-produces-squared-number-of-lines-in-digraph/I bumped into this unusual behavior and am not sure how to fix it.
When I add `color_by_label` for plotting a digraph I get the correct
number SQUARED of lines appearing in the digraph. Is this an error
in SageMath or is there a workaround? All monochrome lines
do not work for my application.
This is my code sample:
stnc = 'ABCCCCDABCDABCDA'
g = DiGraph({}, loops=True, multiedges=True)
for a, b in [(stnc[i], stnc[i + 1]) for i in range(len(stnc) - 1)]:
g.add_edge(a, b, b)
sage: g.edges()
[('A', 'B', 'B'), ('A', 'B', 'B'), ('A', 'B', 'B'),
('B', 'C', 'C'), ('B', 'C', 'C'), ('B', 'C', 'C'),
('C', 'C', 'C'), ('C', 'C', 'C'), ('C', 'C', 'C'),
('C', 'D', 'D'), ('C', 'D', 'D'), ('C', 'D', 'D'),
('D', 'A', 'A'), ('D', 'A', 'A'), ('D', 'A', 'A')]
# This produces the correct number of lines SQUARED
g.plot(color_by_label=True, edge_style='solid', layout='circular').show(figsize=(8, 8))
# Correct number of lines but monochrome
g.plot(layout='circular').show(figsize=(8, 8))
![Incorrect edge multiplicity for multidigraph with color_by_label](/upfiles/16164608644236614.png)
Each edge should have multiplicity 3.
In the plot with color edges, each has multiplicity 9.
The plot with no colors has correct multiplicity 3 for each edge.JJTue, 23 Mar 2021 00:17:54 +0100https://ask.sagemath.org/question/56324/How to eliminate truncated graph arrowheads?https://ask.sagemath.org/question/54450/how-to-eliminate-truncated-graph-arrowheads/The following simple directed graph has truncated arrowheads:
vpos = {'W':(-0.5,0.5),'E':(0.5,0.5),'mW':(-0.5,0),'mE':(0.5,0)}
D1 = DiGraph()
D1.add_edge(('mW','mE','mE-mW'))
D1.add_edge(('W','E','W-E'))
D1.add_edge(('mW','W'))
D1.show(pos=vpos,vertex_size=500,figsize=(2,2))
![image description](https://snipboard.io/FV8Iqy.jpg)
If I change the last statement to:
D1.show(pos=vpos)
I still get truncated horizontal arrows, but less on the vertical.
![image description](https://snipboard.io/P5lAfj.jpg)
Any suggestions for preserving full arrowheads? It looks like the clip limits for arrows are different than those for vertices. Setting `fig_tight=False` has no effect.
holistoneSun, 29 Nov 2020 19:56:09 +0100https://ask.sagemath.org/question/54450/Error in datastructure in sagemathhttps://ask.sagemath.org/question/50244/error-in-datastructure-in-sagemath/I am new to creating a graph. I am trying to analyse a code by recreating it. My sample code is given below:
n=10
show(graphs.CompleteGraph(2*n+2))
g=graphs.CompleteGraph(2*n+2)
time_window_interval = [0, 4*60]
g = g.to_directed(time_window_interval)
g.show
On running the code, I am getting "ValueError: data_structure must be equal to 'sparse', 'static_sparse' or 'dense'" on the line g = g.to_directed(time_window_interval).MrsOSun, 15 Mar 2020 00:58:33 +0100https://ask.sagemath.org/question/50244/Sage stalls during computationhttps://ask.sagemath.org/question/48270/sage-stalls-during-computation/I was using SageMath 8.8's [feedback_edge_set](http://doc.sagemath.org/html/en/reference/graphs/sage/graphs/digraph.html#sage.graphs.digraph.DiGraph.feedback_edge_set) function on a large dataset. The calculation would take a couple of days to finish.
Unfortunately, Sage would keep stalling every few hours. The CPU usage of the process would simply drop to zero, and it would stop doing anything. I had to kill the process (a simple `kill` worked, no `kill -9` necessary).
Has anyone else experienced this? Is it a known problem? Is there a workaround? It is very frustrating to have to keep manually killing and restarting the process. This problem also prevents me from running a calculation overnight: in the morning I might find that it stopped merely an hour after I started it (if I'm unlucky).
----
More information:
- I was using Sage on Linux
- This function uses [MixedIntegerLinearProgram](http://doc.sagemath.org/html/en/reference/numerical/sage/numerical/mip.html#sage.numerical.mip.MixedIntegerLinearProgram). I used the default GLPK (didn't change settings)
- I used `alarm()` to set a time limit on each computation.
- I always believed GLPK [not to be interruptible](https://lists.gnu.org/archive/html/help-glpk/2006-04/msg00059.html), so I am not even sure which interruption (either manual or alarm) work on Sage with this function. This may be relevant.
- The memory usage of the process stayed low. It did not stall because the memory got filled and the machine started swapping.
----
Minimal example:
Put this in a source file:
import datetime
i=1
while True:
alarm(60)
try:
dg=digraphs.RandomDirectedGNM(300,750);
fes = dg.feedback_edge_set()
print(len(fes))
except AlarmInterrupt:
print("timeout")
cancel_alarm()
print(i)
print(str(datetime.datetime.now()))
print("\n")
i = i+1
Run it as `sage sourcefile.sage`.
In my last test, it took 291 iterations and ~4-5 hours before it stalled.
It appears to stall only when GLPK is used as the MIP solver (i.e. `feedback_edge_set(solver='GLPK')`, which is also the default). If I use `solver='Coin'` (which needs to be installed first using `sage -i cbc`) then it does not stall. However, the calculation is several times slower with Coin than with GLPK.SzabolcsFri, 11 Oct 2019 09:27:37 +0200https://ask.sagemath.org/question/48270/DiGraph, Latex, and same orientationhttps://ask.sagemath.org/question/48140/digraph-latex-and-same-orientation/Hi
1) is it possible to write in Latex in vertices and edges ?
2) depending on whether I set the value of the Population variable to 1000 or to 100000 it swaps the branches sick and not sick, so is it a possibility to keep the same orientation each time ?
p=1000 ;print "Population : "+str(p)
sr=1/1000 ;print "Sick Rate : "+str(sr)
pfr=95/100 ;print "Positive False Rate : "+str(pfr*100)+'/'+"100"
nfr=40/100 ;print "Negative False Rate : "+str(nfr*100)+'/'+"100"
PbNS=(p-p*sr)*(1-pfr);print "Positive but Not Sick : "+str(round((p-p*sr)*(1-pfr),5))
PaS=((p-(1-sr)*p))*(1-nfr); print "Positive and Sick : ",str(round(((p-(1-sr)*p))*(1-nfr),5))
print "chance to be Sick if Tested Positive : ",PaS/(PbNS+PaS)," about :",round((PaS/(PbNS+PaS)),5)," : ",\
round((PaS/(PbNS+PaS))*100,5),"%"
H0=DiGraph({0:[1,2], 1:[3,4], 2:[5,6]})
#H.set_latex_options(edge_labels=True)
H0.set_edge_label(0, 1, "Not Sick : "+str(p-sr*p)+"/" +str(p))
H0.set_edge_label(0, 2, "Sick: "+str((p-(1-sr)*p))+'/'+str(p))
# not sick branch
H0.set_edge_label(1, 3, "Not Sick \n Tested Negative: "+str(pfr*100)+'/'+"100")
H0.set_edge_label(1, 4, "\n\n\n Not Sick \n Tested Positive: "+str((1-pfr)*100)+'/'+"100")
# sick branch
H0.set_edge_label(2, 5, "Sick Tested Negative: "+str((nfr)*100)+'/'+"100")
H0.set_edge_label(2, 6, "\n\n\n\nSick Tested Positive: \n "+str((1-nfr)*100)+'/'+"100")
H0.relabel({0:str(p)+' Peoples' , 1:str(p-p*sr), 2:str(p-p*(1-sr)), \
3:str(round((p-p*sr)*pfr,5))+' \n Tested Negative and Not Sick', \
4:str(round((p-p*sr)*(1-pfr),5))+' \n Tested positive but Not Sick', \
5:str(round(((p-(1-sr)*p))*(nfr),5))+' \n Tested Negative and Sick', \
6:str(round(((p-(1-sr)*p))*(1-nfr),5))+' \n Tested Positive and Sick'})
H0.show(vertex_color='white', vertex_shape='_',edge_labels=True,figsize=[10,10],layout='tree')
[edited the 2019/10/06, below attempt to solve pb with get_pos(),see David Coudert comment]
it seems that get_pos() does not get something ?:
def ShowTreeH0(p,H0Vert,H0Pos):
sr=1/1000 ;print "Sick Rate : "+str(sr)
pfr=95/100 ;print "Positive False Rate : "+str(pfr*100)+'/'+"100"
nfr=40/100 ;print "Negative False Rate : "+str(nfr*100)+'/'+"100"
PbNS=(p-p*sr)*(1-pfr);print "Positive but Not Sick : "+str(round((p-p*sr)*(1-pfr),5))
PaS=((p-(1-sr)*p))*(1-nfr); print "Positive and Sick : ",str(round(((p-(1-sr)*p))*(1-nfr),5))
print "chance to be Sick if Tested Positive : ",PaS/(PbNS+PaS)," about :",round((PaS/(PbNS+PaS)),5)," : ",\
round((PaS/(PbNS+PaS))*100,5),"%"
H0=DiGraph({0:[1,2], 1:[3,4], 2:[5,6]})
#H.set_latex_options(edge_labels=True)
H0.set_edge_label(0, 1, "Not Sick : "+str(p-sr*p)+"/" +str(p))
H0.set_edge_label(0, 2, "Sick: "+str((p-(1-sr)*p))+'/'+str(p))
# not sick branch
H0.set_edge_label(1, 3, "Not Sick \n Tested Negative: "+str(pfr*100)+'/'+"100")
H0.set_edge_label(1, 4, "\n\n\n Not Sick \n Tested Positive: "+str((1-pfr)*100)+'/'+"100")
# sick branch
H0.set_edge_label(2, 5, "Sick Tested Negative: "+str((nfr)*100)+'/'+"100")
H0.set_edge_label(2, 6, "\n\n\n\nSick Tested Positive: \n "+str((1-nfr)*100)+'/'+"100")
H0.relabel({0:str(p)+' Peoples' , 1:str(p-p*sr), 2:str(p-p*(1-sr)), \
3:str(round((p-p*sr)*pfr,5))+' \n Tested Negative and Not Sick', \
4:str(round((p-p*sr)*(1-pfr),5))+' \n Tested positive but Not Sick', \
5:str(round(((p-(1-sr)*p))*(nfr),5))+' \n Tested Negative and Sick', \
6:str(round(((p-(1-sr)*p))*(1-nfr),5))+' \n Tested Positive and Sick'})
if H0Vert<>None and H0Vert<>None :
print " set vertice and position"
H0.set_vertices(H0Vert)
H0.set_pos(H0Pos)
H0.show(vertex_color='white', vertex_shape='_',edge_labels=True,figsize=[10,10],layout='tree')
return H0.get_vertices(),H0.get_pos()
H0Vert=None
H0Pos=None
p=1000 ;print "Population : "+str(p)
H0Vert,H0Pos=ShowTreeH0(p,H0Vert,H0Pos)
p=100000 ;print "Population : "+str(p)
H0Vert,H0Pos=ShowTreeH0(p,H0Vert,H0Pos)ortolljWed, 02 Oct 2019 12:46:03 +0200https://ask.sagemath.org/question/48140/Random orientation of a graphhttps://ask.sagemath.org/question/42274/random-orientation-of-a-graph/ Is there a command to randomly orient a graph? (no additional edges) not the to_directed commandstandardtrickynessMon, 07 May 2018 02:36:46 +0200https://ask.sagemath.org/question/42274/temp22.sobj is not UTF-8 encodedhttps://ask.sagemath.org/question/41890/temp22sobj-is-not-utf-8-encoded/I get a temp22.sobj is not UTF-8 encoded after trying to open this file
I saved by using save(G.allsimplecycles, 'temp22') what am I doing wrong?
standardtrickynessFri, 06 Apr 2018 19:33:52 +0200https://ask.sagemath.org/question/41890/find embedded subgraphshttps://ask.sagemath.org/question/40140/find-embedded-subgraphs/Hi there,
is there a method to find all embedded copies of a graph in another graph, e.g. given two graphs H and G I want something like:
G = graphs.RandomGNP(10,.3) #some graph
H = Graph({1:[1,2], 2:[1,2]}) #some other graph
list = G.find_subgraphs(H, homeomorphic=False/True)
Where the elements list are all the subgraphs in G which are isomorphic/homeomorphic to H.
If this is too much to ask for, there should be at least a method to return all cycles in G (i.e. closed paths in G with each vertex at most once). Since there exists the Hamiltonian cycle method this one should exist too.
PS: In my case the graph has multiedges (and loops, but we can ignore this here).ctstWed, 13 Dec 2017 16:13:56 +0100https://ask.sagemath.org/question/40140/Iterate over acyclic subdigraphshttps://ask.sagemath.org/question/37611/iterate-over-acyclic-subdigraphs/I have a graph `D`, and would like to iterate over its (maximal) acyclic subdigraphs (not necessarily induced).
My current best bet is to iterate over all permutations of the vertex set of D and, for each one, create an acyclic digraph A by going through each edge of D in turn and adding to A only those edges `ij` where `i` is less than `j` in the current permutation.
But this seems awfully inefficient.
More precisely:
D = DiGraph()
D.add_edges([[0,1],[0,2],[1,2],[1,3],[2,3],[3,4],[4,5],[4,6],[5,6],[5,0],[6,0]])
n = D.num_verts()
for p in Permutations(n):
A = DiGraph()
for e in D.edges():
if p[e[0]] < p[e[1]]:
A.add_edge(p[e[0]] -1,p[e[1]] -1)
# Here A is a maximal acyclic subdigraph of D
do_stuff(A)
Any ideas would be greatly appreciated.tassioWed, 17 May 2017 17:34:11 +0200https://ask.sagemath.org/question/37611/Mixed graphhttps://ask.sagemath.org/question/36938/mixed-graph/ Can we draw mixed graphs( graphs with some edges oriented while some are not) in sagemath?
Deepak SarmaTue, 14 Mar 2017 05:16:39 +0100https://ask.sagemath.org/question/36938/How to get all digraphs with loopshttps://ask.sagemath.org/question/35736/how-to-get-all-digraphs-with-loops/ I'm trying to count all of the directed graphs on n vertices which have fixed in/out degree, up to isomorphism. I would like to allow loops, though not multiple edges. I can't figure out how to tell the digraphs iterrator to include the ones with loops, though i see this is an option in the graphs iterator. I would appreciate suggestions to get around this/explanations why it is not an option.BillyFri, 25 Nov 2016 10:30:55 +0100https://ask.sagemath.org/question/35736/How to get an arbitrary orientation of a graph.https://ask.sagemath.org/question/34711/how-to-get-an-arbitrary-orientation-of-a-graph/I want to know how to get the iterator of all orientations of a given graph G.
Thanks for your valuable timing.
There is another question in the same title, unfortunately that question has irrelevant title.
https://ask.sagemath.org/question/9835/how-to-get-an-arbitrary-orientation-of-a-graph/GA316Sun, 04 Sep 2016 07:59:18 +0200https://ask.sagemath.org/question/34711/Using a lambda expression in digraphs fails for len(G.sinks())?https://ask.sagemath.org/question/33384/using-a-lambda-expression-in-digraphs-fails-for-lengsinks/I'm gathering digraphs that have exactly one sink.
This list comprehension works fine to find the 6 such digraphs of order 3 & put them in a list:
[G for G in digraphs(3) if len(G.sinks()) == 1]
However, I need this to work in a lambda expression to make it part of a larger calculation. However,
digraphs(3,lambda G: len(G.sinks()) == 1)
creates an iterator that returns no entries.
Creating a lamba expression creates the same unexpected zero-length iterator in digraphs, but that same iterator correctly finds the 6 single-sink digraphs if used in a for expression:
sage: property = lambda G: len(G.sinks()) == 1
sage: T = digraphs(3, property)
sage: print(list(T))
[]
sage: for H in digraphs(3):
....: print property(H)
....:
False
False
False
True
False
False
False
False
True
True
True
True
False
True
False
False
So, what's the right way to generate the one-sink digraphs of order N directly in the digraphs() generator?
jim_snydergrantThu, 12 May 2016 17:05:40 +0200https://ask.sagemath.org/question/33384/edge_style for different edges in a multigraphhttps://ask.sagemath.org/question/33228/edge_style-for-different-edges-in-a-multigraph/I'm trying to make a directed multigraph in which different edges have colors/edge styles so that they can be easy read either in color or in black and white.
I can make a graph with different colors:
D = DiGraph(multiedges=True)
var('A,B')
D.add_edge(A,B,'edge1')
D.add_edge(A,B,'edge2')
D.graphplot(color_by_label={'edge1':'green','edge2':'blue'}).show()
I can also make a graph with different styles, but overlayed:
G1 = DiGraph(multiedges=True)
G2 = DiGraph(multiedges=True)
var('A,B')
G1.add_edge(A,B,'edge1')
G2.add_edge(A,B,'edge2')
G1.set_pos({A:[0,0],B:[1,0]})
G2.set_pos({A:[0,0],B:[1,0]})
G = G1.graphplot(color_by_label={'edge1':'green'}, edge_style='--').plot() + G2.graphplot(color_by_label={'edge2':'blue'}, edge_style=':').plot()
G.show(axes=False)
and a very hack-y solution which looks nicer, but still bad:
G1 = DiGraph(multiedges=True)
G2 = DiGraph(multiedges=True)
var('A,B')
G1.add_edge(A,B,'edge1')
G2.add_edge(A,B,'edge2')
G1.add_edge(A,B,'edge2')
G2.add_edge(A,B,'edge1')
G1.set_pos({A:[0,0],B:[1,0]})
G2.set_pos({A:[0,0],B:[1,0]})
G = G1.graphplot(color_by_label={'edge1':'green','edge2':'white'}, edge_style='--').plot() + G2.graphplot(color_by_label={'edge2':'blue','edge1':'white'}, edge_style=':').plot()
G.show(axes=False)
I'd love to be able to have a multigraph where the edges are both different colors and different styles and don't completely overlap, but I'm not seeing a way to do this. Any help is appreciated!mthomasTue, 26 Apr 2016 02:17:33 +0200https://ask.sagemath.org/question/33228/Smart set (database?)https://ask.sagemath.org/question/32217/smart-set-database/Hi,
What I would like is to define a smart hierarchical set (or database) like:
example_set={(0,0,0):[4,[7,11,0]], (0,0,1):[-5,[8,-3,6]], (0,1,0):[4,[7,11,-1]]}
The lefthand side is an hierarchy (a,b,c,d,e,...); the righthand side is some structure [*, [*,*,*,...]] consisting of nested lists. How can I quickly -via a smart design- determine for instance the sum for a higher level? For instance example_set.sum[(0,0)] would yield [4-5, [7,11,0] + [8,-3,6]] and example_set.sum[(0,)] yields [4-5+4, [7,11,0] + [8,-3,6] + [7,11,-1]].
The setting is that we have a few thousand hierarchical elements with unknown depth, but always the same structure on the righthand side. The structure could contain many nested lists with in total several hunderd values (flattened). I like to have (fast) basic operators for the lists within the structure such as addition and index.
Another example.
next_example={(0,0,0):[(5,6)], (0,0,1):[(8,9),(3,4)], (0,1,0):[(2,6)], (0,1,1):[(8,16)]}
(wanted) print next_example.sum[(0, 0)]
[(5, 6), (8, 9), (3, 4)]
I considered to define a class and I looked at [database](http://doc.sagemath.org/html/en/reference/databases/index.html). But that didn't help me much :(
To complicate matters, I would also like to connect hierarchical levels (one-direction). For instance in the first example assume (0,0,0) is connected to (0,1,1). How to store and display such a connection? For connections I looked for instance at [igraph](http://doc.sagemath.org/html/en/reference/graphs/sage/graphs/generic_graph.html#sage.graphs.generic_graph.GenericGraph.igraph_graph). But it isn't clear to me whether it would be helpful in combination with the above mentioned set design.
To summarize: it would be awesome if a routine 'smart_set(n, structure)' would define a n-level hierarchy whereby operations like .sum(input) and .sum.connected(input) and .show_graph() would work.
Suggestions how to move forward in Sage are much appreciated!
Roland
RolandbFri, 15 Jan 2016 21:46:28 +0100https://ask.sagemath.org/question/32217/Dotted and dashed lines in directed graphshttps://ask.sagemath.org/question/31304/dotted-and-dashed-lines-in-directed-graphs/Hi,
I would like to know if it is possible to do (one of) the following with Sage.
Reading
http://doc.sagemath.org/html/en/reference/plotting/sage/graphs/graph_plot.html
I saw that it is possible to draw dashed and dotted lines. Now my questions are
1) Is it possible to produce an output graphic where some edges are dotted and some edges are dashed?
2) Is it possible to force the text in the labels of the vertices, e.g. M2, M4, M1 instead of 0,1,2?
Thanks for the help!
BernFri, 04 Dec 2015 03:39:18 +0100https://ask.sagemath.org/question/31304/How to make pygraphviz and sage compatible?https://ask.sagemath.org/question/31070/how-to-make-pygraphviz-and-sage-compatible/ Hi,
I would like sage to help me when I am working with (un)directed graphs and quivers, and so on. After having played around with various possibilities, I would like to convert some stuff into a string and then let sage print something like a .ps - file that contains an image from dot (or something similar to this).
> Unfortunately, I came across the following issue(s) and have no idea what to do now. With the sage version I installed, there is python 2.x as a delivered package. But it seems that sage complains about python3, what doesn't make sense to me.
Could you help me understand and solve the following:
boehmler@boehmler-X55A:~/Schreibtisch/bb/sage-6.9-x86_64-Linux$ ./sage
┌────────────────────────────────────────────────────────────────────┐
│ SageMath Version 6.9, Release Date: 2015-10-10 │
│ Type "notebook()" for the browser-based notebook interface. │
│ Type "help()" for help. │
└────────────────────────────────────────────────────────────────────┘
sage: import networkx as nx
sage: import matplotlib.pyplot as plt
sage: import matplotlib.image as mpimg
sage: from cStringIO import StringIO
sage: g = nx.dodecahedral_graph()
sage: d = nx.to_pydot(g)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-0d33c400a5cf> in <module>()
----> 1 d = nx.to_pydot(g)
AttributeError: 'module' object has no attribute 'to_pydot'
sage: d = nx.to_agraph(g)
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-7-d9254026fb59> in <module>()
----> 1 d = nx.to_agraph(g)
/home/boehmler/Schreibtisch/bb/sage-6.9-x86_64-Linux/local/lib/python/networkx/drawing/nx_agraph.pyc in
to_agraph(N)
132 raise ImportError('requires pygraphviz ',
133 'http://networkx.lanl.gov/pygraphviz ',
--> 134 '(not available for Python3)')
135 directed=N.is_directed()
136 strict=N.number_of_selfloops()==0 and not N.is_multigraph()
ImportError: ('requires pygraphviz ', 'http://networkx.lanl.gov/pygraphviz ', '(not available for Python3)')
sage:
Exiting Sage (CPU time 0m3.33s, Wall time 56m28.80s).
After typing
boehmler@boehmler-X55A:~/Schreibtisch/bb/sage-6.9-x86_64-Linux$ sudo -H pip install pygraphviz
I get the message
Wall -Wstrict-prototypes -fPIC -I/usr/include/graphviz -I/usr/include/python2.7 -c pygraphviz/graphviz_wrap.c -o build/temp.linux-x86_64-2.7/pygraphviz/graphviz_wrap.o
pygraphviz/graphviz_wrap.c:130:21: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
# include <Python.h>
^
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
----------------------------------------
Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-6yZh3l/pygraphviz/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-a6o8Fg-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-6yZh3l/pygraphviz
in the end. I would be grateful for any hints how to solve / fix this.
Thanks for the help!
BernThu, 26 Nov 2015 03:42:50 +0100https://ask.sagemath.org/question/31070/Counting paths in directed graph with multiedgeshttps://ask.sagemath.org/question/29949/counting-paths-in-directed-graph-with-multiedges/ I would like to could paths in a directed graph with multiedges, where taking a different edge between a given pair of vertices is counted as a new path. For example:
A = DiGraph(multiedges=True)
A.add_edge(1,2,'a')
A.add_edge(1,2,'b')
A.add_edge(2,3,'c')
A.graphplot(edge_labels=True).show()
A.all_paths(1,3)
returns `[[1,2,3]]`. I would like to have it return 2 paths, ideally listed by the edges instead of the vertices, e.g. `[a,c]` and `[b,c]`. Any recommendations?mthomasMon, 12 Oct 2015 22:01:09 +0200https://ask.sagemath.org/question/29949/Partial order with equalitieshttps://ask.sagemath.org/question/29943/partial-order-with-equalities/I am working on a theorem prover related to inequalities. It works in the following way: it assumes, by contradiction, that certain inequalities are true. Then, it proves that there is a cyclic inequality, such as: a<b<c<a, which is a contradiction.
Initially I did this with a poset. Then, thanks to [Nathann](http://ask.sagemath.org/question/29580/adding-relations-to-a-poset/), I switched to using a DiGraph. For each inequality a<b, I add an edge a→b to the graph. Then, I check "digraph.all_simple_cycles()". If it is not empty, i.e. the graph has a directed cycle such as a→b→c→a, this is a contradiction.
Now, I want to add equalities. I want to be able to add a fact such as "d==e". Then, if the graph contains the inequalities "a<d" and "e<a", this is a contradiction.
What is a good way to implement this?Erel Segal-HaleviMon, 12 Oct 2015 20:06:27 +0200https://ask.sagemath.org/question/29943/labelling the edges of posethttps://ask.sagemath.org/question/29820/labelling-the-edges-of-poset/ P = SetPartitions(3)
f = lambda q,p: q in p.refinements()
Po = Poset((P,f))
By using this command I have defined a poset in sage.
Po.show() displays the poset as a directed graph. My question is how to put labels to edges of this graph.
when I try to do so, I try to iterate over the edge set like:
for u in Po.edges() :
but sage saying the error message that poset object has no method edges.
Can any one tell me how to put label for this directed graph.
If we define the corresponding Hasse diagram then we can define label, but I want to do label for the edges in the poset but not for the edges in the Hasse diagram. because when we display the pose it looks nice to see, but when we print Hasse diagram it looks little messy.
Thanks for your valuable time.GA316Thu, 08 Oct 2015 09:26:00 +0200https://ask.sagemath.org/question/29820/call graph of a recursive functionhttps://ask.sagemath.org/question/10420/call-graph-of-a-recursive-function/A colleague asked if I could write some code to show the call graph of a recursive function. I came up with this:
def grafo_llamadas(f):
class G(object):
def __init__(self, f):
self.f=f
self.stack = []
self.g = DiGraph()
def __call__(self, *args):
if self.stack:
sargs = ','.join(str(a) for a in args)
last = ','.join(str(a) for a in self.stack[-1])
if self.g.has_edge(last, sargs):
l = self.g.edge_label(last, sargs)
self.g.set_edge_label(last, sargs, l + 1)
else:
self.g.add_edge(last, sargs, 1)
else:
self.g = DiGraph()
self.stack.append(args)
v = self.f(*args)
self.stack.pop()
return v
def grafo(self):
return self.g
return G(f)
@grafo_llamadas
def fibo(n):
if n<=2:
return 1
else:
return fibo(n-1) + fibo(n-2)
fibo(6)
g = fibo.grafo()
g.show(edge_labels=True)
@grafo_llamadas
def particiones(n, k):
if k == n:
return [[1]*n]
if k == 1:
return [[n]]
if not(0 < k < n):
return []
ls1 = [p+[1] for p in particiones(n-1, k-1)]
ls2 = [[parte+1 for parte in p] for p in particiones(n-k, k)]
return ls1 + ls2
particiones(8,3)
g = particiones.grafo()
g.show(edge_labels=True, figsize=(8,8), vertex_size=500)
Do you like it? Can you improve it?
![call graph of the partitions example](http://wiki.sagemath.org/pics?action=AttachFile&do=get&target=call_graph_partitions.png)pangTue, 06 Aug 2013 13:08:58 +0200https://ask.sagemath.org/question/10420/how do I set label of multiedges graphhttps://ask.sagemath.org/question/25659/how-do-i-set-label-of-multiedges-graph/ Hello,
Let me consider a graph that I often need to use: the graph with one vertex and three loops.
sage: G = DiGraph([(0,0,'a'), (0,0,'b'), (0,0,'c')])
Is there a way to change the labels after the creation? Because
sage: G.set_edge_label(0,0,'d')
Traceback (most recent call last):
...
RuntimeError: Cannot set edge label, since there are multiple edges from 0 to 0.
VincentvdelecroixSat, 31 Jan 2015 21:01:13 +0100https://ask.sagemath.org/question/25659/digraph.diameter() returning +Infinity for some caseshttps://ask.sagemath.org/question/25486/digraphdiameter-returning-infinity-for-some-cases/ I'm running Sage 6.4.1 on OS X (Yosemite). Creating a directed graph with `n` vertices (for any n that I tried) returned `+Infinity`. EG:
sage: digraphs.Path(10).diameter()
+Infinity
or even
sage: digraphs.ButterflyGraph(5).diameter()
+Infinity
However, both of these Path and Butterfly graphs are finite, connected, directed acyclic graphs so their diameter should always be finite.zrathustraSun, 11 Jan 2015 23:14:19 +0100https://ask.sagemath.org/question/25486/Orientation of poset plot in Sage 6.3 vs 6.4https://ask.sagemath.org/question/25192/orientation-of-poset-plot-in-sage-63-vs-64/In older versions of Sage (6.3 and below), plotting a poset (or an acyclic graph with layout = "acyclic") gives a directed graph with arrows pointing up.
However, it seems like in Sage 6.4, the arrows now point down (and the bottom element appears at the top).
Is this a bug? Or are there any options I can tweak to reverse the orientation? I would expect the "correct" behaviour to be the one with the arrows pointing up; the Sage reference on [layout_acyclic](http://www.sagemath.org/doc/reference/graphs/sage/graphs/digraph.html#sage.graphs.digraph.DiGraph.layout_acyclic) seems to agree.
(I noticed the discrepancy while running Sage 6.3 on the [Sage Cell Server](http://sagecell.sagemath.org/) and Sage 6.4 on [Sagemath Cloud](https://cloud.sagemath.com/))
Here's some code you can try:
Poset({0:[2],1:[2],2:[]}).show()ZeWed, 10 Dec 2014 10:07:32 +0100https://ask.sagemath.org/question/25192/plot directed bipartite graphhttps://ask.sagemath.org/question/11353/plot-directed-bipartite-graph/I would like to have a plot of a directed bipartite graph. I can easily get the bipartite graph to look nice or the directed graph. But, I would like a bipartite picture with the directed edges. Here is what I've tried.
G=Graph()
left=['S1','S2','S3']
rt=['T1','T2','T3','T4']
for v in left+rt:
G.add_vertex(v)
for l in left:
for r in rt:
G.add_edge(l,r)
BipartiteGraph(G).to_directed().plot()calc314Fri, 11 Apr 2014 09:50:53 +0200https://ask.sagemath.org/question/11353/.plot() displaying cycle graphs as huge pretzelshttps://ask.sagemath.org/question/10324/plot-displaying-cycle-graphs-as-huge-pretzels/![image description](http://i.imgur.com/U4RU0I5.png)
That big morass of vertices on the left is actually just a single cycle. Is there any way to get Sage to render it more sensibly? I'd use `layout=planar` but as you can see this isn't a simple graph, the 0 vertex is connected to itself.
I suspect this might just be Sage trying to fit the large cycle into a small space, is there some way to tell it what size image to use?JackMFri, 05 Jul 2013 11:01:28 +0200https://ask.sagemath.org/question/10324/motifs and subgraphshttps://ask.sagemath.org/question/10157/motifs-and-subgraphs/I'm counting the number of motifs (3-nodes isophormic class of connected subgraphs) in a random directed network. There are 13 of this. One is, for example S1={1 -> 2, 2 -> 3} and another one S2={1 -> 2, 2 -> 3, 1 -> 3}. They are two distinct motifs, and I wouldn't count a S1 when I actually find S2. The problem is that S1 is in S2, hence subgraph_search() finds a S1 in each S2 and all related functions inherit the problem (wrong counting, wrong iterator...).
Any idea how to resolve this issue? Similar things would happen for 4-nodes motifs and so on...
The code I used goes like:
import numpy
M1 = DiGraph(numpy.array([[0,1,0],[0,0,1],[0,0,0]])) #first motif
M5 = DiGraph(numpy.array([[0,1,1],[0,0,1],[0,0,0]])) #second motif
g = digraphs.RandomDirectedGNP(20,0.1) #a random network
l1 = []
for p in g.subgraph_search_iterator(M1): #search first motif
l1.append(p) #make a list of its occurences
l5 = []
for p in g.subgraph_search_iterator(M5): #the same for the second motif
l5.append(p)
gvdrMon, 27 May 2013 02:02:15 +0200https://ask.sagemath.org/question/10157/epsilon basis for roots (was graph edge labels)https://ask.sagemath.org/question/9969/epsilon-basis-for-roots-was-graph-edge-labels/I need an illustration of some (sub)poset of positive roots. I have a working code that produces correct labels, but they are written as sums of simple roots. I.e. the resulting graph (when exported to LaTeX) has labels such as $\alpha_1 + \alpha_2$. I would like to have these labels in $\epsilon$-notation. I.e. the previous example would read $\epsilon_1 - \epsilon_3$.
RootSystem has an ambient_space method that provides an access epsilon basis, but
1. I am not clear on converting between these two bases
and
2. output to LaTeX should really use $\epsilon_1 - \epsilon_3$ rather than $(1,0,-1)$.vit.tucekMon, 01 Apr 2013 11:43:19 +0200https://ask.sagemath.org/question/9969/code which counts the number of edgeshttps://ask.sagemath.org/question/9952/code-which-counts-the-number-of-edges/How to write a code which counts the number of edges from a one vertex to another vertex in a directed bipartite graph?REKHA BISWALThu, 28 Mar 2013 14:20:38 +0100https://ask.sagemath.org/question/9952/code for bipartite graphshttps://ask.sagemath.org/question/9951/code-for-bipartite-graphs/How to write a code for obtaining a bipartite graph where the edges are indexed by some numbers?e.g if i write the code as D = DiGraph({ 0: [1,2,3], 1: [0,2], 2: [3], 3: [4], 4: [0,5], 5: [1] }) then only graph is coming but the edges are not indexed here.How should i modify this so that edges of the graph will be indexed?REKHA BISWALThu, 28 Mar 2013 13:32:13 +0100https://ask.sagemath.org/question/9951/