Giter Club home page Giter Club logo

networkx's Introduction

NetworkX

image

image

image

NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks.

Simple example

Find the shortest path between two nodes in an undirected graph:

>>> import networkx as nx
>>> G = nx.Graph()
>>> G.add_edge("A", "B", weight=4)
>>> G.add_edge("B", "D", weight=2)
>>> G.add_edge("A", "C", weight=3)
>>> G.add_edge("C", "D", weight=4)
>>> nx.shortest_path(G, "A", "D", weight="weight")
['A', 'B', 'D']

Install

Install the latest version of NetworkX:

$ pip install networkx

Install with all optional dependencies:

$ pip install networkx[all]

For additional details, please see INSTALL.rst.

Bugs

Please report any bugs that you find here. Or, even better, fork the repository on GitHub and create a pull request (PR). We welcome all changes, big or small, and we will help you make the PR if you are new to git (just ask on the issue and/or see CONTRIBUTING.rst).

License

Released under the 3-Clause BSD license (see LICENSE.txt):

Copyright (C) 2004-2024 NetworkX Developers
Aric Hagberg <[email protected]>
Dan Schult <[email protected]>
Pieter Swart <[email protected]>

networkx's People

Contributors

aweinstein avatar bjedwards avatar branliu0 avatar chebee7i avatar dschult avatar eriknw avatar hagberg avatar jarrodmillman avatar jfinkels avatar jg-you avatar jtorrents avatar k-karakatsanis avatar loicseguin avatar lukong123 avatar mcognetta avatar michael-e-rose avatar mriduls avatar navyagarwal avatar paulitapb avatar progval avatar qudirah avatar rossbar avatar sanketdg avatar schefflera-arboricola avatar stefanv avatar thegreathippo avatar theosotr avatar vanshika230 avatar wuhaochen avatar ysitu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

networkx's Issues

