Can't access attributes of pydot graph in networkx graph after conversion
My task is to generate a graph from a dot file (using pydot) and then convert the same as networkx graph. The problem that I faced was that the attributes of Graph (as I have given in the .dot file) is not present in the networkx graph. I also used read_dot() function which is again an error. My code is successfully working to visualize graphs but not its attribs.
My code is:
import pydot
import networkx as nx
(graph,) = pydot.graph_from_dot_file('1.dot')
G = nx.nx_pydot.from_pydot(graph)
nx.get_node_attributes(G,'1')
My output is {}
Pls help me to fix the problem
Thanks from Mathan :)
See also questions close to this topic

psychopy  error when trying to set nonscalar variable via conditions file
Summary
In PsychoPy v1.85.1 I am configuring the 'polygon' stimuli object. I am trying to set the height attribute via a csv conditions file. I get an error message saying "Invalid parameter. Single numbers are not accepted"
Details
PsychoPy v1.85.1 on Windows.
In the polygon's popup UI 'size' box I enter: $height
In the csvfile I have a 'height' column. Each row has values such as: (1.5, 0)
PsychoPy gives the error message:
File "C:\Program Files (x86)\PsychoPy2\lib\sitepackages\psychopy \visual\basevisual.py", line 1312, in pos self.__dict__['pos'] = val2array(value, False, False) File "C:\Program Files (x86)\PsychoPy2\lib\sitepackages\psychopy\tools\arraytools.py", line 176, in val2array raise ValueError(msg % str(length)) ValueError: Invalid parameter. Single numbers are not accepted. Should be tuple/list/array of length 2
Troubleshooting  Misc
 Scalar variables work in other csv columns work fine so PsychoPy connects with the csvfile.
 Tried xlsx format.
 Tried entering without parenthesis and with square bracket parenthesis
Troubleshooting  Running the code outside of PsychoPy
I go to the arraytools.py file and find the relevant code snippet. I paste it into a Python notebook (although it is python 3.3) and add some print rows for debugging:
# Copied code snippet from # C:\Program Files (x86)\PsychoPy2\lib\sitepackages\psychopy\tools\arraytools.py import numpy def val2array(value, withNone=True, withScalar=True, length=2): """Helper function: converts different input to a numpy array. Raises informative error messages if input is invalid. withNone: True/False. should 'None' be passed? withScalar: True/False. is a scalar an accepted input? Will be converted to array of this scalar length: False / 2 / 3. Number of elements input should have or be converted to. Might be False (do not accept arrays or convert to such) """ if value is None: if withNone: return None else: raise ValueError('Invalid parameter. None is not accepted as ' 'value.') value = numpy.array(value, float) print ("value:", value) #I ADDED print ("value.shape:", value.shape) #I ADDED print ("numpy.product(value.shape):", numpy.product(value.shape)) #I ADDED if numpy.product(value.shape) == 1: #MY COMMENT: WHY DOES THIS EVALUTE TRUE? if withScalar: # e.g. 5 becomes array([5.0, 5.0, 5.0]) for length=3 return numpy.repeat(value, length) else: msg = ('Invalid parameter. Single numbers are not accepted. ' 'Should be tuple/list/array of length %s') raise ValueError(msg % str(length)) elif value.shape[1] == length: return numpy.array(value, float) else: msg = 'Invalid parameter. Should be length %s but got length %s.' raise ValueError(msg % (str(length), str(len(value))))
I test it by entering a value and then run the function.
# Run the function value = (1.5,0.0) val2array(value, False, False, length =2)
Results below. Seems to work fine:
value: [ 1.5 0. ] value.shape: (2,) numpy.product(value.shape): 2 Out: array([ 1.5, 0. ])
Any idea what I am doing wrong?

pretty printing sympy array
I am trying to create 2dim arrays in sympy but getting error. Here is my code:
from sympy import * from sympy.tensor.array import Array init_printing() x = symbols('x') vec1 = Array([ [x,x**2],[x**3,x**4] ]) print(vec1)
I am getting output as
[[x, x**2], [x**3, x**4]]
But I wanted to get output as pretty printed array like shown on http://docs.sympy.org/latest/tutorial/printing.html. How can I do that? I am using python 3.6 running on Spyder 3.4 on Windows.

Creating a column in a pandas dataframe containing the number elements in the group (groupby)
I'm analysis a large dataset containing a variable number of observations per subject (ranging from 1 occurrence to 26 occurrences...). As I would need to analyse the time between events, the subjects with only one occurrence are noninformative.
Previously, while working in Stata I would assign a variable (called eg. total) using Stata code:
by idnummer, sort: gen total=_N
In this way every line/subject has a variable 'total' and I could eliminate all subjects total=1.
I have been trying with agg functions and with size but I end up with 'NaN'...
PS: using the "similar questions" on the side I have found the answer to my own question....
df['total'] = df.groupby('idnummer')['sequence'].transform('max')

