graph-tool 37.5 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#! /usr/bin/env python
# (C) 2006 by Tiago de Paula Peixoto <tiago@forked.de>
#
# 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
# the Free Software Foundation; either version 2 of the License, or
# (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
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
Tiago Peixoto's avatar
Tiago Peixoto committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

import sys

sys.path.append(".")

from libgraph_tool import *

from optparse import *
import string
import os
import os.path
import re
import struct
import fcntl
import termios
import gzip
import bz2
import string
import time
import signal
from time import *
38
import math
Tiago Peixoto's avatar
Tiago Peixoto committed
39

40
41
42
#import gc # garbage collector
#gc.enable()
#gc.set_debug(gc.DEBUG_LEAK|gc.DEBUG_STATS)
Tiago Peixoto's avatar
Tiago Peixoto committed
43
44
45
46
47
48

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():
49
50
51
52
53
    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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    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")
86
87
modification.add_option("--edit-vertex-property", action="callback", callback=push_option, type="string", metavar="PROPERTY|EXPRESSION", help="edit the selected vertex property")
modification.add_option("--edit-edge-property", action="callback", callback=push_option, type="string", metavar="PROPERTY|EXPRESSION", help="edit the selected edge property")
Tiago Peixoto's avatar
Tiago Peixoto committed
88
89
90
91
92
93
94
95
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")
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")

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")
96
97
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")
98
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")
99
statistics.add_option("--distance-histogram", action="callback", callback=push_option, type="string", metavar="[WEIGHT|]FILE", help="get the distance histogram")
100
101
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")
102
103
104
statistics.add_option("--sampled-distance-histogram", action="callback", callback=push_option, type="string", metavar="[WEIGHT|]SAMPLES|SEED|FILE", help="get the sampled distance histogram")
statistics.add_option("--average-sampled-distance", action="callback", callback=push_option, type="string", metavar="[WEIGHT|]SAMPLES|SEED|FILE", help="get the average sampled distance")
statistics.add_option("--average-sampled-harmonic-distance", action="callback", callback=push_option, type="string", metavar="[WEIGHT|]SAMPLES|SEED|FILE", help="get the average sampled harmonic distance")
Tiago Peixoto's avatar
Tiago Peixoto committed
105
statistics.add_option("--component-size-histogram", action="callback", callback=push_option, type="string", metavar="FILE", help="get the component size histogram")
106
107
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")
108
statistics.add_option("--reciprocity", action="callback", callback=push_option, type="string", metavar="FILE", help="get the edge reciprocity")
109
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
110
111

correlations =  parser.add_option_group("Correlations")
112
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")
113
114
115
correlations.add_option("--vertex-correlation-histogram", action="callback", callback=push_option, type="string", metavar="DEGREE1|DEGREE2|FILE", help="get the degree correlation histogram. Scalar properties are also accepted in place of DEGREE")
correlations.add_option("--average-nearest-neighbours-correlation", action="callback", callback=push_option, type="string", metavar="ORIGIN-DEGREE|DEGREE|FILE", help="get the average nearest neighbours correlation")
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")
116
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")
117
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
118
119
120
121