configuration model should return pseudograph (XGraph type) (migrated from Trac #20)

Original ticket https://networkx.lanl.gov/trac/ticket/20
Reported 2005-10-25 by @hagberg, assigned to @hagberg.

The configuration model source:networkx/trunk/networkx/generators/degree_seq.py#14
uses a Graph() datatype that doesn't allow for parallel edges or self loops.
This is the typical model used in the physics community. Using instead the
XGraph(selfloops=True,multiedges=True) type will give a graph with the
exact degree sequence requested - the parallel edges and self loops can
be removed if desired.

G(w) generator? (migrated from Trac #49)

Original ticket https://networkx.lanl.gov/trac/ticket/49
Reported 2006-07-19 by rmrichardson, assigned to @hagberg.

I'd like to request a new random graph generator. I'd like a generator which, given a degree sequence w, returns a G(w)
random graph. For reference, see the paper:
Chung, Fan and L. Lu. Connected components in random graphs with given expected degree sequences.
Annals of Combinatorics 6 (2002), 125-145.

Let me know if any assistance is necessary.

Please include example of generating graph and writing it to a file. (migrated from Trac #30)

Original ticket https://networkx.lanl.gov/trac/ticket/30
Reported 2006-03-18 by list, assigned to @hagberg.

I would like to use pygraphviz to generate graphs and display them through a webserver. An example of writing a pygraphviz generated graph to a file-like object (a real file or say StringIO) in some format (say PNG, JPG, or SVG) would be helpful.
Or is rendering the graph ouside the scope of pygraphviz?

TIA

neighbors use of with_labels doesn't match docs or "theme" of with_labels elsewhere. (migrated from Trac #38)

Original ticket https://networkx.lanl.gov/trac/ticket/38
Reported 2006-05-16 by @dschult, assigned to @hagberg.

neighbors() returns a list of tuples when with_labels=True. The theme for
the package is to return a dict when with_labels=True (at least that is my
understanding). The iterators return tuples when with_labels=True.
Perhaps the whole with_labels API needs to be revisited
to make a consistent, or at least a more clear, specification of its intent.
Personally, I like the as_dict/as_list/as_set keyword argument system,
but it has been rightfuly criticized as being to oriented to the python
language as opposed to the graph metaphor. Another approach would be
to always return a specific form that has enough info to let users convert
to any other data structure. i.e. neighbors(v) always returns a list, degree(v)
returns a single value and degree() returns a dict (or listof tuples if that is
preferred.) neighbors_iter(v) would iterate through the neighbors and not
have with_labels as an option.

Erdos-Renyi random graph generates complete graph when it should not (migrated from Trac #48)

Original ticket https://networkx.lanl.gov/trac/ticket/48
Reported 2006-06-20 by ddiamantaras, assigned to @hagberg.

On a Windows XP machine, my co-author stumbled on this problem:

When the following code is run,

'''
net_zero = NX.erdos_renyi_graph(n,0.25_n_(n-1))
'''

the result is the complete graph. (n has been defined earlier in the code, as a small integer, 7 or 10.)

Setup: Windows XP SP2, Python 2.3.5 (Enthought edition build 1078), networkx 0.29. On Fedora Core 5 on my machine, this works correctly (Python 2.4.1).

Should be able to choose Numeric or numpy (migrated from Trac #33)

Original ticket https://networkx.lanl.gov/trac/ticket/33
Reported 2006-04-04 by @dschult, assigned to @dschult.

I put a system in for using numpy or Numeric in the spectrum
and threshold modules, but it uses numpy if both are available.
Users ought to be able to use either numpy or Numeric because
some packages don't support numpy yet. I'm not if it is worth
putting a lot of effort into this since Numeric will presumably
be phased out, but if I have to overcome it anyway......

connected_component_subgraphs does not work properly (migrated from Trac #37)

Original ticket https://networkx.lanl.gov/trac/ticket/37
Reported 2006-05-16 by trac user MishaS, assigned to @hagberg.

I was using networkx 0.24 for quite some time and today decided to upgrade. My script (build order deductor :)) is not working properly any more. After investigation it turned out that connected_component_subgraphs does not work as it was previously. After further investigation I found that there were substantial changes in this and related function.

The attached script produced the following result with networkx 0.24:


[('gtk+2.0', 'gedit'), ('glib2.0', 'gtk+2.0'), ('glib2.0', 'gedit')]
cc: 1

[('gtk+2.0', 'gedit'), ('glib2.0', 'gtk+2.0'), ('glib2.0', 'gedit')]

[('0', '1'), ('2', '1'), ('2', '0')]
cc: 1

[('0', '1'), ('2', '1'), ('2', '0')]

[(0, 1), (2, 0), (2, 1)]
cc: 1
[(0, 1), (2, 0), (2, 1)]

And it produces the following result with networkx 0.29 (btw, I'd put the version 0.29 in the ticket, but it's not available):


[('gtk+2.0', 'gedit'), ('glib2.0', 'gtk+2.0'), ('glib2.0', 'gedit')]
cc: 2
[('gtk+2.0', 'gedit'), ('glib2.0', 'gtk+2.0'), ('glib2.0', 'gedit')]

[('gtk+2.0', 'gedit')]

[('0', '1'), ('2', '1'), ('2', '0')]
cc: 3
[('0', '1'), ('2', '1'), ('2', '0')]
[('0', '1')]

[]

[(0, 1), (2, 0), (2, 1)]
cc: 2
[(0, 1), (2, 0), (2, 1)]
[(0, 1)]

Kind Regards

Misha

add node and edge type mapping to read_* routines in io.py (migrated from Trac #23)

Original ticket https://networkx.lanl.gov/trac/ticket/23
Reported 2006-01-26 by @hagberg, assigned to @hagberg.

Add functions to allow node and edge mappings to other types when reading from
an ascii file. Currently all you can get are strings. Make strings the default
and allow for integers, etc. Suggestion by Chris Myers.

Add gz and bz2 file handling.

Don't store both edge copies in adjacency list formats.

io.py functions should work for XGraph types with edge data and with multiedges and self loops

XGraph and XDiGraph multiedges=True reports exception for delete_edge with nonexistent edge (migrated from Trac #29)

Original ticket https://networkx.lanl.gov/trac/ticket/29
Reported 2006-03-06 by @hagberg, assigned to @hagberg.

'''

G=XDiGraph(multiedges=True)
G.add_edge(1,2,'blue')
G.delete_edge(1,2)
G=XDiGraph(multiedges=True)
Traceback (most recent call last):
File "", line 1, in ?
File "/u/aric/networkx/networkx/xbase.py", line 560, in delete_edge
self.adj[n1][n2].remove(x) # remove the edge item from list
'''

Should ignore silently.

digraph drawing with pylab fails if using Numeric (migrated from Trac #45)

Original ticket https://networkx.lanl.gov/trac/ticket/45
Reported 2006-06-02 by @hagberg, assigned to @hagberg.

drawing digraphs with nx_pylab using Numeric fails
(works with numpy)

'''

import networkx as NX
g = NX.DiGraph()
g.add_edge('b','g')
g.add_edge('b','d')
g.add_edge('d','f')
NX.draw(g)
Traceback (most recent call last):
File "", line 1, in ?
File "C:\Program
Files\Python24\Lib\site-packages\networkx\drawing\nx_pylab.py
", line 120, in draw
draw_networkx(G, pos, ax=ax, with_labels=with_labels, **kwds)
File "C:\Program
Files\Python24\Lib\site-packages\networkx\drawing\nx_pylab.py
", line 163, in draw_networkx
edge_collection=draw_networkx_edges(G, pos, ax=ax, **kwds)
File "C:\Program
Files\Python24\Lib\site-packages\networkx\drawing\nx_pylab.py
", line 289, in draw_networkx_edges
d=sqrt((x2-x1)**2+(y2-y1)**2)
ValueError: math domain error
'''

documentation typo (migrated from Trac #53)

Original ticket https://networkx.lanl.gov/trac/ticket/53
Reported 2006-08-04 by unknown, assigned to @hagberg.

base.py line 58

will add the edge (n1,n2,None), and G.delete_node(n1,n2) will attempt

should be

will add the edge (n1,n2,None), and G.delete_edge(n1,n2) will attempt

xbase.py line 108

G.delete_node(n1,n2) will attempt to delete the edge (n1,n2,None).

should be

G.delete_edge(n1,n2) will attempt to delete the edge (n1,n2,None).

I could be mistaken, but this seems right.

DOT properties (migrated from Trac #51)

Original ticket https://networkx.lanl.gov/trac/ticket/51
Reported 2006-08-02 by rmrichardson, assigned to @hagberg.

It would be very nice to have a standard way of accessing the attributes contained in a DOT file and still
work with NetworkX graphs. Right now, the code that convertes Agraphs -> NWX ignores the attributes. This is a pain, since then I need to either dump the attributes to a dictionary manually or keep both the Agraph and NWX graph data around.
I noticed that the code is marked with this as an eventual improvement--for interoperability with DOT I think this should be a priority.

Thanks!

shortest path length in paths.py fails with python2.3 (migrated from Trac #31)

Original ticket https://networkx.lanl.gov/trac/ticket/31
Reported 2006-03-27 by @hagberg, assigned to @hagberg.

'''

from networkx import *
g = barabasi_albert_graph(3000,5)
g.order()
3000
g.size()
14868
diameter(g)
Traceback (most recent call last):
File "", line 1, in ?
File "/usr/lib/python2.3/site-packages/networkx/paths.py", line 52, in diameter
File "/usr/lib/python2.3/site-packages/networkx/paths.py", line 36, in eccentricity
File "/usr/lib/python2.3/site-packages/networkx/paths.py", line 101, in shortest_path_length
AttributeError: keys
'''

bug in "reverse" (migrated from Trac #9)

Original ticket https://networkx.lanl.gov/trac/ticket/9
Reported 2005-08-11 by zeph, assigned to @hagberg.

I don't know python so maybe my version of python (2.3.4) is at fault and not your code. In any case, the only way I got the package to import properly was to comment out the "reverse()" code in base.py.
Here's the error report I originally got:

import networkx as NX
Traceback (most recent call last):
File "", line 1, in ?
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/networkx/init.py", line 57, in ?
from base import Graph, DiGraph, NetworkXException, NetworkXError,
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/networkx/base.py", line 1526
H.add_edges_from((v,u) for (u,v) in self.edges_iter())

-Zeph Grunschlag

feature requestion: A useful little addition - G.info() print a little summary of G (migrated from Trac #16)

Original ticket https://networkx.lanl.gov/trac/ticket/16
Reported 2005-09-15 by bagrowjp, assigned to @hagberg.

I think it would be handy to make a small method for a graph that prints a little nicely-formatted list of statistics about the net, so you can get a quick overview of the graph.

For example:
'''

   type              undirected, simple
   number of nodes   56
   number of edges   102
   size              15807 bytes
   created           19:32 9/8/05
   etc               ?

'''

As you can see, this method would just call existing stuff and format the results. I think it would be very handy at an interactive prompt. Is there a networkxrc file or something similar? Then you could use that to customize what G.info() outputs.

Let me know what you think,[[BR]]
Jim

DiGraph's definition for neighbors() doesn't work with search algorithms (migrated from Trac #25)

Original ticket https://networkx.lanl.gov/trac/ticket/25
Reported 2006-01-27 by @dschult, assigned to @hagberg.

DiGraph.neighbors() returns both successors and predecessors, but the search algorithms we have coded assume that neighbors() yields only successors (it was developed primarily for Graphs).

Possible fixes include:

  • changing the search algorithms, (and looking for other uses of neighbors in other places).
  • changing the neighbors() API for DiGraph to return successors() only.
  • changing the Graph API to use successors instead of neighbors.

draw(G,pos) doesn't always create figures with the nodes in exactly the same place (migrated from Trac #46)

Original ticket https://networkx.lanl.gov/trac/ticket/46
Reported 2006-06-07 by jomiller, assigned to unknown.

I've defined G through erdos_renyi_graph.
I then define pos by spring_layout(G).

I then use the commands:
In [234]:draw(G,pos, nodelist=G.nodes(), node_color='b')

In [235]:savefig('bugtest1.png')

In [236]:show()

In [237]:draw(G,pos, nodelist=G.nodes(), node_color='b')

In [238]:draw(G,pos, nodelist=[1], node_color='r')

In [239]:savefig('bugtest2.png')

In [240]:show()

The nodes in the two png files do not lie in the same place. I'm using the version currently the default on t7 machines.

shortest path routines name and interface proposal (migrated from Trac #40)

Original ticket https://networkx.lanl.gov/trac/ticket/40
Reported 2006-05-19 by @hagberg, assigned to @hagberg.

Proposal for changing shortest paths interface to work generically
with single-source or bidirectional algorithm and weighted graphs.

= Proposal =

The generic shortest_path and shortest_path_length should attempt to infer
what algorithm to call based on arguments and graph type

=== Changes ===

  • shortest_path -> single_source_shortest_path
  • bidirectional_shortest_path -> bidirectional_shortest_path (no change)
  • dijkstra -> single_source_dijkstra
  • dijkstra_bi -> bidirectional_dijkstra
  • shortest_path = new code that calls either single_source_shortest_path or bidirectdional_shortest_path depending on argument (has target or not). Also attepts to infer weighted graph and call correct dijkstra function
  • shortest_path_length = new code that does len() on shortest_path results (might be slower?)
  • dijkstra_path = new code that calls single_source_dijkstra or bidirectional_dijkstra
  • dijkstra_path_length = new code that does len() on dijkstra_path results

=== Misc ===

  • need to choose bidirectional_shortest_path or bidirectional_shortest_path2, they are the same speed
  • perhaps update bidirectional_dijkstra in more pythonic idiom?

networkx.paths.is_directed_acyclic_graph is broken (migrated from Trac #21)

Original ticket https://networkx.lanl.gov/trac/ticket/21
Reported 2005-11-27 by joeb, assigned to @hagberg.

I think I've found a bug in networkx -- two functions fail to recognize DAGs. Here's a test case.

'''
import networkx
G = networkx.DiGraph()

G.add_edge("B. Globe" , "Punditry")
G.add_edge("TV Coverage" , "Punditry")
G.add_edge("Persistence" , "Punditry")
G.add_edge("TV Coverage" , "Wash. Post")
G.add_edge("Punditry" , "USA Today")
G.add_edge("Wash. Post" , "Punditry")

prints "False"; should be "True

print networkx.paths.is_directed_acyclic_graph(G)

prints "None", should print a list of nodes

print networkx.paths.topological_sort(G)

uncomment to see the graph

networkx.drawing.nx_pydot.write_dot(G,"new.dot")

'''

Do you get the same (mis)behavior?

best,

Joe

[pygraphviz] ImportError: libagraph.so.1: cannot open shared object file: No such file or directory (migrated from Trac #34)

Original ticket https://networkx.lanl.gov/trac/ticket/34
Reported 2006-04-24 by peralta_alejandro, assigned to @hagberg.

Software:

Python 2.4.2, GCC 3.4.4,
graphviz 2.6,
linux kernel 2.6.14,
AMD Athlon(tm) 64 Processor 3000+,

'''

import pygraphviz
Traceback (most recent call last):
File "", line 1, in ?
File "/usr/lib64/python2.4/site-packages/pygraphviz/init.py", line 31, in ?
from pygraphviz import *
File "/usr/lib64/python2.4/site-packages/pygraphviz/pygraphviz.py", line 11, in ?
from graphviz import *
File "/usr/lib64/python2.4/site-packages/pygraphviz/graphviz.py", line 5, in ?
import _graphviz
ImportError: libagraph.so.1: cannot open shared object file: No such file or directory
'''

'''

ls /usr/lib64/graphviz/libagraph.*

/usr/lib64/graphviz/libagraph.la /usr/lib64/graphviz/libagraph.so.1
/usr/lib64/graphviz/libagraph.so /usr/lib64/graphviz/libagraph.so.1.0.0
'''

after first try I edited this lines:

'''

set includes and libs by hand here if you have a very nonstandard

installation of graphviz

includes=prefix+os.sep+'include'+os.sep+'graphviz'
libs=prefix+os.sep+'lib64'+os.sep+'graphviz'
'''

with the same results. Any help is welcomed :-). Thanks.

Error in degree and clustering computation with disconnected nodes (migrated from Trac #47)

Original ticket https://networkx.lanl.gov/trac/ticket/47
Reported 2006-06-07 by ddiamantaras, assigned to @hagberg.

The following is an error message produced by the code below. Background: I am an economist, and learning how to use python for social network formation simulation. I am working currently with a co-author on a particular network formation process, using Networkx 0.29, with numpy 0.9.5 installed, on a Fedora Core 5 machine. Lots of stuff goes well, but we have the problem that when the network has nodes with degree zero, the degree() and clustering() give errors. As an illustration, below (with clustering we get the same kind of error).

I have not reported a bug to an open source program before---apologies if this is not optimal. In such a case, I will be happy to provide missing details. I highly appreciate your work on this module.

Dimitrios Diamantaras

'''
File "cbnetsim.py", line 77, in ?
node_degree = NX.degree(sps,k)
File "buil/bdist.linux-i686/egg/networkx/base.py", line 228, in degree
File "buil/bdist.linux-i686/egg/networkx/base.py", line 813, in degree
TypeError: iteration over non-sequence
'''

Input was -5, 10; this resulted in a network with some nodes with degree zero; the first such node encountered terminated output with the error shown above.

Code:

'''

!/usr/bin/env python

import networkx as NX
import networkx.drawing as NXD
from pylab import *
import random as R
"""
Main simulation process. Takes input from a file called
cbninput.txt. Simulates network formation under case-based
decision making.
"""

n = 25 # for now

"""
Ask: generate randomly input values, or read them from input.txt?
If yes, then run the random processes below, which writes input.txt.
Read input.txt to proceed.
"""

def createinput(m = n):
mm = float(raw_input("Enter average for delta: "))
sd = float(raw_input("Enter standard deviation for delta: "))
nodedata = zeros((m, m), Float)
infile = open('input.txt', 'w')
for i in xrange(m):
for j in xrange(m):
nodedata[i,j] = R.gauss(mm, sd)
if i == m-1 and j == m-1:
infile.write(repr(nodedata[i,j]))
else:
infile.write(repr(nodedata[i,j])+ ",")
infile.close()

"""Ask if input should be created"""
answer = raw_input("Do you want to create a random input file? [y,n]: ")

if answer == 'y':
createinput()
else:
pass

"""Read the deltas from the file"""
delta = zeros((n,n), Float)
deltathree = []
inputter = open('input.txt', 'r')
deltaone = inputter.read()
inputter.close()
deltatwo = deltaone.split(',')
for h in xrange(len(deltatwo)):
deltathree.append(float(deltatwo[h]))
delta = array(deltathree)
delta.shape = (n,n)

Now compute the strongly pairwise stable network from the delta data

sps = NX.Graph()

for i in xrange(n):
for j in xrange(i,n):
if delta[i,j] < 0:
pass
elif delta[j,i] < 0:
pass
else:
sps.add_edge(i,j)

NXD.draw_spectral(sps)
show()

NX.write_edgelist(sps, 'sps-output.txt')
out = open('sps-output.txt', 'a')
out.writelines(['\nThe array of delta values is:\n\n', repr(delta), '\n\n'])
degree_sum = 0
sps_value = 0

for k in xrange(0,n):
node_degree = NX.degree(sps,k)
node_clust = NX.clustering(sps,k)
out.writelines(['Node ', str(k), ' has degree ', str(node_degree), ' and clustering ', str(node_clust), '.\n'])
degree_sum += node_degree
for h in xrange(k+1,n):
if sps.has_edge(k,h):
sps_value = delta[k,h] + delta[h,k] + sps_value

out.writelines(['\n', 'The average node degree is ', str(degree_sum/float(n)), '.\n'])
out.writelines(['\n', 'The clustering for the network is ', str(NX.average_clustering(sps)), '.\n\n', 'The value of the SPS network is ', str(sps_value), '\n\nThe edge percentage of the SPS network is ', str(sps.size()/(0.5_n_(n-1)))])
out.close()
'''

draw complains about scope of layouts (silent failure for python2.3) (migrated from Trac #32)

Original ticket https://networkx.lanl.gov/trac/ticket/32
Reported 2006-03-31 by unknown, assigned to @hagberg.

/usr/lib/python2.3/site-packages/networkx/drawing/nx_pylab.py in draw(G, pos, with_labels, **kwds)
109 """
110 if pos is None:
--> 111 pos=networkx.drawing.spring_layout(G) # default to spring layout
112
113 ax=gca()

AttributeError: 'module' object has no attribute 'spring_layout'

so I tried changing 111: pos=networkx.drawing.layout.spring_layout(G), and got similar response.

serious bug when deleting node in XGraph or XDiGraph with multiedges=True (migrated from Trac #28)

Original ticket https://networkx.lanl.gov/trac/ticket/28
Reported 2006-03-03 by swart, assigned to @hagberg.

G=XGraph(multiedges=True)
G.add_edge(1,2,'a')
G.add_edge(1,2,'b')
G.add_edge(1,2,'c')

G.delete_node(1)

exceptions.ValueError Traceback (most recent call last)

/Users/swart/Research/NETWORKS/My Networkx Examples/chess_XGraph/

/Users/swart/Research/NETWORKS/networkx/networkx/base.py in delete_node(self, n)
443 try:
444 for u in self.adj[n].keys():
--> 445 self.delete_edge(n,u)# remove all edges n-u in graph
446 del self.adj[n] # now remove node
447 except KeyError: # NetworkXError if n not in self

/Users/swart/Research/NETWORKS/networkx/networkx/xbase.py in delete_edge(self, n1, n2, x)
558 if self.multiedges:
559 if self.has_edge(n1,n2,x): # (n1,n2,x) is an edge; now remove
--> 560 self.adj[n1][n2].remove(x) # remove the edge item from list
561 if n1!=n2: # and if not self loop
562 self.adj[n2][n1].remove(x) # remove n2->n1 entry

ValueError: list.remove(x): x not in list

improve shortest path memory usage (migrated from Trac #26)

Original ticket https://networkx.lanl.gov/trac/ticket/26
Reported 2006-02-21 by jfd, assigned to @hagberg.

The current implementation of shortest_path() uses a lot of memory to construct a dict of complete paths to the target node. As I understand it, it is only really neccesary to specify the next node in the path.

E.g. if there is the graph A->B->C->D. Instead of returning something like:
{
A: [A, B, C, D]
B: [B, C, D]
C: [C, D]
D: [D]
}

It would be better to say
{A: B, B: C, C: D}

from which generators for each path can be constructed to keep with the current API.

'''

!python

def shortest_path(G,source,target=None,cutoff=None):
if target==source: return [] # trivial path
level=0 # the current level
nextlevel=set([source]) # set of nodes to check at next level
paths={source:source} # paths hash (paths to key from source)
while nextlevel:
thislevel=nextlevel
nextlevel=set()
for v in thislevel:
for w in G.neighbors(v):
if not paths.has_key(w):
paths[w]=v
if w==target: # Shortcut if target is not None
return paths[w]
nextlevel.add(w)
level=level+1
etc.
'''

An nbunch that is not a node or a sequence of nodes gives an unclear error (migrated from Trac #41)

Original ticket https://networkx.lanl.gov/trac/ticket/41
Reported 2006-05-19 by @dschult, assigned to @hagberg.

In most every routine that uses nbunch, an exception is thrown when nbunch
is not a node and also not a sequence. The resulting "TypeError, iteration over non-sequence"
message can be confusing because the location of the error is sometimes a few lines below the for-loop
over nbunch.

This does not occur for edges_iter and its cousins which are set up
to ignore the exception.

Proposal:
Reduce the nbunch handling code to a few lines which are isolated from
the rest of the routine and the same for all routines using nbunch.
I think the following is a possibility:
'''
if nbunch is None: # include all nodes
nbunch=self.nodes_iter():
elif nbunch in self: # a single node in the graph
nbunch=[nbunch]
else: # try making a list of ndes from the nbunch sequence
try:
nbunch=[ n for n in nbunch if n in self ]
except TypeError, "iteration over non-sequence":
raise NetworkXError, "nbunch is not a node or a sequence of nodes."
'''

What do you think? Also, should edges and family still return empty lists?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.