AttributeError when trying to do a block partition with graph-tool - python

I am getting this error:
AttributeError: 'list' object has no attribute 'clear'
when trying to execute the example at this page
The example is:
>>> g = gt.collection.data["power"]
>>> bstack, mdl = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
>>> t = gt.get_hierarchy_tree(bstack)[0]
>>> tpos = pos = gt.radial_tree_layout(t, t.vertex(t.num_vertices() - 1), weighted=True)
>>> cts = gt.get_hierarchy_control_points(g, t, tpos)
>>> pos = g.own_property(tpos)
>>> b = bstack[0].vp["b"]
>>> gt.graph_draw(g, pos=pos, vertex_fill_color=b, vertex_shape=b, edge_control_points=cts,
... edge_color=[0, 0, 0, 0.3], vertex_anchor=0, output="power_nested_mdl.pdf")
<...>
and it gives me the exception when running the line:
>>> bstack, mdl = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
Any clue?
Thanks

list.clear() is not in Python 2, only in Python 3. The example runs without problem in Python 3.
Anyway, graph-tool is supposed to work on Python 2.7 and above, so this might as well be reported as a bug.

Related

Update edge attributes of a graph with networkx

I have the following graph with the edge attributes:
import networkx as nx
import random
G=nx.DiGraph()
G.add_edge('x','a', dependency=0.4)
G.add_edge('x','b', dependency=0.6)
G.add_edge('a','c', dependency=1)
G.add_edge('b','c', dependency=0.3)
G.add_edge('b','d', dependency=0.7)
G.add_edge('d','e', dependency=1)
G.add_edge('c','y', dependency=1)
G.add_edge('e','y', dependency=1)
After setting the structure of my graph, I will sample three different edge attributes and multiply them with a random number as followed:
for i in range(3):
sampled_edge = random.sample(G.edges, 1)
print(sampled_edge)
sampled_edge_with_random_number = G.edges[sampled_edge[0]]['dependency'] * random.uniform(0,1)
print(sampled_edge_with_random_number)
Now I want to update the initial graph attribute with the new sampled graph attribute so it would look something like this. The algorithm should look for the same edge attribute in the structure and update the dependency value:
for i in G.edges:
if i == sampled_edge:
i['dependency'] = sampled_edge_with_random_number
Can someone help me with this?
You can just access the attribute to update and change it
>>> G=nx.DiGraph()
>>> G.add_edge('x','a', dependency=0.4)
>>> G['x']['a']
{'dependency': 0.4}
>>> G['x']['a']['dependency'] = 10
>>> G['x']['a']
{'dependency': 10}
Another approach is nx.set_edge_attributes
>>> sampled_edge = ('x', 'a')
>>> new_val = 42
>>> nx.set_edge_attributes(G, {sampled_edge:{'dependency':new_val}})
>>> G['x']['a']['dependency']
42
where ('x','a') is your sampled_edge.

Getting a "TypeError: '<' not supported between instances of 'int' and 'str'", without even using the '<' character

I am trying to check if a condition is true, of which all the parts are integers and I am not using any '<' signs, but still I get this error. I am really confused...
Code:
import sys
packets, packets_x, packets_y, packets_z = [], [], [], []
for packet in sys.stdin:
if packet == "\n":
break
packets.append(packet[:-1])
packets_x.append(int(list(packet.split())[0]))
packets_y.append(int(list(packet.split())[1]))
packets_z.append(int(list(packet.split())[2]))
while True:
for number in range(len(packets)):
if int(sorted(packets_x)[0]) == packets_x[number] and int(sorted(packets_y)[0]) == packets_y[number] and int(sorted(packets_z)[0]) == packets_z[number]:
print(packets[number])
packets[number] = "a"
packets_x[number] = "a"
packets_y[number] = "a"
packets_y[number] = "a"
if packets.count("a") == len(packets) + 1:
break
Input I used:
6220 1 10 Because he's the hero Gotham deserves,
6210 1 10 Asd
<ENTER>
<ENTER> - Click enter, don't actually type that.
Type the inputs line by line, don't type them all at once.
Error I get:
if int(sorted(packets_x)[0]) == packets_x[number] and int(sorted(packets_y)[0]) == packets_y[number] and int(sorted(packets_z)[0]) == packets_z[number]:
TypeError: '<' not supported between instances of 'str' and 'int'
Could this be some kind of a Python error?
The issue seems to be in Python3, but not in Python2.7
And the solution for python3 can be:
>>> a = [1,2,3,'bla',4,5,None]
Python2.7:
>>> sorted(a)
[None, 1, 2, 3, 4, 'bla']
Python3:
>>> sorted(a)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'
Can be fixed with:
>>> sorted(a, key=lambda x: str(x))
[1, 2, 3, 4, 5, None, 'bla']
The if-statement doesn't use the '<' sign, but the sorted() function does!
I am getting the error because the sorted() function can't sort different types of variables.
If we try sorted([1, "a string"]), you will get the error, but if we try sorted([5, 2]), it will work.
This solution was written based on Mark Dickinson's and Barmar's comments.

