graph-tool 50.4 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1
#! /usr/bin/env python
2
3
# graph-tool -- a general graph modification and manipulation thingy
#
Tiago Peixoto's avatar
Tiago Peixoto committed
4
# Copyright (C) 2007 Tiago de Paula Peixoto <tiago@forked.de>
Tiago Peixoto's avatar
Tiago Peixoto committed
5
6
7
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
Tiago Peixoto's avatar
Tiago Peixoto committed
8
# the Free Software Foundation; either version 3 of the License, or
Tiago Peixoto's avatar
Tiago Peixoto committed
9
10
11
12
13
14
15
16
17
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
Tiago Peixoto's avatar
Tiago Peixoto committed
19

20
21
22
23
24
__author__="Tiago de Paula Peixoto <tiago@forked.de>"
__copyright__="Copyright 2007 Tiago de Paula Peixoto"
__license__="GPL version 3 or above"
__URL__="http://graph-tool.forked.de"

Tiago Peixoto's avatar
Tiago Peixoto committed
25
26
27
28
29
import sys

sys.path.append(".")

from libgraph_tool import *
30
__version__= mod_info().version
Tiago Peixoto's avatar
Tiago Peixoto committed
31
32
33
34
35
36
37
38
39
40
41
42
43

from optparse import *
import os
import os.path
import re
import struct
import fcntl
import termios
import gzip
import bz2
import string
import time
import signal
44
import traceback
Tiago Peixoto's avatar
Tiago Peixoto committed
45
from time import *
46
from math import *
Tiago Peixoto's avatar
Tiago Peixoto committed
47

48
49
50
#import gc # garbage collector
#gc.enable()
#gc.set_debug(gc.DEBUG_LEAK|gc.DEBUG_STATS)
Tiago Peixoto's avatar
Tiago Peixoto committed
51
52
53
54
55
56

prog_info = mod_info()
version_string = "%s %s\nWritten by %s\n\n%s" % (prog_info.name, prog_info.version, \
                                               prog_info.author,prog_info.copyright)

def getheightwidth():
57
58
59
60
61
    height, width = 20, 80
    try:
        height, width = struct.unpack("hhhh", fcntl.ioctl(0, termios.TIOCGWINSZ ,"\000"*8))[0:2]
    except IOError:
        pass
Tiago Peixoto's avatar
Tiago Peixoto committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
    return height, width

option_list = list()
class Opt:
    def __init__(self, name, value):
        self.name = name
        self.value = value

def push_option(option, opt_str, value, parser):
    option_list.append(Opt(opt_str.lstrip("--"), value))

parser = OptionParser(usage="%s [options]" % sys.argv[0], version=version_string, \
                      formatter=IndentedHelpFormatter(max_help_position=getheightwidth()[1]/2,width=getheightwidth()[1]))
basic =  parser.add_option_group("Basic options")
basic.add_option("--load", action="callback", callback=push_option, type="string", metavar="FILE", help="load graph from file")
basic.add_option("--save", action="callback", callback=push_option, type="string", metavar="FILE", help="save graph to file")

generation =  parser.add_option_group("Graph generation")
generation.add_option("--correlated-configurational-model", action="callback", type="string", metavar="OPTIONS", callback=push_option, help="generate graph using the configurational model with arbitrary degree correlations. Options are: N, pjk, pjk_ceil, pjk_m, inv_pjk_ceil, corr, corr_ceil, corr_m, inv_corr_ceil, undirected, directed, progress, seed. See documentation for details.")

filtering =  parser.add_option_group("Filtering")
filtering.add_option("--directed", action="callback", callback=push_option, help="treat graph as directed (default)")
filtering.add_option("--undirected", action="callback", callback=push_option, help="treat graph as undirected")
filtering.add_option("--reverse", action="callback", callback=push_option, help="reverse edges")
filtering.add_option("--vertex-filter", action="callback", callback=push_option, type="string", metavar="FILTER RULE", help="set generic vertex filter")
filtering.add_option("--vertex-range-filter", action="callback", callback=push_option, type="string", metavar="PROPERTY|RANGE", help="choose vertex property and range to filter")
filtering.add_option("--reset-vertex-filter", action="callback", callback=push_option, help="remove edge filter")
filtering.add_option("--edge-filter", action="callback", callback=push_option, type="string", metavar="FILTER RULE", help="set generic edge filter")
filtering.add_option("--edge-range-filter", action="callback", callback=push_option, type="string", metavar="PROPERTY|RANGE", help="choose edge property and range to filter")
filtering.add_option("--reset-edge-filter", action="callback", callback=push_option, help="remove edge filter")

modification =  parser.add_option_group("Graph Modification")
94
95
modification.add_option("--edit-vertex-property", action="callback", callback=push_option, type="string", metavar="PROPERTY[|TYPE]|EXPRESSION", help="edit the selected vertex property")
modification.add_option("--edit-edge-property", action="callback", callback=push_option, type="string", metavar="PROPERTY[|TYPE]|EXPRESSION", help="edit the selected edge property")
Tiago Peixoto's avatar
Tiago Peixoto committed
96
modification.add_option("--edit-graph-property", action="callback", callback=push_option, type="string", metavar="PROPERTY[|TYPE]|EXPRESSION", help="edit the selected graph property")
Tiago Peixoto's avatar
Tiago Peixoto committed
97
98
modification.add_option("--remove-vertex-property", action="callback", callback=push_option, type="string", metavar="PROPERTY", help="remove vertex property from graph")
modification.add_option("--remove-edge-property", action="callback", callback=push_option, type="string", metavar="PROPERTY|RANGE", help="remove edge property from graph")
Tiago Peixoto's avatar
Tiago Peixoto committed
99
modification.add_option("--remove-graph-property", action="callback", callback=push_option, type="string", metavar="PROPERTY|RANGE", help="remove graph property from graph")
Tiago Peixoto's avatar
Tiago Peixoto committed
100
101
modification.add_option("--insert-vertex-index-property", action="callback", callback=push_option, type="string", metavar="PROPERTY", help="insert vertex index as property")
modification.add_option("--insert-edge-index-property", action="callback", callback=push_option, type="string", metavar="PROPERTY", help="insert edge index as property")
102
modification.add_option("--list-properties", action="callback", callback=push_option, help="list all properties")
Tiago Peixoto's avatar
   