NetworkX asymmetric weights
Im using networkX to calcute all shortest path between endpoints.
In a example topology like graph1, in which weights are not symetric between R1 <> R2, I would expect to see ONLY one shortest path from R1 to R3, however I'm seeing two (see below). My goal is to replicate what protocols like OSPF or ISIS does.
is there any way to achieve that ? (metrics/weights cannot be modified, are obtained directly from routers)
Example:
>>> from networkx import nx >>> graph1 = { ... ... 'R1':{'R2':{'weight':50000},'R3':{'weight':200}}, ... 'R2':{'R1':{'weight':100},'R3':{'weight':100}}, ... 'R3':{'R1':{'weight':200},'R2':{'weight':100}} ... } >>> network_graph = nx.from_dict_of_dicts(graph1) >>> print [p for p in nx.all_shortest_paths(network_graph,source='R1',target='R3', weight='weight')] [['R1', 'R3'], ['R1', 'R2', 'R3']]

Python Networkx : find all edges for a given path in a multiDiGraph
In my multi directed graph, I would like to find all the (simple) paths possible between 2 nodes. I manage to get all the path, but cannot distinguish which edge (given that it's a multiDiGraph) the source node takes to reach the target node.
For example I have A>B>C where there are multiple edges in parallele between (A,B) and (B,C). If I have let say 5 parallele edges for A>B and 2 parallele edges for B>C, the all_simple_path(graph, source='A', target='C') will return in total 7 paths, all are of course A>B>C
When using get_edge_data(), it returns ALL the parallele edge between each node. But what I want is to be able to list all the combinations edges taken by the specified nodes in the path.
Thank you !

how to read from pandas dataframe with networkx versions before 2.0
I need to generate a networkx graph with arc attributes from a pandas dataframe. In networkx version 2.0, I am aware of the from_pandas_dataframe function and I did what I wanted as follows:
graph=nx.from_pandas_dataframe(df_t, 'node2', 'node1', ['Transit Time','arctype','node1type','node2type','cpt'],nx.DiGraph())
However at the moment I have to use networkx 1.9., which does not have from_pandas_dataframe function. I was wondering how I can do that. Any help will be appreciated.
P.S. I am deploying my application in a framework which has only networkx v1.9. I don't have time to upgrade the networkx version in the framework so I am trying to change my own code.

How can I scale bigger graphs while using pydot for creating it
I was trying to visualize a large graph with pydot. The graph has 3180 nodes and 36735 edges. When I try to generate the .png ,I got a message like:
dot: graph is too large for cairorenderer bitmaps. Scaling by 0.265185 to fit
It's generating the .png file without any clarity...I have also tried to generate it's pdf. The result is same. How can I overcome this situation? There is another tool that can do this?

How to get graph coordinates (layout) with networkx using graphviz?
I have a graph with 3000 nodes. I am trying to use the pydot layout engines to find a more pleasing layout than the default networkx layout
layout = nx.fruchterman_reingold_layout(G)
The example from neteorkx doc
G_tst = nx.complete_graph(4) pos = nx.nx_pydot.pydot_layout(G_tst ) pos = nx.nx_pydot.pydot_layout(G_tst , prog='dot')
works just fine. However when I use my own graph
pos = nx.nx_pydot.pydot_layout(G)
I get aType Error
where it claims thatG
has the attibutename
more than once. TypeError Traceback (most recent call last) <ipythoninput721326868cc786> in <module>() 1 > 2 pos = nx.nx_pydot.pydot_layout(G) 3 nx.draw(G, pos=pos) C:\Anaconda3\lib\sitepackages\networkx\drawing\nx_pydot.py in pydot_layout(G, prog, root, **kwds) 261 """ 262 import pydotplus > 263 P=to_pydot(G) 264 if root is not None : 265 P.set("root",make_str(root)) C:\Anaconda3\lib\sitepackages\networkx\drawing\nx_pydot.py in to_pydot(N, strict) 200 for n,nodedata in N.nodes_iter(data=True): 201 str_nodedata=dict((k,make_str(v)) for k,v in nodedata.items()) > 202 p=pydotplus.Node(make_str(n),**str_nodedata) 203 P.add_node(p) 204 TypeError: __init__() got multiple values for argument 'name'
Here are the
node attributes
I do have:`G.add_node(G.number_of_nodes(), name=endNode.endWord, # string teaching_text=endNode.tt_corpus, # string definition=endNode.domainDef, # string search_string=endNode.searchKey_obj.search_key_str, name_len = len(endNode.endWord))` #int

Delete a Node in Graphviz
Is there a nice way to delete a node from a graph? I am using graphviz library to create nodes but they don't have a function to delete a node
Purpose: [I want to show that a node moved from a cluster to another one, but I can't find a way to delete it from the old cluster and I can't add it to the new one because of duplicate name]
I got an advice to use pydotplus library but objects from graphviz and pydotplus can't be added in one graph as a subgraph , so if you confirm there is no solution using Graphviz I have to change the whole code