Error in Selecting Random Nodes(Python) - python

Here is My Python Code is given below:-
import networkx as nx
import matplotlib.pyplot as plt
from random import choice
g=nx.Graph()
city_set=['Delhi','Lucknow','Indore','Kolkata','Hyderabad','Chennai',
'Tivandrum','Banglore','Pune','Mumbai','Surat','Ahmedabad','Jaipur']
for each in city_set:
g.add_node(each)
costs=[]
value =100
while(value<=2000):
costs.append(value)
value=value+70
while(g.number_of_edges()<24):
c1=choice(g.nodes())
c2=choice(g.nodes())
if c1!=c2 and g.has_edge(c1,c2)==0:
w=choice(costs)
g.add_edge(c1,c2,weight=w)
nx.draw(g,with_labels=1)
plt.show(g)
and while compiling the code I got the error stated below:-
$ python cities.py
Traceback (most recent call last):
File "cities.py", line 22, in <module>
c1=choice(g.nodes())
File "/usr/lib/python2.7/random.py", line 277, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq
is empty
File "/usr/local/lib/python2.7/dist-
packages/networkx/classes/reportviews.py", line 178, in __getitem__
return self._nodes[n]
KeyError: 7
I also created vitual enviourment of Pyhton but again it shows the smae error.
Also, I tried finding some stuff on Google and check for the solution but no one has similar problem like this.

Change
c1=choice(g.nodes())
c2=choice(g.nodes())
into
c1=choice(list(g))
c2=choice(list(g))
should work.
g.nodes() returns a NodeView and not a list of nodes.

import random
import networkx as nx
costs = []
value=100
while(value<=2000):
costs.append(value)
value+=100
print (costs)
while(G.number_of_edges()<16):
c1 = random.choice(list(G.nodes()))
c2 = random.choice(list(G.nodes()))
if c1!=c2 and G.has_edge(c1,c2)==0:
w= random.choice(costs)
G.add_edge(c1,c2,weight = w)
Try this code as there is some error in the syntax of the random shown in the video. I have pasted my code, test it.
G.nodes() needs to return a list but here is returning a NodeView. Hence change G.nodes() to list(G.nodes())

Related

Too many values to unpack? python-radar

I have problem which when i run the code it shows an error:
Traceback (most recent call last):
File "C:\Users\server\PycharmProjects\Publictest2\main.py", line 19, in <module>
Distance = radar.route.distance(Starts, End, modes='transit')
File "C:\Users\server\PycharmProjects\Publictest2\venv\lib\site-packages\radar\endpoints.py", line 612, in distance
(origin_lat, origin_lng) = origin
ValueError: too many values to unpack (expected 2)
My Code:
from radar import RadarClient
import pandas as pd
API_key = 'API'
radar = RadarClient(API_key)
file = pd.read_excel('files')
file['AntGeo'] = Sourced[['Ant_lat', 'Ant_long']].apply(','.join, axis=1)
file['BaseGeo'] = Sourced[['Base_lat', 'Base_long']].apply(','.join, axis=1)
antpoint = file['AntGeo']
basepoint = file['BaseGeo']
for antpoint in antpoint:
dist= radar.route.distance(antpoint , basepoint, modes='transit')
dist= dist['routes'][0]['distance']
dist= dist / 1000
Firstly, your error code does not match your given code sample correctly.
It is apparent you are working with the python library for the Radar API.
Your corresponding line 19 is dist= radar.route.distance(antpoint , basepoint, modes='transit')
From the radar-python 'pypi manual', your route should be referenced as:
## Routing
radar.route.distance(origin=[lat,lng], destination=[lat,lng], modes='car', units='metric')
Without having sight of your dataset, file, one can nonetheless deduce or expect the following:
Your antpoint and basepoint must be a two-item list (or tuple).
For instance, your antpoint ought to have a coordinate like [40.7041029, -73.98706]
See the radar-python manual
line 11 and 13 in your code
file['AntGeo'] = Sourced[['Ant_lat', 'Ant_long']].apply(','.join, axis=1)
file['BaseGeo'] = Sourced[['Base_lat', 'Base_long']].apply(','.join, axis=1)
Your error is occuring at this part:
Distance = radar.route.distance(Starts, End, modes='transit')
(origin_lat, origin_lng) = origin
First of all check the amount of variables that "origin" delivers to you, it's mismatched with the expectation I guess.