Tiago Peixoto committed
103
104
modification.add_option("--random-rewire", action="callback", callback=push_option, type="string", metavar="OPTIONS", help="randomly rewire edges. Options are: correlated, uncorrelated, no-self-loops, no-parallel-edges")

Tiago Peixoto's avatar
Tiago Peixoto committed
105
106
107
108

statistics =  parser.add_option_group("Basic Statistics")
statistics.add_option("--number-of-vertices", action="callback", callback=push_option, type="string", metavar="FILE", help="get the number of vertices")
statistics.add_option("--number-of-edges", action="callback", callback=push_option, type="string", metavar="FILE", help="get the number of edges")
109
110
statistics.add_option("--vertex-histogram", action="callback", callback=push_option, type="string", metavar="DEGREE|FILE", help="get the vertex degree/property histogram")
statistics.add_option("--edge-histogram", action="callback", callback=push_option, type="string", metavar="PROPERTY|FILE", help="get the edge property histogram")
111
statistics.add_option("--combined-vertex-histogram", action="callback", callback=push_option, type="string", metavar="DEGREE1|DEGREE2|FILE", help="get the combined (DEGREE1,DEGREE2) histogram. Scalar properties are also accepted as DEGREE1 or DEGREE2")
112
statistics.add_option("--distance-histogram", action="callback", callback=push_option, type="string", metavar="[WEIGHT|]FILE", help="get the distance histogram")
113
114
statistics.add_option("--average-distance", action="callback", callback=push_option, type="string", metavar="[WEIGHT|]FILE", help="get the averarge distance")
statistics.add_option("--average-harmonic-distance", action="callback", callback=push_option, type="string", metavar="[WEIGHT|]FILE", help="get the averarge harmonic distance")
115
116
117
statistics.add_option("--sampled-distance-histogram", action="callback", callback=push_option, type="string", metavar="OPTIONS|FILE", help="get the sampled distance histogram. Options are samples, weight (optional), seed (default: from clock)")
statistics.add_option("--average-sampled-distance", action="callback", callback=push_option, type="string", metavar="OPTIONS|FILE", help="get the average sampled distance. Options are samples, weight (optional), seed (default: from clock)")
statistics.add_option("--average-sampled-harmonic-distance", action="callback", callback=push_option, type="string", metavar="OPTIONS|FILE", help="get the average sampled harmonic distance. Options are samples, weight (optional), seed (default: from clock)")
118
statistics.add_option("--label-components", action="callback", callback=push_option, type="string", metavar="PROPERTY", help="label components to PROPERTY")
Tiago Peixoto's avatar
Tiago Peixoto committed
119
statistics.add_option("--label-parallel-edges", action="callback", callback=push_option, type="string", metavar="PROPERTY", help="label parallel edges to PROPERTY")
120
121
statistics.add_option("--average-vertex-property", action="callback", callback=push_option, type="string", metavar="PROPERTY|FILE", help="get the average of the vertex property")
statistics.add_option("--average-edge-property", action="callback", callback=push_option, type="string", metavar="PROPERTY|FILE", help="get the average of the edge property")
122
statistics.add_option("--reciprocity", action="callback", callback=push_option, type="string", metavar="FILE", help="get the edge reciprocity")
123
statistics.add_option("--minimum-spanning-tree", action="callback", callback=push_option, type="string", metavar="[WEIGHT|]PROPERTY", help="mark the minimum spanning tree edges in PROPERTY")
Tiago Peixoto's avatar
Tiago Peixoto committed
124
statistics.add_option("--line-graph", action="callback", callback=push_option, type="string", metavar="FILE[|FORMAT]", help="save the corresponding line graph to FILE")
125
126
127
statistics.add_option("--betweenness-centrality", action="callback", callback=push_option, type="string", metavar="VERTEX_BETWEENESS[|EDGE_BETWEENESS[|WEIGHT]]", help="calculate and store the vertex and/or edge betweenness centrality")
statistics.add_option("--central-point-dominance", action="callback", callback=push_option, type="string", metavar="VERTEX_BETWEENESS|FILE", help="calculate central point dominance, given the VERTEX_BETWEENESS vertex property")

Tiago Peixoto's avatar
Tiago Peixoto committed
128
129

correlations =  parser.add_option_group("Correlations")
130
correlations.add_option("--average-combined-vertex-correlation", action="callback", callback=push_option, type="string", metavar="DEGREE1|DEGREE2|FILE", help="get the average of DEGREE2 in function of DEGREE1. Scalar properties are also accepted as DEGREE1 or DEGREE2")
131
132
correlations.add_option("--vertex-correlation-histogram", action="callback", callback=push_option, type="string", metavar="DEGREE1|DEGREE2[|WEIGHT]|FILE", help="get the degree correlation histogram. Scalar properties are also accepted in place of DEGREE. An optional edge weight property can be passed by WEIGHT")
correlations.add_option("--average-nearest-neighbours-correlation", action="callback", callback=push_option, type="string", metavar="ORIGIN-DEGREE|DEGREE[|WEIGHT]|FILE", help="get the average nearest neighbours correlation. An optional edge weight property can be passed by WEIGHT")
133
correlations.add_option("--edge-vertex-correlation-histogram", action="callback", callback=push_option, type="string", metavar="DEGREE1|EDGE-PROP|DEGREE2|FILE", help="get the source degree vs. edge scalar vs. target degree correlation histogram. Scalar properties are also accepted in place of DEGREE-TYPE")
134
correlations.add_option("--assortativity-coefficient", action="callback", callback=push_option, type="string", metavar="DEGREE|FILE", help="get the assortativity coefficient. Scalar properties are also accepted in place of DEGREE")
135
correlations.add_option("--scalar-assortativity-coefficient", action="callback", callback=push_option, type="string", metavar="DEGREE|FILE", help="get the scalar assortativity coefficient. Scalar properties are also accepted in place of DEGREE")
Tiago Peixoto's avatar
Tiago Peixoto committed
136
137

