~ubuntu-branches/ubuntu/utopic/python-networkx/utopic

« back to all changes in this revision

Viewing changes to networkx/generators/stochastic.py

  • Committer: Package Import Robot
  • Author(s): Sandro Tosi
  • Date: 2012-08-11 12:41:30 UTC
  • mfrom: (1.4.1) (5.1.13 sid)
  • Revision ID: package-import@ubuntu.com-20120811124130-whr6uso7fncyg8bi
Tags: 1.7-1
* New upstream release
* debian/patches/changeset_*
  - removed, included upstream

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
"""
2
 
Stocastic graph.
3
 
"""
 
1
"""Stocastic graph."""
 
2
import networkx as nx
4
3
#    Copyright (C) 2010 by 
5
4
#    Aric Hagberg <hagberg@lanl.gov>
6
5
#    Dan Schult <dschult@colgate.edu>
8
7
#    All rights reserved.
9
8
#    BSD license.
10
9
__author__ = "Aric Hagberg <hagberg@lanl.gov>"
11
 
 
12
10
__all__ = ['stochastic_graph']
13
11
 
14
 
import networkx as nx
15
 
 
16
 
def stochastic_graph(G,copy=True):
 
12
def stochastic_graph(G, copy=True, weight='weight'):
17
13
    """Return a right-stochastic representation of G.
18
14
 
19
15
    A right-stochastic graph is a weighted graph in which all of
27
23
    copy : boolean, optional
28
24
      If True make a copy of the graph, otherwise modify original graph
29
25
 
 
26
    weight : key (optional)
 
27
      Edge data key used for weight.  If None all weights are set to 1.
30
28
    """        
31
29
    if type(G) == nx.MultiGraph or type(G) == nx.MultiDiGraph:
32
 
        raise Exception("stochastic_graph not implemented for Multi(Di)Graphs")
 
30
        raise Exception("stochastic_graph not implemented for multigraphs")
33
31
 
34
32
    if not G.is_directed():
35
 
        raise Exception("stochastic_graph not implemented for undirected graphs")
 
33
        raise Exception("stochastic_graph not defined for undirected graphs")
36
34
 
37
35
    if copy:
38
36
        W=nx.DiGraph(G)
39
37
    else:
40
38
        W=G # reference original graph, no copy
41
39
 
42
 
    try:        
43
 
        degree=W.out_degree(weighted=True)
44
 
    except:
45
 
        degree=W.out_degree()
46
 
#    for n in W:
47
 
#        for p in W[n]:
48
 
#            weight=G[n][p].get('weight',1.0)
49
 
#            W[n][p]['weight']=weight/degree[n]        
50
 
 
 
40
    degree=W.out_degree(weight=weight)
51
41
    for (u,v,d) in W.edges(data=True):
52
 
        d['weight']=d.get('weight',1.0)/degree[u]
53
 
 
54
 
 
 
42
        d[weight]=d.get(weight,1.0)/degree[u]
55
43
    return W