Apriori not running

I'm trying to find the correlation between my parameters using apriori but I get this error constantly, I tried using efficient_apriori but it only prints "2"
import pandas as pd
import numpy as np
from apriori import apriori
import matplotlib.pyplot as plt
%matplotlib inline
df = pd.read_csv('D:\\Project\\database\\2-Second Parameters chosen\\Half Year\\HalfYearCombine2.csv',header=None,low_memory=False)
data = []
for i in range(0,15578088):
data.append([str(df.values[i,j])
for j in range(0,14)])
dataset = apriori(data, min_length = 2,
min_support = 0.2, min_confidence = 0.2,
min_lift = 3)
if dataset:
print('not none!')
print(len(dataset))
else:
print('dataset is none!')
The error is:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3296, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-13-de4fe3df3901>", line 5, in <module>
from apriori import apriori
File "C:\ProgramData\Anaconda3\lib\site-packages\apriori.py", line 79
print freqSet-conseq,'-->',conseq,'conf:',conf
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(freqSet-conseq,'-->',conseq,'conf:',conf)?
I don't know why it says missing parentheses in call to print while my print function looks fine?
Thank you.
Notice how "print freqSet-conseq,'-->',conseq,'conf:',conf" doesn't have brackets? That means it was written in python2. You must've installed apriori for python2, but you are using python3.
Install apriori for python3 and try again.
The reason why efficient_apriori prints 2 is because it returns a tuple with (itemsets, rules). To use efficient_apriori, you can do something like:
from efficient_apriori import apriori
itemsets, rules = apriori(data, min_support=min_support, min_confidence=min_confidence)
if rules:
print(len(rules))

Biopython Array Addition Error (Open for all)

Okay. Let me explain the things first. I have used a specific module named Biopython in this code. I am explaining the necessary details to solve the problem if you are not accustomed with the module.
The code is:
#!/usr/bin/python
from Bio.PDB.PDBParser import PDBParser
import numpy as np
parser=PDBParser(PERMISSIVE=1)
structure_id="mode_7"
filename="mode_7.pdb"
structure=parser.get_structure(structure_id, filename)
model1=structure[0]
s=(124,3)
newc=np.zeros(s,dtype=np.float32)
coord=[]
#for chain1 in model1.get_list():
# for residue1 in chain1.get_list():
# ca1=residue1["CA"]
# coord1=ca1.get_coord()
# newc.append(coord1)
for i in range(0,29):
model=structure[i]
for chain in model.get_list():
for residue in chain.get_list():
ca=residue["CA"]
coord.append(ca.get_coord())
newc=np.add(newc,coord)
print newc
print "END"
PDB file is the protein data bank file. The file I'm working with can be downloaded from https://drive.google.com/open?id=0B8oUhqYoEX6YVFJBTGlNZGNBdlk
If you remove the hashes from the first for loop, you'll find that get_coord() returns a (124,3) array with dtype float32. Likewise, the next for loop is supposed to return the same.
It gives out a strange error:
Traceback (most recent call last):
File "./average.py", line 27, in <module>
newc=np.add(newc,coord)
ValueError: operands could not be broadcast together with shapes (124,3) (248,3)
I am absolutely clueless how it manages to make a 248,3 array. I just want to add the array coord over itself. I tried with another modification of the code:
#!/usr/bin/python
from Bio.PDB.PDBParser import PDBParser
import numpy as np
parser=PDBParser(PERMISSIVE=1)
structure_id="mode_7"
filename="mode_7.pdb"
structure=parser.get_structure(structure_id, filename)
model1=structure[0]
s=(124,3)
newc=np.zeros(s,dtype=np.float32)
coord=[]
newc2=[]
#for chain1 in model1.get_list():
# for residue1 in chain1.get_list():
# ca1=residue1["CA"]
# coord1=ca1.get_coord()
# newc.append(coord1)
for i in range(0,29):
model=structure[i]
for chain in model.get_list():
for residue in chain.get_list():
ca=residue["CA"]
coord.append(ca.get_coord())
newc2=np.add(newc,coord)
print newc
print "END"
It gives out the same error. Can you help???
I'm not sure I fully understand what you're doing, but it looks like you need to reset the coords list at the start of every iteration:
for i in range(0,29):
coords = []
model=structure[i]
for chain in model.get_list():
for residue in chain.get_list():
ca=residue["CA"]
coord.append(ca.get_coord())
newc=np.add(newc,coord)
If you keep appending without clearing the list you add 124 items to coords at every iteration of the outer loop. The exception you see is likely raised during the second iteration.