clustering =  parser.add_option_group("Clustering")
138
clustering.add_option("--local-clustering-coefficient", action="callback", callback=push_option, type="string", metavar="PROPERTY", help="set the local clustering coefficient to vertex property")
Tiago Peixoto's avatar
Tiago Peixoto committed
139
clustering.add_option("--global-clustering-coefficient", action="callback", callback=push_option, type="string", metavar="FILE", help="get the global clustering coefficient")
140
clustering.add_option("--extended-clustering-coefficient", action="callback", callback=push_option, type="string", metavar="PREFIX|MAX", help="set the extended clustering coefficients c1 to cMAX to vertex properties PREFIX1 to PREFIXMAX")
Tiago Peixoto's avatar
Tiago Peixoto committed
141
142
143
144
145

layout =  parser.add_option_group("Layout")
layout.add_option("--compute-spring-block-layout", action="callback", callback=push_option, type="string", metavar="ITERATIONS[|SEED]", help="compute the spring block layout")
layout.add_option("--compute-gursoy-atun-layout", action="callback", callback=push_option, type="string", metavar="ITERATIONS[|SEED]", help="compute the Gursoy-Atun layout")

Tiago Peixoto's avatar
Tiago Peixoto committed
146
community =  parser.add_option_group("Community")
Tiago Peixoto's avatar
Tiago Peixoto committed
147
community.add_option("--community-structure", action="callback", callback=push_option, type="string", metavar="PROPERTY|OPTIONS", help="calculate the community structure and assign it to PROPERTY. Options are: g (default: 1.0), N (default: 1000), Tmin (default: 0.01), Tmax (default: 1.0), spins (default: number of vertices), corr_type (default: uncorrelated), weight, seed (default: from clock), verbose, history.  The value of corr_type can be 'random', 'uncorrelated' or 'correlated'.")
148
community.add_option("--modularity", action="callback", callback=push_option, type="string", metavar="PROPERTY[|WEIGHT]|FILE", help="calculate the modularity, given a community partition specified by PROPERTY")
149
community.add_option("--community-graph", action="callback", callback=push_option, type="string", metavar="PROPERTY|FILE[|FORMAT]", help="obtain the graph of communities, given a community partition specified by PROPERTY")
Tiago Peixoto's avatar
Tiago Peixoto committed
150

Tiago Peixoto's avatar
Tiago Peixoto committed
151
layout =  parser.add_option_group("History")
152
153
154
layout.add_option("--for", action="callback", callback=push_option, type="string", metavar="INIT|CONDITION|STEP", help="simplified scripting")
layout.add_option("--history", action="callback", callback=push_option, type="string", metavar="INIT|CONDITION|STEP", help="simplified scripting (does not overwrite previous results)")
layout.add_option("--refresh-rate", type="string", metavar="TIME", default="1h", help="for/history files refresh rate")
Tiago Peixoto's avatar
Tiago Peixoto committed
155

156
157
158
159
160
161
try:
    import optcomplete
    optcomplete.autocomplete(parser)
except ImportError:
    pass

Tiago Peixoto's avatar
Tiago Peixoto committed
162
163
164
165
166
167
(options, args) = parser.parse_args()

graph = GraphInterface()

def parse_values(value):
    "this will parse the options with multiple values"
Tiago Peixoto's avatar
Tiago Peixoto committed
168
169
    p = re.compile(r"((('[^']*')|(\"[^\"']*\"))|([^\|]+)(?=\||$))")
    values = [x[0].strip() for x in p.findall(value)]
Tiago Peixoto's avatar
Tiago Peixoto committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
    return values

def get_suboption(suboption, string):
    p = re.compile(r"([^,'\"]+|[^,]+'[^']*'|[^,]+\"[^\"]*\")(?:,|$)")
    opts = p.findall(string)
    for opt in opts:
        if opt.split("=",1)[0].strip() == suboption:
            if "=" in opt:            
                return opt.split("=",1)[1].strip("\"").strip("'")
            else:
                return True
    return False

def degree(name):
    "this will retrieve the degree type from string"
    deg = name
    if name == "in-degree" or name == "in":
        deg = Degree.In
    if name == "out-degree" or name == "out":
        deg = Degree.Out
    if name == "total-degree" or name == "total":
        deg = Degree.Total
    return deg

194
195
def get_mean(hist):
    avg,dev,count = 0.0,0.0,0.0
196
    try:
Tiago Peixoto's avatar
Tiago Peixoto committed
197
198
199
        for k,v in hist.iteritems():
            avg += k*v
            count += v
200
        avg /= count
Tiago Peixoto's avatar
Tiago Peixoto committed
201
202
203
        for k,v in hist.iteritems():
            dev += (k - avg)**2
        dev = sqrt(dev/(count**2))
204
205
    except ZeroDivisionError:
        avg = dev = float("nan") # nans are ok, since graph can be empty
206
207
    return (avg,dev)

Tiago Peixoto's avatar
Tiago Peixoto committed
208
209
210
211
212
213
class OptionError(Exception):
    def __init__(self, option, error):
        self.what = "error parsing option %s: %s" % (option,error)
    def __str__(self):
        return self.what

214
215
216
217
218
219
220
def generate_graph(parameters):
    "this option will generate a graph with the given parameters"
    seed = int(time())
    N = 10000
    pjk = "1.0"
    pjk_ceil = "pjk(j,k)"
    m_pjk = "1.0"
221
    inv_pjk_ceil = "(inv_poisson(p,2), inv_poisson(p,2))"
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
    corr = "1.0"
    corr_ceil = "corr(jl,kl,j,k)"
    m_corr = "1.0"
    inv_corr_ceil = "inv_pjk_ceil(p,r)"
    try:
        if get_suboption("N",parameters) != False:
            N = int(get_suboption("N",parameters))
        if get_suboption("pjk",parameters) != False:
            pjk = get_suboption("pjk",parameters)
            corr = "pjk(j,k)"
        if get_suboption("pjk_ceil",parameters) != False:
            pjk_ceil = get_suboption("pjk_ceil",parameters)
        if get_suboption("pjk_m",parameters) != False:
            m_pjk = get_suboption("pjk_m",parameters)
            m_corr = m_pjk
        if get_suboption("inv_pjk_ceil",parameters) != False:
            inv_pjk_ceil = get_suboption("inv_pjk_ceil",parameters)
        if get_suboption("corr",parameters) != False:
            corr = get_suboption("corr",parameters)
        if get_suboption("corr_ceil",parameters) != False:
            corr_ceil = get_suboption("corr_ceil",parameters)
        if get_suboption("corr_m",parameters) != False:
            corr_m = get_suboption("corr_m",parameters)
        if get_suboption("inv_corr_ceil",parameters) != False:
            inv_corr_ceil = get_suboption("inv_corr_ceil",parameters)            
        undirected = get_suboption("undirected",parameters)
        verbose = get_suboption("progress", parameters)
        if get_suboption("seed",parameters) != False:
            seed = int(get_suboption("seed",parameters))
    except ValueError, e:
        raise OptionError(opt.name, e)