clustering =  parser.add_option_group("Clustering")
clustering.add_option("--set-local-clustering-to-property", action="callback", callback=push_option, type="string", metavar="PROPERTY", help="set the local clustering coefficient to vertex property")
clustering.add_option("--global-clustering-coefficient", action="callback", callback=push_option, type="string", metavar="FILE", help="get the global clustering coefficient")
122
clustering.add_option("--set-extended-clustering-to-property", 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
123
124
125
126
127
128

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")

layout =  parser.add_option_group("History")
129
130
131
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

(options, args) = parser.parse_args()

graph = GraphInterface()

def parse_values(value):
    "this will parse the options with multiple values"
    p = re.compile(r"([^\|'\"]+|[^\|]+'[^']*'|[^\|]+\"[^\"]*\")(?:\||$)")
    values = p.findall(value)
    values = [x.strip() for x in values]
    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

166
167
168
169
170
171
def get_mean(hist):
    avg,dev,count = 0.0,0.0,0.0
    for k,v in hist.iteritems():
        avg += k*v
        dev += k*k*v
        count += v
172
173
174
175
176
    try:
        avg /= count
        dev = math.sqrt(dev/count - avg*avg)/math.sqrt(count)
    except ZeroDivisionError:
        avg = dev = float("nan") # nans are ok, since graph can be empty
177
178
    return (avg,dev)

Tiago Peixoto's avatar
Tiago Peixoto committed
179
180
181
182
183
184
class OptionError(Exception):
    def __init__(self, option, error):
        self.what = "error parsing option %s: %s" % (option,error)
    def __str__(self):
        return self.what

185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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"
    inv_pjk_ceil = ""
    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)
    variables = dict()
    # default packages to be included
    exec """
try:
    from math import *
    from scipy import *
    from scipy.special import *
    from scipy.optimize import *
    from scipy.optimize.minpack import *
233
234
    import psyco
    psyco.full()
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
except ImportError:
    pass
"""  in variables
    # some predefined functions
    exec """
def inv_poisson(p,m):
    return round(fsolve(lambda k,l: gammaincc(k,l)-p, m, (m))-0.5+1e-15)
""" in variables
    exec """
def inv_exponential(p,m):
    return round(log(1-p)/log(float(m)/(m+1))-0.5+1e-15)
""" in variables
    exec """
def inv_power_law(p,b):
    return round((1-p)**(-1/(b-1)) - 1)
""" in variables    
    exec """
def step(x):
    if x >= 0:
        return 1.0
    else:
        return 0.0
""" in variables
    # read main funtions
    exec "def pjk(j,k):\n   return %s\n" % pjk in variables
    exec "def pjk_ceil(j,k):\n   return %s\n" % pjk_ceil in variables    
    exec "m_pjk = %s" % m_pjk in variables    
    m_pjk = float(variables["m_pjk"])
    if "file:" in inv_pjk_ceil:
        exec open(inv_pjk_ceil.replace("file:","").strip()).read() in variables
    else:
        exec """
def inv_pjk_ceil(p,r):
    retval = %s
    return (int(round(retval[0])),int(round(retval[1])))
""" % inv_pjk_ceil in variables
    exec "def corr(jl,kl,j,k):\n   return %s\n" % corr in variables
    exec "def corr_ceil(jl,kl,j,k):\n   return %s\n" % corr_ceil in variables
    exec "m_corr = %s" % m_corr in variables
    m_corr = float(variables["m_corr"])
    if "file:" in inv_corr_ceil:
        exec open(inv_corr_ceil.replace("file:","").strip()).read() in variables
    else:
        exec """
def inv_corr_ceil(p,r,j,k):
    retval = %s
    return (int(round(retval[0])),int(round(retval[1])))
""" % inv_corr_ceil in variables
    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
287
288
289
290
291
292
293
294
295
296
297
298
299
def parse_option(opt, just_file=False):
    "this will execute an aption, and return either None, or a tuple with the result and the respective file name, if it exists"
    if opt.name == "load":
        if just_file:
            return None
        graph.ReadFromFile(opt.value)
    elif opt.name == "save":
        if just_file:
            return None
        graph.WriteToFile(opt.value)
    elif opt.name == "correlated-configurational-model":
        if just_file:
            return None
300
        generate_graph(opt.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
301
302
303
304
305
306
307
308
    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)
309
310
311
312
    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
313
        if just_file:
314
315
            return values[2]
        return (graph.GetCombinedVertexHistogram(degree(values[0]),degree(values[1])), values[2])
316
317
318
319
320
321
322
    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])
323
324
325
326
327
328
329
330
331
332
333
    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
334
    elif opt.name == "average-distance":
335
336
337
338
339
340
341
        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
342
        if just_file:
343
            return file_name
344
        return ("%f\t%f" % get_mean(graph.GetDistanceHistogram(weight)), file_name)