graph-tool - 'NestedBlockState' object has no attribute 'get_nonempty_B'

I am trying to replicate a section of code from the graph-tool cookbook to find the marginal probablity of the number of groups in a graph when using hierarchical partitioning. I however get an error telling me that 'NestedBlockState' object has no attribute 'get_nonempty_B' so presumably I have made a mistake somewhere. Does anybody know where I went wrong?
import graph_tool.all as gt
import cPickle as pickle
g = gt.load_graph('graph_no_multi_reac_type.gt')
gt.remove_parallel_edges(g)
state = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
state = state.copy(sampling=True)
with open('state_mcmc.pkl','wb') as state_pkl:
pickle.dump(state,state_pkl,-1)
print 'equilibrating Markov chain'
gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))
h = np.zeros(g.num_vertices() + 1)
def collect_num_groups(s):
B = s.get_nonempty_B()
h[B] += 1
print 'colleting marginals'
gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
callback=collect_num_groups)
with open('state_ncnc.pkl','wb') as state_pkl:
pickle.dump(state,state_pkl,-1)
with open('hist.pkl','wb') as h_pkl:
pickle.dump(h,h_pkl,-1)
The error I get looks as follows:
Traceback (most recent call last):
File "num_groups_marg_prob.py", line 42, in <module>
gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
File "/usr/lib/python2.7/dist-packages/graph_tool/inference/mcmc.py", line 172, in mcmc_equilibrate
extra = callback(state)
File "num_groups_marg_prob.py", line 35, in collect_num_groups
def collect_num_groups(s):
AttributeError: 'NestedBlockState' object has no attribute 'get_nonempty_B'
Quoting from an answer from the graph-tool mailing list:
"The error message is clear. This attribute belongs to BlockState, not
NestedBlockState. What you wish to do is:
s.levels[0].get_nonempty_B()
"
http://main-discussion-list-for-the-graph-tool-project.982480.n3.nabble.com/self-state-couple-state-state-state-entropy-args-Python-argument-types-did-not-match-C-signature-td4026975.html

Error: cannot perform reduce with flexible type

I'm trying to plot a histogram, but I'm keep getting this error;
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
plt.hist(a)
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2827, in hist
stacked=stacked, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 8312, in hist
xmin = min(xmin, xi.min())
File "/usr/lib/python2.7/dist-packages/numpy/core/_methods.py", line 21, in _amin
out=out, keepdims=keepdims)
TypeError: cannot perform reduce with flexible type
I'm very new to python and what I'm trying to do is this;
import numpy, matplotlib.pyplot
line = " "
a = []
b = []
c = []
alpha = []
beta = []
gama = []
while x.readline():
line = x.readline()
a.append(line[16:23])
b.append(line[25:32])
c.append(line[27:34])
alpha.append(line[40:47])
beta.append(line[49:54])
gama.append(line[56:63])
pyplot.hist(a)'
when ever I run this piece of code I'm getting that error. Where did I go wrong? I really appreciate a help
It looks like you are attempting to draw the histogram based on strings, rather than on numbers. Try something like this instead:
from matplotlib import pyplot
import random
# generate a series of numbers
a = [random.randint(1, 10) for _ in xrange(100)]
# generate a series of strings that look like numbers
b = [str(n) for n in a]
# try to create histograms of the data
pyplot.hist(a) # it produces a histogram (approximately flat, as expected)
pyplot.hist(b) # produces the error as you reported.
In general it is better to use a pre-written library to read data from external files (see e.g., numpy's genfromtxt or the csv module).
But at the very least, you likely need to treat the data you have read in as numerical, since readline returns strings. For instance:
for line in f.read():
fields = line.strip().split()
nums = [int(field) for field in fields]
now nums gives you a list of integers from that row.

Categories