load_earley not available in nltk 3.0

I am trying to reproduce an example from the NLTK text book - http://www.ling.helsinki.fi/kit/2009s/clt231/NLTK/book/ch10-AnalyzingTheMeaningOfSentences.html
However, while running this example :
>>> from nltk.parse import load_earley
>>> cp = load_earley('grammars/book_grammars/sql0.fcfg')
>>> query = 'What cities are located in China'
>>> trees = cp.nbest_parse(query.split())
>>> answer = trees[0].node['sem']
>>> q = ' '.join(answer)
>>> print q
I am getting the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name load_earley
Is load_earley discontinued? If so, I am not able to find the replacement for it. Kindly help
I believe that is the case, I ran into the same issue. That course uses NLTK version 2.0. Also:
The material presented in this book assumes that you are using Python version 2.4 or 2.5
Never mind. I got the updated course work -> http://www.nltk.org/book/ch10.html
The above code translates into
>>>from nltk import load_parser
>>> cp = load_parser('grammars/book_grammars/sql0.fcfg')
>>> query = 'What cities are located in China'
>>> trees = list(cp.parse(query.split()))
>>> answer = trees[0].label()['SEM']
>>> answer = [s for s in answer if s]
>>> q = ' '.join(answer)
>>> print(q)
load_earley is replaced by load_parser
>>> trees = cp.nbest_parse(query.split())
>>> answer = trees[0].node['sem']
is replaced by
>>> trees = list(cp.parse(query.split()))
>>> answer = trees[0].label()['SEM']
>>> answer = [s for s in answer if s]

Text Merging - How to do this in Python? (R source)

I have tried several methods but none worked to translate it to Python, specially because I have this error:
'str' object does not support item assignment
R can do the same with the following code:
f<-0
text<- c("foo", "btextr", "cool", "monsttex")
for (i in 1:length(text)){
f[i]<-paste(text[i],text[i+1], sep = "_")
}
f
The output is:
"foo_btextr" "btextr_cool" "cool_monsttex" "monsttex_NA"
I would appreciate so much if you can help me to do the same for Python. Thanks.
In R your output would have been (next time please put this in the question):
> f
[1] "foo_btextr" "btextr_cool" "cool_monsttex" "monsttex_NA"
In Python strings are immutable. So you'll need to create new strings, e.g.:
new_strings = []
text = ['foo', 'btextr', 'cool', 'monsttex']
for i,t in enumerate(text):
try:
new_strings.append(text[i] + '_' + text[i+1])
except IndexError:
new_strings.append(text[i] + '_NA')
Which results in:
>>> new_strings
['foo_btextr', 'btextr_cool', 'cool_monsttex', 'monsttex_NA']
this works:
>>> from itertools import zip_longest
>>>
>>> f = ['foo', 'btextr', 'cool', 'monsttex']
>>>
>>> ['_'.join(i) for i in zip_longest(f, f[1:], fillvalue='NA')]
['foo_btextr', 'btextr_cool', 'cool_monsttex', 'monsttex_NA']

Python findall in a string

There must be an easier way or function to do this code here:
#!/usr/bin/env python
string = "test [*string*] test [*st[ *ring*] test"
points = []
result = string.find("[*")
new_string = string[result+1:]
while result != -1:
points.append(result)
new_string = new_string[result+1:]
result = new_string.find("[*")
print points
Any ideas?
import re
string = "test [*string*] test [*st[ *ring*] test"
points = [m.start() for m in re.finditer('\[', string)]
It looks like you're trying to get the indices in the string that match '[*'...
indices=[i for i in range(len(string)-1) if string[i:i+2] == '[*']
But this output is different than what your code will produce. Can you verify that your code does what you want?
Also note that string is the name of a python module in the standard library -- while it isn't used very often, it's probably a good idea to avoid using it as a variable name. (don't use str either)
>>> indexes = lambda str_, pattern: reduce(
... lambda acc, x: acc + [acc[-1] + len(x) + len(pattern)],
... str_.split(pattern), [-len(pattern)])[1:-1]
>>> indexes('123(456(', '(')
[3, 7]
>>> indexes('', 'x')
[]
>>> indexes("test [*string*] test [*st[ *ring*] test", '[*')
[5, 21]
>>> indexes('1231231','1')
[0, 3, 6]

Categories

Resources