Tiago Peixoto's avatar
Tiago Peixoto committed
345
    elif opt.name == "average-harmonic-distance":
346
347
348
349
350
351
352
        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
353
        if just_file:
354
            return file_name
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
        hist = graph.GetDistanceHistogram(weight)
        avg, err = hist_mean(dict((1.0/k,v) for k,v in hist.iteritems()))
        return ("%f\t%f" % (1.0/avg,1.0/err) , file_name)
    elif opt.name == "sampled-distance-histogram":
        values = parse_values(opt.value)
        if len(values) > 4 or len(values) < 3:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if len(values) == 3:
            weight, samples, seed, file_name = "", int(values[0]), int(values[1]), values[2]
        else:
            weight, samples, seed, file_name = values[0], int(values[1]), int(values[2]), values[3]
        if just_file:
            return file_name
        return (graph.GetSampledDistanceHistogram(weight, samples, seed), file_name)
    elif opt.name == "average-sampled-distance":
        values = parse_values(opt.value)
        if len(values) > 4 or len(values) < 3:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if len(values) == 3:
            weight, samples, seed, file_name = "", int(values[0]), int(values[1]), values[2]
        else:
            weight, samples, seed, file_name = values[0], int(values[1]), int(values[2]), values[3]
        if just_file:
            return file_name
        return ("%f\t%f" % get_mean(graph.GetSampledDistanceHistogram(weight, samples, seed)), file_name)
    elif opt.name == "average-sampled-harmonic-distance":
        values = parse_values(opt.value)
        if len(values) > 4 or len(values) < 3:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if len(values) == 3:
            weight, samples, seed, file_name = "", int(values[0]), int(values[1]), values[2]
        else:
            weight, samples, seed, file_name = values[0], int(values[1]), int(values[2]), values[3]
        if just_file:
            return file_name
        hist = graph.GetSampledDistanceHistogram(weight, samples, seed)
        avg, err = hist_mean(dict((1.0/k,v) for k,v in hist.iteritems()))
        return ("%f\t%f" % (1.0/avg,1.0/err) , file_name)
Tiago Peixoto's avatar
Tiago Peixoto committed
393
394
395
396
    elif opt.name == "component-size-histogram":
        if just_file:
            return opt.value
        return (graph.GetComponentSizeHistogram(), opt.value)
397
    elif opt.name == "vertex-histogram":
Tiago Peixoto's avatar
Tiago Peixoto committed
398
399
400
401
402
403
        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]
404
405
406
407
408
409
410
411
        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])
412
413
414
415
    elif opt.name == "reciprocity":
        if just_file:
            return opt.value
        return (graph.GetReciprocity(), opt.value)
416
417
418
419
420
421
422
423
424
425
426
    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)
427
    elif opt.name == "vertex-correlation-histogram":
Tiago Peixoto's avatar
Tiago Peixoto committed
428
429
430
431
432
433
434
        values = parse_values(opt.value)
        if len(values) != 3:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        deg1 = degree(values[0])
        deg2 = degree(values[1])
        if just_file:
            return values[2]
435
436
        return (graph.GetVertexCorrelationHistogram(deg1,deg2), values[2])
    elif opt.name == "edge-vertex-correlation-histogram":
Tiago Peixoto's avatar
Tiago Peixoto committed
437
438
439
440
441
442
443
        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]
444
445
        return (graph.GetEdgeVertexCorrelationHistogram(deg1,values[1],deg2), values[3])
    elif opt.name == "average-nearest-neighbours-correlation":
Tiago Peixoto's avatar
Tiago Peixoto committed
446
        values = parse_values(opt.value)
447
        if len(values) != 3:
Tiago Peixoto's avatar
Tiago Peixoto committed
448
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
449
450
        deg1 = degree(values[0])
        deg2 = degree(values[1])
Tiago Peixoto's avatar
Tiago Peixoto committed
451
        if just_file:
452
            return values[2]
453
        return (graph.GetAverageNearestNeighboursCorrelation(deg1,deg2), values[2])
