graph-tool 31.3 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
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#! /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
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

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
43
44
45
46
47
48
49

try:
    import psyco
except ImportError:
    pass

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():
50
51
52
53
54
    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
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
86
87
88
89
90
91
92
93
94
95
    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")
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")
modification.add_option("--remove-parallel-edges", action="callback", callback=push_option, help="remove parallel edges from graph")

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
100
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")
Tiago Peixoto's avatar
Tiago Peixoto committed
101
statistics.add_option("--component-size-histogram", action="callback", callback=push_option, type="string", metavar="FILE", help="get the component size histogram")
102
103
104
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")

Tiago Peixoto's avatar
Tiago Peixoto committed
105
106

correlations =  parser.add_option_group("Correlations")
107
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")
108
109
110
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")
111
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")
112
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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

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

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")
layout.add_option("--history", action="callback", callback=push_option, type="string", metavar="INIT|CONDITION|STEP", help="compute graph history")
layout.add_option("--history-rate", type="string", metavar="TIME", default="1h", help="history file refresh rate")

(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

class OptionError(Exception):
    def __init__(self, option, error):
        self.what = "error parsing option %s: %s" % (option,error)
    def __str__(self):
        return self.what

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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
233
234
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
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 *
    import psyco 
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
266
267
268
269
270
271
272
273
274
275
276
277
278
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
279
        generate_graph(opt.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
280
281
282
283
284
285
286
287
    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)
288
289
290
291
    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
292
        if just_file:
293
294
            return values[2]
        return (graph.GetCombinedVertexHistogram(degree(values[0]),degree(values[1])), values[2])
295
296
297
298
299
300
301
    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])
Tiago Peixoto's avatar
Tiago Peixoto committed
302
    elif opt.name == "average-distance":
303
304
305
306
307
308
309
        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
310
        if just_file:
311
312
            return file_name
        return (graph.GetAverageDistance(weight), file_name)
Tiago Peixoto's avatar
Tiago Peixoto committed
313
    elif opt.name == "average-harmonic-distance":
314
315
316
317
318
319
320
        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
321
        if just_file:
322
323
            return file_name
        return (graph.GetAverageHarmonicDistance(weight), file_name)
Tiago Peixoto's avatar
Tiago Peixoto committed
324
325
326
327
    elif opt.name == "component-size-histogram":
        if just_file:
            return opt.value
        return (graph.GetComponentSizeHistogram(), opt.value)
328
    elif opt.name == "vertex-histogram":
Tiago Peixoto's avatar
Tiago Peixoto committed
329
330
331
332
333
334
        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]
335
336
337
338
339
340
341
342
343
        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])
    elif opt.name == "vertex-correlation-histogram":
Tiago Peixoto's avatar
Tiago Peixoto committed
344
345
346
347
348
349
350
        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]
351
352
        return (graph.GetVertexCorrelationHistogram(deg1,deg2), values[2])
    elif opt.name == "edge-vertex-correlation-histogram":
Tiago Peixoto's avatar
Tiago Peixoto committed
353
354
355
356
357
358
359
        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]
360
361
        return (graph.GetEdgeVertexCorrelationHistogram(deg1,values[1],deg2), values[3])
    elif opt.name == "average-nearest-neighbours-correlation":
Tiago Peixoto's avatar
Tiago Peixoto committed
362
        values = parse_values(opt.value)
363
        if len(values) != 3:
Tiago Peixoto's avatar
Tiago Peixoto committed
364
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
365
366
        deg1 = degree(values[0])
        deg2 = degree(values[1])
Tiago Peixoto's avatar
Tiago Peixoto committed
367
        if just_file:
368
            return values[2]
369
        return (graph.GetAverageNearestNeighboursCorrelation(deg1,deg2), values[2])
Tiago Peixoto's avatar
Tiago Peixoto committed
370
371
    elif opt.name == "assortativity-coefficient":
        values = parse_values(opt.value)
372
        if len(values) != 2:
Tiago Peixoto's avatar
Tiago Peixoto committed
373
            raise OptionError(opt.name, "invalid value '%s'" % opt.value)
374
        deg = degree(values[0])
Tiago Peixoto's avatar
Tiago Peixoto committed
375
        if just_file:
376
            return values[1]
377
378
379
380
381
382
383
384
385
386
387
388
389
        (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])