253

254
    # some predefined functions
255
256
257
258
259
    try:
        from scipy.special import gammaincc
        from scipy.optimize import fsolve
    except ImportError:
        pass
260
    
261
262
    variables = globals()

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
    def inv_poisson(p,m):
        return round(fsolve(lambda k,l: gammaincc(k,l)-p, m, (m))-0.5+1e-15)
    variables["inv_poisson"] = inv_poisson
    
    def inv_exponential(p,m):
        return round(log(1-p)/log(float(m)/(m+1))-0.5+1e-15)
    variables["inv_exponential"] = inv_exponential
    
    def inv_power_law(p,b):
        return round((1-p)**(-1/(b-1)) - 1)
    variables["inv_power_law"] = inv_power_law
    
    def step(x):
        if x >= 0:
            return 1.0
        else:
            return 0.0
    variables["step"] = step

282
    # read main funtions
283
284
285
286
287
288
289
290
291
292
    def pjk_f(j,k):
        return eval("%s" % pjk, variables, locals())
    variables["pjk"] = pjk_f
    
    def pjk_ceil_f(j,k):
        return eval("%s" % pjk_ceil, variables, locals())
    variables["pjk_ceil"] = pjk_ceil_f

    m_pjk = float(m_pjk)
    variables["m_pjk"] = m_pjk
293

294
    if "file:" in inv_pjk_ceil:
295
        exec open(os.path.expanduser(inv_pjk_ceil.replace("file:","").strip())).read() in variables
296
    else:
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
        def inv_pjk_ceil_f(p,r):
            variables["p"] = p
            variables["r"] = r
            retval = eval("%s" % inv_pjk_ceil, variables, locals())
            del(variables["p"])
            del(variables["r"])
            return (int(round(retval[0])), int(round(retval[1])))
        variables["inv_pjk_ceil"] = inv_pjk_ceil_f
        
    def corr_f(jl,kl,j,k):
        return eval("%s" % corr, variables, locals())
    variables["corr"] = corr_f
    
    def corr_ceil_f(jl,kl,j,k):
        return eval("%s" % corr_ceil, variables, locals())
    variables["corr_ceil"] = corr_ceil_f
    
    m_corr = float(m_corr)
    variables["m_corr"] = m_corr
        
317
    if "file:" in inv_corr_ceil:
318
        exec open(os.path.expanduser(inv_corr_ceil.replace("file:","").strip())).read() in variables
319
    else:
320
321
322
323
324
        def inv_corr_ceil_f(p,r,j,k):
            retval = eval("%s" % inv_corr_ceil, variables, locals())
            return (int(round(retval[0])), int(round(retval[1])))
        variables["inv_corr_ceil"] = inv_corr_ceil_f

325
326
327
328
    graph.GenerateCorrelatedConfigurationalModel(N, variables["pjk"], variables["pjk_ceil"], variables["inv_pjk_ceil"], m_pjk, variables["corr"],
                                                 variables["corr_ceil"], variables["inv_corr_ceil"], m_corr, undirected, seed, verbose)


Tiago Peixoto's avatar
Tiago Peixoto committed
329
def parse_option(opt, just_file=False):
Tiago Peixoto's avatar
Tiago Peixoto committed
330
    "this will execute an option, and return either None, or a tuple with the result and the respective file name, if it exists"
Tiago Peixoto's avatar
Tiago Peixoto committed
331
    if opt.name == "load":