Tiago Peixoto's avatar
Tiago Peixoto committed
454
455
    elif opt.name == "assortativity-coefficient":
        values = parse_values(opt.value)
456
        if len(values) != 2:
Tiago Peixoto's avatar
Tiago Peixoto committed
457
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
458
        deg = degree(values[0])
Tiago Peixoto's avatar
Tiago Peixoto committed
459
        if just_file:
460
            return values[1]
461
462
463
464
465
466
467
468
469
470
471
472
473
        (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])
474
475
476
477
478
479
480
481
    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:
482
            hist = graph.GetEdgeHistogram(values[0])
483
        ret = "%f\t%f" % get_mean(hist)
Tiago Peixoto's avatar
Tiago Peixoto committed
484
        if just_file:
485
486
            return values[1]
        return (ret,values[1])
Tiago Peixoto's avatar
Tiago Peixoto committed
487
488
489
    elif opt.name == "global-clustering-coefficient":
        if just_file:
            return opt.value
490
491
492
        (avg, dev) = graph.GetGlobalClustering()
        ret = "%f\t%f" % (avg, dev)
        return (ret, opt.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
493
494
495
496
    elif opt.name == "set-local-clustering-to-property":
        if just_file:
            return None
        graph.SetLocalClusteringToProperty(opt.value)
497
498
499
500
501
502
    elif opt.name == "set-extended-clustering-to-property":
        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)
503
        graph.SetExtendedClusteringToProperty(values[0],int(values[1]))
Tiago Peixoto's avatar
Tiago Peixoto committed
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
    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()
540
541
        def filter_function():
            return not (eval(opt.value,filter_vars))
Tiago Peixoto's avatar
Tiago Peixoto committed
542
        if opt.name == "vertex-filter":
543
            graph.SetGenericVertexFilter((filter_function,filter_vars))
Tiago Peixoto's avatar
Tiago Peixoto committed
544
        else:
545
            graph.SetGenericEdgeFilter((filter_function,filter_vars))
Tiago Peixoto's avatar
Tiago Peixoto committed
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
    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())
588
589
590
591
592
593
594
    elif opt.name == "edit-vertex-property" or opt.name == "edit-edge-property":
        values = parse_values(opt.value)
        if len(values) != 2:
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
        if just_file:
            return None
        edit_vars = dict()
595
596
        def edit_function():
            return (eval(values[1],edit_vars))
597
        if opt.name == "edit-vertex-property":
598
            graph.EditVertexProperty(values[0],(edit_function,edit_vars))
599
        else:
600
            graph.EditEdgeProperty(values[0],(edit_function,edit_vars))
Tiago Peixoto's avatar
Tiago Peixoto committed
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
    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)
    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)          
        
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)

def write_data(data, file, prefix=""):
    if prefix != "":
        prefix = "%s\t" % prefix
    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)))
651
652
    if file.__class__ != bz2.BZ2File:
        file.flush()
Tiago Peixoto's avatar
Tiago Peixoto committed
653
654
655
656
657
658
659
660
661
662
663

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:
664
    def __init__(self, file_name, overwrite):
Tiago Peixoto's avatar
Tiago Peixoto committed
665
        self.file_name = os.path.expanduser(file_name)
666
        self.last_prefix = None
Tiago Peixoto's avatar
Tiago Peixoto committed
667
        self.file = None
668
        self.time = clock()
Tiago Peixoto's avatar
Tiago Peixoto committed
669
670
671
672
673
        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"
674
        match = re.compile("([0-9]+)([d,h,m,s])").match(options.refresh_rate)
Tiago Peixoto's avatar
Tiago Peixoto committed
675
676
677
678
679
680
681
682
683
684
        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:
685
686
            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
687
688
689
690
691
692
693
694
695
696
697
            # 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)
698
            #upadate last_prefix
Tiago Peixoto's avatar
Tiago Peixoto committed
699
            for line in open_file(self.file_name, "r"):
700
                self.last_prefix = line.split()[0]
Tiago Peixoto's avatar
Tiago Peixoto committed
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
            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)