390
391
392
393
394
395
396
397
398
399
    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:
            hist = graph.GetEdgeHistogram(values[0])
        avg,dev,count = 0.0,0.0,0.0
Tiago Peixoto's avatar
Tiago Peixoto committed
400
401
        for k,v in hist.iteritems():
            avg += k*v
402
            dev += k*k*v
Tiago Peixoto's avatar
Tiago Peixoto committed
403
404
            count += v
        avg /= count
405
406
        dev = math.sqrt(dev/count - avg*avg)/math.sqrt(count)
        ret = "%f\t%f" % (avg, dev)
Tiago Peixoto's avatar
Tiago Peixoto committed
407
        if just_file:
408
409
            return values[1]
        return (ret,values[1])
Tiago Peixoto's avatar
Tiago Peixoto committed
410
411
412
    elif opt.name == "global-clustering-coefficient":
        if just_file:
            return opt.value
413
414
415
        (avg, dev) = graph.GetGlobalClustering()
        ret = "%f\t%f" % (avg, dev)
        return (ret, opt.value)
Tiago Peixoto's avatar
Tiago Peixoto committed
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
    elif opt.name == "set-local-clustering-to-property":
        if just_file:
            return None
        graph.SetLocalClusteringToProperty(opt.value)
    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()
        filter_vars["variables"] = filter_vars
        def populate_vars(dict, variables):
            for k,v in dict.iteritems():
                variables[k] = v
        filter_vars["populate_vars"] = populate_vars
        try:
462
            exec "def filter_function(props):\n    populate_vars(props,variables); return not %s\n" % opt.value in filter_vars
Tiago Peixoto's avatar
Tiago Peixoto committed
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
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
540
541
542
543
544
545
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
        except:
            raise OptionError(opt.name, "invalid value '%s': %s" % (opt.value,sys.exc_info()[0]))
        if opt.name == "vertex-filter":
            graph.SetGenericVertexFilter(filter_vars["filter_function"])
        else:
            graph.SetGenericEdgeFilter(filter_vars["filter_function"])
    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())
    elif opt.name == "remove-parallel-edges":
        if just_file:
            return None
        graph.RemoveParallelEdges()
    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)))
    file.flush()

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:
    def __init__(self, file_name):
        self.file_name = os.path.expanduser(file_name)
        self.prefixes = set()
        self.file = None
581
        self.time = clock()
Tiago Peixoto's avatar
Tiago Peixoto committed
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
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
        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"
        match = re.compile("([0-9]+)([d,h,m,s])").match(options.history_rate)
        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:
            raise HistoryException(what="invalid history refresh rate value: %s" % options.history_rate)
        if os.path.exists(self.file_name) and self.file_name != "-":            
            # 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)
            #upadate prefixes
            for line in open_file(self.file_name, "r"):
                prefix = line.split()[0]
                self.prefixes.add(prefix)
            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)
643
        if clock() - self.time > self.rate:
Tiago Peixoto's avatar
Tiago Peixoto committed
644
645
            self.file.close()
            self.refresh()
646
            self.time = clock()
Tiago Peixoto's avatar
Tiago Peixoto committed
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677

# signal handling
graph.InitSignalHandling()

# parse each option in order
try:
    history_range = None
    for opt in option_list:
        if opt.name == "history":
            # the rest of the commands are to be treated as history template
            history_range = opt
            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:
            raise OptionError("history", "invalid value '%s'" % options.history_range)
        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
678
        exec "___continue = %s" % values[1] in variables # condition
Tiago Peixoto's avatar
Tiago Peixoto committed
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
        count = 0
        while variables["___continue"]:
            for opt in histories:
                new_opt = Opt(opt.name,opt.value)
                if new_opt.value != None:
                    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"])
                    if not history_files.has_key(file_name):
                        history_files[file_name] = HistoryFile(file_name)
                    if prefix not in history_files[file_name].prefixes:
                        data = parse_option(new_opt)[0]
                        history_files[file_name].write(data, prefix)
                else:
                    parse_option(new_opt)

702
703
            exec values[2] in variables # step
            exec "___continue = %s" % values[1] in variables # condition
Tiago Peixoto's avatar
Tiago Peixoto committed
704
            count += 1
705
        del history_files
Tiago Peixoto's avatar
Tiago Peixoto committed
706
707
708
709
710
            
except (OptionError, HistoryException), e:
    print "graph-tool:", e
except KeyboardInterrupt:
    pass