332
333
334
        values = parse_values(opt.value)
        if len(values) > 2 or len(values) < 1:
            raise OptionError(opt.name, "invalid value '$s'" % opt.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
335
336
        if just_file:
            return None
337
338
        if len(values) == 1:
            graph.ReadFromFile(values[0])
Tiago Peixoto's avatar
Tiago Peixoto committed
339
340
        else:
            graph.ReadFromFile(values[0], values[1])
Tiago Peixoto's avatar
Tiago Peixoto committed
341
    elif opt.name == "save":
342
        values = parse_values(opt.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
343
        if len(values) > 2 or len(values) < 1:
344
            raise OptionError(opt.name, "invalid value '$s'" % opt.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
345
346
        if just_file:
            return None
347
348
        if len(values) == 1:
            graph.WriteToFile(values[0])
Tiago Peixoto's avatar
Tiago Peixoto committed
349
350
        else:
            graph.WriteToFile(values[0], values[1])
Tiago Peixoto's avatar
Tiago Peixoto committed
351
352
353
    elif opt.name == "correlated-configurational-model":
        if just_file:
            return None
354
        generate_graph(opt.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
355
356
357
358
359
360
361
362
    elif opt.name == "number-of-vertices":
        if just_file:
            return opt.value
        return (graph.GetNumberOfVertices(), opt.value)
    elif opt.name == "number-of-edges":
        if just_file:
            return opt.value
        return (graph.GetNumberOfEdges(), opt.value)
363
364
365
366
    elif opt.name == "combined-vertex-histogram":
        values = parse_values(opt.value)
        if len(values) != 3:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
367
        if just_file:
368
369
            return values[2]
        return (graph.GetCombinedVertexHistogram(degree(values[0]),degree(values[1])), values[2])
370
371
372
373
374
375
376
    elif opt.name == "average-combined-vertex-correlation":
        values = parse_values(opt.value)
        if len(values) != 3:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if just_file:
            return values[2]
        return (graph.GetAverageCombinedVertexCorrelation(degree(values[0]),degree(values[1])), values[2])
377
378
379
380
381
382
383
384
385
386
387
    elif opt.name == "distance-histogram":
        values = parse_values(opt.value)
        if len(values) > 2 or len(values) < 1:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        file_name, weight = values[0],""
        if len(values) > 1:
            weight = values[0]
            file_name = values[1]
        if just_file:
            return file_name
        return (graph.GetDistanceHistogram(weight), file_name)
Tiago Peixoto's avatar
Tiago Peixoto committed
388
    elif opt.name == "average-distance":
389
390
391
392
393
394
395
        values = parse_values(opt.value)
        if len(values) > 2 or len(values) < 1:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        file_name, weight = values[0],""
        if len(values) > 1:
            weight = values[0]
            file_name = values[1]
Tiago Peixoto's avatar
Tiago Peixoto committed
396
        if just_file:
397
            return file_name
398
        return ("%f\t%f" % get_mean(graph.GetDistanceHistogram(weight)), file_name)
Tiago Peixoto's avatar
Tiago Peixoto committed
399
    elif opt.name == "average-harmonic-distance":
400
401
402
403
404
405
406
        values = parse_values(opt.value)
        if len(values) > 2 or len(values) < 1:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        file_name, weight = values[0],""
        if len(values) > 1:
            weight = values[0]
            file_name = values[1]
Tiago Peixoto's avatar
Tiago Peixoto committed
407
        if just_file:
408
            return file_name
409
        hist = graph.GetDistanceHistogram(weight)
Tiago Peixoto's avatar
Tiago Peixoto committed
410
411
        avg, err = get_mean(dict((1.0/k,v) for k,v in hist.iteritems()))
        return ("%f\t%f" % (1.0/avg,err/(avg**2)) , file_name)
412
413
    elif opt.name == "sampled-distance-histogram":
        values = parse_values(opt.value)
414
        if len(values) != 2:
415
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
416
417
418
419
420
421
422
423
424
425
        if get_suboption("weight", values[0]) != False:
            weight = get_suboption("weight", values[0])
        else:
            weight = ""
        if get_suboption("samples", values[0]) != False:
            samples = int(get_suboption("samples", values[0]))
        else:
            raise OptionError(opt.name, "you must provide the number of samples")
        if get_suboption("seed", values[0]) != False:
            seed = int(get_suboption("seed", values[0]))
426
        else:
427
            seed = int(time())
428
        if just_file:
429
430
            return values[1]
        return (graph.GetSampledDistanceHistogram(weight, samples, seed), values[1])
431
432
    elif opt.name == "average-sampled-distance":
        values = parse_values(opt.value)
433
        if len(values) != 2:
434
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
435
436
437
438
439
440
        if get_suboption("weight", values[0]) != False:
            weight = get_suboption("weight", values[0])
        else:
            weight = ""
        if get_suboption("samples", values[0]) != False:
            samples = int(get_suboption("samples", values[0]))
441
        else:
442
443
444
445
446
            raise OptionError(opt.name, "you must provide the number of samples")
        if get_suboption("seed", values[0]) != False:
            seed = int(get_suboption("seed", values[0]))
        else:
            seed = int(time())
447
        if just_file:
448
449
            return values[1]
        return ("%f\t%f" % get_mean(graph.GetSampledDistanceHistogram(weight, samples, seed)), values[1])
450
451
    elif opt.name == "average-sampled-harmonic-distance":
        values = parse_values(opt.value)
452
        if len(values) != 2:
453
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
454
455
        if get_suboption("weight", values[0]) != False:
            weight = get_suboption("weight", values[0])
456
        else:
457
458
459
460
461
462
463
464
465
            weight = ""
        if get_suboption("samples", values[0]) != False:
            samples = int(get_suboption("samples", values[0]))
        else:
            raise OptionError(opt.name, "you must provide the number of samples")
        if get_suboption("seed", values[0]) != False:
            seed = int(get_suboption("seed", values[0]))
        else:
            seed = int(time())
466
        if just_file:
467
            return values[1]
468
        hist = graph.GetSampledDistanceHistogram(weight, samples, seed)
Tiago Peixoto's avatar
Tiago Peixoto committed
469
        avg, err = get_mean(dict((1.0/k,v) for k,v in hist.iteritems()))
470
        return ("%f\t%f" % (1.0/avg,1.0/err) , values[1])
471
    elif opt.name == "label-components":
Tiago Peixoto's avatar
Tiago Peixoto committed
472
        if just_file:
473
474
            return
        graph.LabelComponents(opt.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
475
476
477
478
    elif opt.name == "label-parallel-edges":
        if just_file:
            return
        graph.LabelParallelEdges(opt.value)
479
    elif opt.name == "vertex-histogram":
Tiago Peixoto's avatar
Tiago Peixoto committed
480
481
482
483
484
485
        values = parse_values(opt.value)
        if len(values) != 2:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        deg = degree(values[0])
        if just_file:
            return values[1]
486
487
488
489
490
491
492
493
        return (graph.GetVertexHistogram(deg), values[1])
    elif opt.name == "edge-histogram":
        values = parse_values(opt.value)
        if len(values) != 2:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if just_file:
            return values[1]
        return (graph.GetEdgeHistogram(values[0]), values[1])
494
495
496
497
    elif opt.name == "reciprocity":
        if just_file:
            return opt.value
        return (graph.GetReciprocity(), opt.value)
498
499
500
501
502
503
504
505
506
507
508
    elif opt.name == "minimum-spanning-tree":
        values = parse_values(opt.value)
        if len(values) > 2 or len(values) < 1:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if just_file:
            return None
        prop, weight = values[0],""
        if len(values) > 1:
            weight = values[0]
            prop = values[1]
        graph.GetMinimumSpanningTree(weight,prop)
509
510
511
512
513
514
515
516
517
518
519
    elif opt.name == "line-graph":
        values = parse_values(opt.value)
        if len(values) < 1 or len(values) > 2:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if just_file:
            return None
        if len(values) > 1:
            format = values[1]
        else:
            format = ""
        graph.GetLineGraph(values[0], format)
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
    elif opt.name == "betweenness-centrality":
        values = parse_values(opt.value)
        if len(values) < 1 or len(values) > 3:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if just_file:
            return None
        vertex_centrality = values[0]
        if len(values) > 1:
            edge_centrality = values[1]
        else:
            edge_centrality = ""
        if len(values) > 2:
            weight = values[2]
        else:
            weight = ""
535
        graph.GetBetweenness(weight, edge_centrality, vertex_centrality)
536
537
538
539
540
541
542
    elif opt.name == "central-point-dominance":
        values = parse_values(opt.value)
        if len(values) != 2:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if just_file:
            return None
        return (graph.GetCentralPointDominance(values[0]), values[1])
543
    elif opt.name == "vertex-correlation-histogram":
Tiago Peixoto's avatar
Tiago Peixoto committed
544
        values = parse_values(opt.value)
545
        if len(values) < 3 or len(values) > 4:
Tiago Peixoto's avatar
Tiago Peixoto committed
546
547
548
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        deg1 = degree(values[0])
        deg2 = degree(values[1])
549
550
551
552
553
554
        if len(values) == 4:
            weight = values[2]
            file_name = values[3]
        else:
            weight = ""
            file_name = values[2]
Tiago Peixoto's avatar
Tiago Peixoto committed
555
        if just_file:
556
557
            return file_name
        return (graph.GetVertexCorrelationHistogram(deg1, deg2, weight), file_name)
558
    elif opt.name == "edge-vertex-correlation-histogram":
Tiago Peixoto's avatar
Tiago Peixoto committed
559
560
561
562
563
564
565
        values = parse_values(opt.value)
        if len(values) != 4:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        deg1 = degree(values[0])
        deg2 = degree(values[2])
        if just_file:
            return values[3]
566
567
        return (graph.GetEdgeVertexCorrelationHistogram(deg1,values[1],deg2), values[3])
    elif opt.name == "average-nearest-neighbours-correlation":
Tiago Peixoto's avatar
Tiago Peixoto committed
568
        values = parse_values(opt.value)
569
        if len(values) < 3 or len(values) > 4:
Tiago Peixoto's avatar
Tiago Peixoto committed
570
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
571
572
        deg1 = degree(values[0])
        deg2 = degree(values[1])
573
574
575
576
577
578
        if len(values) == 4:
            weight = values[2]
            file_name = values[3]
        else:
            weight = ""
            file_name = values[2]
Tiago Peixoto's avatar
Tiago Peixoto committed
579
        if just_file:
580
581
            return file_name
        return (graph.GetAverageNearestNeighboursCorrelation(deg1, deg2, weight), file_name)
Tiago Peixoto's avatar
Tiago Peixoto committed
582
583
    elif opt.name == "assortativity-coefficient":
        values = parse_values(opt.value)
584
        if len(values) != 2:
Tiago Peixoto's avatar
Tiago Peixoto committed
585
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
586
        deg = degree(values[0])
Tiago Peixoto's avatar
Tiago Peixoto committed
587
        if just_file:
588
            return values[1]
589
590
591
592
593
594
595
596
597
598
599
600
601
        (r,err) = graph.GetAssortativityCoefficient(deg)
        ret = "%f\t%f" % (r,err)
        return (ret, values[1])
    elif opt.name == "scalar-assortativity-coefficient":
        values = parse_values(opt.value)
        if len(values) != 2:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        deg = degree(values[0])
        if just_file:
            return values[1]
        (r,err) = graph.GetScalarAssortativityCoefficient(deg)
        ret = "%f\t%f" % (r,err)
        return (ret, values[1])
602
603
604
605
606
607
608
609
    elif opt.name == "average-vertex-property" or opt.name == "average-edge-property":
        values = parse_values(opt.value)
        if len(values) != 2:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if opt.name == "average-vertex-property":
            deg = degree(values[0])
            hist = graph.GetVertexHistogram(deg)
        else:
610
            hist = graph.GetEdgeHistogram(values[0])
611
        ret = "%f\t%f" % get_mean(hist)
Tiago Peixoto's avatar
Tiago Peixoto committed
612
        if just_file:
613
614
            return values[1]
        return (ret,values[1])
Tiago Peixoto's avatar
Tiago Peixoto committed
615
616
617
    elif opt.name == "global-clustering-coefficient":
        if just_file:
            return opt.value
618
619
620
        (avg, dev) = graph.GetGlobalClustering()
        ret = "%f\t%f" % (avg, dev)
        return (ret, opt.value)
621
    elif opt.name == "local-clustering-coefficient":
Tiago Peixoto's avatar
Tiago Peixoto committed
622
623
624
        if just_file:
            return None
        graph.SetLocalClusteringToProperty(opt.value)
625
    elif opt.name == "extended-clustering-coefficient":
626
627
628
629
630
        if just_file:
            return None
        values = parse_values(opt.value)
        if len(values) == 0 or len(values) > 2:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
631
        graph.SetExtendedClusteringToProperty(values[0],int(values[1]))
Tiago Peixoto's avatar
Tiago Peixoto committed
632
633
634
635
    elif opt.name == "community-structure":
        if just_file:
            return None
        values = parse_values(opt.value)
636
        if len(values) < 1 or len(values) > 2:
Tiago Peixoto's avatar
Tiago Peixoto committed
637
638
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        prop = values[0]
639
640
        if len(values) > 1:
            param = values[1]
Tiago Peixoto's avatar
Tiago Peixoto committed
641
        else:
642
            param = ""
Tiago Peixoto's avatar
Tiago Peixoto committed
643
        try:
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
            if  get_suboption("g", param) != False:
                g = float( get_suboption("g", param))
            else:
                g = 1.0
            if  get_suboption("N", param) != False:
                N = int( get_suboption("N", param))
            else:
                N = 1000
            if  get_suboption("Tmin", param) != False:
                Tmin = float( get_suboption("Tmin", param))
            else:
                Tmin = 0.0
            if  get_suboption("Tmax", param) != False:
                Tmax = float( get_suboption("Tmax", param))
            else:
                Tmax = 100.0
660
661
662
663
            if  get_suboption("spins", param) != False:
                spins = int( get_suboption("spins", param))
            else:
                spins = 0
664
665
            if  get_suboption("corr_type", param) != False:
                if  get_suboption("corr_type", param)  == "random":
666
                    corr = CommCorr.ErdosReyni
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
                elif  get_suboption("corr_type", param)  == "uncorrelated":
                    corr = CommCorr.Uncorrelated
                elif  get_suboption("corr_type", param)  == "correlated":
                    corr = CommCorr.Correlated
                else:
                    raise OptionError(opt.name, "invalid correlation type value '%s'" %  get_suboption("corr_type", param) )
            else:
                corr = CommCorr.Uncorrelated
            if  get_suboption("seed", param) != False:
                seed = int( get_suboption("seed", param))
            else:
                seed = int(clock())
            if  get_suboption("weight", param) != False:
                weight =  get_suboption("weight", param)
            else:
                weight = ""
            verbose =  get_suboption("verbose", param) != False
Tiago Peixoto's avatar
Tiago Peixoto committed
684
685
686
687
688
            if  get_suboption("history", param) != False:
                history =  get_suboption("history", param)
            else:
                history = ""
                                                    
Tiago Peixoto's avatar
Tiago Peixoto committed
689
690
        except ValueError,e:
            raise OptionError(opt.name, "invalid value '%s': %s" % (opt.value, e))
Tiago Peixoto's avatar
Tiago Peixoto committed
691
        graph.GetCommunityStructure(g, corr, N, Tmin, Tmax, spins, seed, verbose, history, weight, prop)
692
    elif opt.name == "modularity":
Tiago Peixoto's avatar
Tiago Peixoto committed
693
694
695
696
697
698
699
700
701
702
        values = parse_values(opt.value)
        if len(values) < 2 or len(values) > 3:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        prop, weight, file_name = values[0], "", values[1]
        if len(values) > 2:
            weight = values[1]
            file_name = values[2]
        if just_file:
            return file_name
        return (graph.GetModularity(weight, prop), file_name)
Tiago Peixoto's avatar
   
Tiago Peixoto committed
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
    elif opt.name == "random-rewire":
        values = parse_values(opt.value)
        if len(values) == 0:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        strat = RewireStrat.Uncorrelated
        if get_suboption("correlated", values[0]) != False:
            strat = RewireStrat.Correlated
        if get_suboption("uncorrelated", values[0]) != False:
            strat = RewireStrat.Uncorrelated
        if get_suboption("no-self-loops", values[0]) != False:
            self_loops = False
        else:
            self_loops = True
        if get_suboption("no-parallel-edges", values[0]) != False:
            parallel = False
        else:
            parallel = True
        if get_suboption("seed", values[0]) != False:
            seed = int(get_suboption("seed", values[0]))
        else:
            seed = seed = int(time())
        if just_file:
            return
        graph.RandomRewire(strat, self_loops, parallel, seed)
727
728
729
730
731
732
733
734
735
736
737
738
    elif opt.name == "community-graph":
        values = parse_values(opt.value)
        if len(values) < 2 or len(values) > 3:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        prop, file_name = values[0], values[1]
        if len(values) > 2:
            format = values[2]
        else:
            format = ""
        if just_file:
            return
        return (graph.GetCommunityNetwork(prop, file_name, format))
Tiago Peixoto's avatar
Tiago Peixoto committed
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
    elif opt.name == "compute-spring-block-layout":
        if just_file:
            return None
        values = parse_values(opt.value)
        if len(values) == 0 or len(values) > 2:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        iterations,seed = 0,0
        try:
            iterations = int(values[0])
            if len(values) > 1:
                seed = int(values[1])
            else:
                seed = int(time())
        except ValueError:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        graph.ComputeGraphLayoutSpringBlock(iterations,seed)
    elif opt.name == "compute-gursoy-atun-layout":
        if just_file:
            return None
        values = parse_values(opt.value)
        if len(values) == 0 or len(values) > 2:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        iterations,seed = 0,0
        try:
            iterations = int(values[0])
            if len(values) > 1:
                seed = int(values[1])
            else:
                seed = int(time())
        except ValueError:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        graph.ComputeGraphLayoutGursoy(iterations,seed)
    elif opt.name == "vertex-filter" or opt.name == "edge-filter":
        if just_file:
            return None
        filter_vars = dict()
775
776
        def filter_function():
            return not (eval(opt.value,filter_vars))
Tiago Peixoto's avatar
Tiago Peixoto committed
777
        if opt.name == "vertex-filter":
778
            graph.SetGenericVertexFilter((filter_function,filter_vars))
Tiago Peixoto's avatar
Tiago Peixoto committed
779
        else:
780
            graph.SetGenericEdgeFilter((filter_function,filter_vars))
Tiago Peixoto's avatar
Tiago Peixoto committed
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
    elif opt.name == "vertex-range-filter" or opt.name == "edge-range-filter":
        if just_file:
            return None
        values = parse_values(opt.value)
        if len(values) != 2:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if (len(values[1].split()) != 2):
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        filter_range = (0,0)
        try:
            vals = values[1].split()
            filter_range = (float(vals[0]), float(vals[1]))
        except ValueError:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if opt.name == "vertex-range-filter":
            graph.SetVertexFilterProperty(values[0])
            graph.SetVertexFilterRange(filter_range)
        if opt.name == "edge-range-filter":
            graph.SetEdgeFilterProperty(values[0])
            graph.SetEdgeFilterRange(filter_range)
    elif opt.name == "reset-vertex-filter":
        if just_file:
            return None
        graph.SetVertexFilterProperty("")
        graph.SetGenericVertexFilter(None)
    elif opt.name == "reset-edge-filter":
        if just_file:
            return None
        graph.SetEdgeFilterProperty("")
        graph.SetGenericEdgeFilter(None)
    elif opt.name == "directed":
        if just_file:
            return None
        graph.SetDirected(True)
    elif opt.name == "undirected":
        if just_file:
            return None
        graph.SetDirected(False)
    elif opt.name == "reverse":
        if just_file:
            return None
        graph.SetReversed(not graph.GetReversed())
Tiago Peixoto's avatar
Tiago Peixoto committed
823
    elif opt.name in ["edit-vertex-property", "edit-edge-property",  "edit-graph-property"]:
824
        values = parse_values(opt.value)
825
        if len(values) < 2 or len(values) > 3:
826
827
828
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if just_file:
            return None
829
830
831
832
833
834
        if len(values) == 2:
            val_type = "double"
            expr = values[1]
        else:
            val_type = values[1].strip()
            expr = values[2]
835
        edit_vars = dict()
836
837
        if "file:" in expr:
            expressions = expr.split("file:")
838
839
            if len(expressions) > 1:
                exec expressions[0] in edit_vars
840
                exp_file = expressions[1]
841
            else:
842
843
                exp_file = expressions[0]            
            exec open(os.path.expanduser(exp_file.strip())).read() in edit_vars
844
845
846
            edit_function = edit_vars["edit_function"]
        else:
            def edit_function():
847
                return (eval(expr,edit_vars))
848
        if opt.name == "edit-vertex-property":
849
            graph.EditVertexProperty(values[0], val_type, (edit_function,edit_vars))
Tiago Peixoto's avatar
Tiago Peixoto committed
850
        elif opt.name == "edit-edge-property":
851
            graph.EditEdgeProperty(values[0], val_type, (edit_function,edit_vars))
Tiago Peixoto's avatar
Tiago Peixoto committed
852
853
        else:
            graph.EditGraphProperty(values[0], val_type, (edit_function,edit_vars))
Tiago Peixoto's avatar
Tiago Peixoto committed
854
855
856
857
858
859
860
861
    elif opt.name == "remove-vertex-property":
        if just_file:
            return None
        graph.RemoveVertexProperty(opt.value)
    elif opt.name == "remove-edge-property":
        if just_file:
            return None
        graph.RemoveEdgeProperty(opt.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
862
863
864
865
    elif opt.name == "remove-graph-property":
        if just_file:
            return None
        graph.RemoveGraphProperty(opt.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
866
867
868
869
870
871
872
873
    elif opt.name == "insert-edge-index-property":
        if just_file:
            return None
        graph.InsertEdgeIndexProperty(opt.value)
    elif opt.name == "insert-vertex-index-property":
        if just_file:
            return None
        graph.InsertVertexIndexProperty(opt.value)          
874
875
876
877
    elif opt.name == "list-properties":
        if just_file:
            return None
        graph.ListProperties()          
Tiago Peixoto's avatar
Tiago Peixoto committed
878
879
880
881
882
883
884
885
886
887
        
def open_file(name, mode="w"):
    if name == "-":
        return sys.stdout
    if name.endswith("bz2"):
        return bz2.BZ2File(name, mode)
    if name.endswith("gz"):
        return gzip.GzipFile(name, mode)
    return file(name, mode)

888
889
def write_data(data, file, prefix=None):
    if prefix != None:
Tiago Peixoto's avatar
Tiago Peixoto committed
890
        prefix = "%s\t" % prefix
891
892
    else:
        prefix = ""
Tiago Peixoto's avatar
Tiago Peixoto committed
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
    if data.__class__ == dict:
        # it is a histogram
        keys = data.keys()
        keys.sort()
        for k in keys:
            file.write(prefix)
            if k.__class__ == tuple:
                # higher dimensional histogram
                for i in xrange(0,len(k)):
                    file.write("%s\t" % str(k[i]))                
            else:
                file.write("%s\t" % (str(k)))
            if data[k].__class__ == tuple:
                for i in xrange(0,len(data[k])):
                    file.write("%s\t" % str(data[k][i]))
                file.write("\n")
            else:
                file.write("%s\n" % str(data[k]))
    else:
        # single value
        file.write("%s%s\n" % (prefix,str(data)))
914
915
    if file.__class__ != bz2.BZ2File:
        file.flush()
Tiago Peixoto's avatar
Tiago Peixoto committed
916
917
918
919
920
921
922
923
924
925
926

class HistoryException (Exception):
    def __init__(self, file=None, old=None, what=None):
        if what == None:
            self.what = "error copying contents from file '%s' to file '%s'" % (old,file)
        else:
            self.what = what
    def __str__(self):
        return self.what

class HistoryFile:
927
    def __init__(self, file_name, overwrite):
Tiago Peixoto's avatar
Tiago Peixoto committed
928
        self.file_name = os.path.expanduser(file_name)
929
        self.last_prefix = None
Tiago Peixoto's avatar
Tiago Peixoto committed
930
        self.file = None
931
        self.time = clock()
Tiago Peixoto's avatar
Tiago Peixoto committed
932
933
934
935
936
        self.temp = self.file_name + "___temp"
        if self.file_name.endswith(".bz2"):
            self.temp = self.file_name.rstrip(".bz2") + "___temp.bz2"
        if self.file_name.endswith(".gz"):
            self.temp = self.file_name.rstrip(".gz") + "___temp.gz"
937
        match = re.compile("([0-9]+)([d,h,m,s])").match(options.refresh_rate)
Tiago Peixoto's avatar
Tiago Peixoto committed
938
939
940
941
942
943
944
945
946
947
        if match != None:
            self.rate = int(match.group(1))
            modifier = match.group(2)
            if modifier == "m":
                self.rate *= 60
            if modifier == "h":
                self.rate *= 60
            if modifier == "d":
                self.rate *= 24
        else:
948
949
            raise HistoryException(what="invalid history refresh rate value: %s" % options.represh_rate)
        if os.path.exists(self.file_name) and self.file_name != "-" and not overwrite:            
Tiago Peixoto's avatar
Tiago Peixoto committed
950
951
952
953
954
955
956
957
958
959
960
            # test the integrity of the compressed files
            try:
                if self.file_name.endswith(".bz2") or self.file_name.endswith(".gz"):
                    for line in open_file(self.file_name,"r"):
                        pass
            except (IOError, EOFError):
                if not os.path.exists(self.temp):
                    old = open_file(self.temp, "w")
                    old.write("")
                    old.close()
                os.rename(self.temp, self.file_name)
961
            #upadate last_prefix
Tiago Peixoto's avatar
Tiago Peixoto committed
962
            for line in open_file(self.file_name, "r"):
963
                self.last_prefix = line.split()[0]
Tiago Peixoto's avatar
Tiago Peixoto committed
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
            self.refresh()
        else:
            self.file = open_file(self.file_name, "w")

    def __del__(self):
        if self.file != None:
            self.file.close()
        if self.temp != None:
            if os.path.exists(self.temp):
                os.remove(self.temp)

    def refresh(self):
        try:                                                                        
            if self.file_name.endswith(".bz2") or  self.file_name.endswith(".gz"):
                os.rename(self.file_name, self.temp)
                # copy history from old file to new file
                self.file = open_file(self.file_name, "w")
                for line in open_file(self.temp, "r"):
                    self.file.write(line)
            else:
                self.file = open_file(self.file_name, "a")
        except:
            os.rename(self.old, self.file_name)
            raise HistoryException(self.file_name, self.temp)
    
            
    def write(self, data, prefix):
        write_data(data, self.file, prefix)
992
        if clock() - self.time > self.rate:
Tiago Peixoto's avatar
Tiago Peixoto committed
993
994
            self.file.close()
            self.refresh()
995
            self.time = clock()
Tiago Peixoto's avatar
Tiago Peixoto committed
996
997
998
999
1000

# signal handling
graph.InitSignalHandling()

# parse each option in order
For faster browsing, not all history is shown. View entire blame