729
        if clock() - self.time > self.rate:
Tiago Peixoto's avatar
Tiago Peixoto committed
730
731
            self.file.close()
            self.refresh()
732
            self.time = clock()
Tiago Peixoto's avatar
Tiago Peixoto committed
733
734
735
736
737
738
739

# signal handling
graph.InitSignalHandling()

# parse each option in order
try:
    history_range = None
740
    overwrite_history = False
Tiago Peixoto's avatar
Tiago Peixoto committed
741
    for opt in option_list:
742
        if opt.name == "for" or opt.name == "history":
Tiago Peixoto's avatar
Tiago Peixoto committed
743
744
            # the rest of the commands are to be treated as history template
            history_range = opt
745
746
            if opt.name == "for":
                overwrite_history = True
Tiago Peixoto's avatar
Tiago Peixoto committed
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
            break
        retval = parse_option(opt)
        if retval != None:
            if retval[1] != None:
                prefix = ""
                if retval[1] == "-":
                    prefix = opt.name.replace("-"," ")+": "
                write_data(retval[0], open_file(retval[1]), prefix)
                
    # deal with history
    if history_range != None:
        class MyTemplate(string.Template):
            delimiter = "%"
        values = parse_values(history_range.value)
        if len(values) != 3:
762
            raise OptionError("history", "invalid value '%s'" % history_range.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
763
764
765
766
        histories = option_list[option_list.index(history_range)+1:]
        history_files = dict() # open history files
        variables = dict() # template variables
        exec values[0] in variables #init
767
        exec "___continue = %s" % values[1] in variables # condition
Tiago Peixoto's avatar
Tiago Peixoto committed
768
769
770
771
        count = 0
        while variables["___continue"]:
            for opt in histories:
                new_opt = Opt(opt.name,opt.value)
772
                uses_prefix = True
Tiago Peixoto's avatar
Tiago Peixoto committed
773
                if new_opt.value != None:
774
775
                    if "%prefix" in opt.value:
                        uses_prefix = False
Tiago Peixoto's avatar
Tiago Peixoto committed
776
777
778
779
780
781
782
783
784
785
                    t = MyTemplate(new_opt.value)
                    try:
                        new_opt.value = t.substitute(variables)
                    except KeyError:
                        raise OptionError(opt.name, "invalid value '%s'" % opt.value)
                file_name = parse_option(new_opt, just_file=True)
                if file_name != None:
                    prefix = str(count)
                    if variables.has_key("prefix"):
                        prefix = str(variables["prefix"])
786
                    if not history_files.has_key(opt.name):
787
                        history_files[opt.name] = HistoryFile(file_name, overwrite_history)
788
789
                    else:
                        if history_files[opt.name].file_name != os.path.expanduser(file_name):
790
                            history_files[opt.name] = HistoryFile(file_name, overwrite_history)
791
792
793
794
795
796
797
                    try:
                        if history_files[opt.name].last_prefix != None:
                            is_new = float(prefix) > float(history_files[opt.name].last_prefix)
                        else:
                            is_new = True
                    except ValueError:
                        is_new = True
798
                    if is_new or overwrite_history:
Tiago Peixoto's avatar
Tiago Peixoto committed
799
                        data = parse_option(new_opt)[0]
800
801
802
803
                        if uses_prefix:
                            history_files[opt.name].write(data, prefix)
                        else:
                            history_files[opt.name].write(data, "")
Tiago Peixoto's avatar
Tiago Peixoto committed
804
805
                else:
                    parse_option(new_opt)
806
807
            exec values[2] in variables # step
            exec "___continue = %s" % values[1] in variables # condition
Tiago Peixoto's avatar
Tiago Peixoto committed
808
            count += 1
809
        del history_files
Tiago Peixoto's avatar
Tiago Peixoto committed
810
            
811
812
except (OptionError, HistoryException, IOError, RuntimeError), e:
    print "graph-tool error:", e
Tiago Peixoto's avatar
Tiago Peixoto committed
813
814
except KeyboardInterrupt:
    pass