analyze.py 10.1 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 Tiago de Paula Peixoto <tiago@skewed.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 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os.path
import pickle
from collections import defaultdict
from functools import wraps
from graph_tool.all import *
import process_entry
from locks import acquire_lock, acquire_lock_file

from util import *
import contextlib
import shelve
import dbm

import numpy
import scipy.sparse.linalg

@contextlib.contextmanager
def open_cache(entry, flag="rf"):
    "Open a persistent cache for a given entry."

    base = f"cache/analysis/{entry.name}"
    os.makedirs(base, exist_ok=True)

    try:
        with shelve.open(f"{base}/cache_db", flag=flag) as cache:
            yield cache
    except dbm.error:
        if flag[0] == "r":
            yield {}
        else:
            raise

def cache_result(f):
    "Decorator that caches the result of the given function."

    name = f.__name__.split(".")[-1]
    @wraps(f)
    def wrap(entry, alt, g, cache, *args, cache_only=False, force=False,
             **kwargs):
        try:
            if force:
                raise KeyError()
            if alt is not None:
                try:
                    ret = cache[repr((alt, name))]
                except KeyError:
                    ret = cache[alt][name]
            else:
                ret = cache[name]
            return ret
        except KeyError:
            if cache_only:
                return None
            if g is None:
                return None
            print(f"\t\t{alt} {name}...")
            ret = f(g(), *args, **kwargs)
            if alt is not None:
                cache[repr((alt, name))] = ret
            else:
                cache[name] = ret
            return ret
    return wrap

def restrict(N, exclude=[]):
    """Decorator that restricts the function call to networks with N nodes or less,
    and that do not belong to the exclude list, and returns None otherwise.
    """

    def rec(f):
        @wraps(f)
        def wrap(entry, alt, g, cache, *args, **kwargs):
            N_e = get_N(entry, alt, g, cache, *args, **kwargs)
            if N_e > N or entry.name in exclude:
                return None
            return f(entry, alt, g, cache, *args, **kwargs)
        return wrap
    return rec

def uses(names):

    def rec(f):
        @wraps(f)
        def wrap(entry, alt, g, cache, *args, **kwargs):
            global analyses
            x = [analyses[name](entry, alt, g, cache, *args, **kwargs) for name in names]
            return f(entry, alt, g, cache, *x, *args, **kwargs)
        return wrap
    return rec

analyses = {}
titles = {}
111
scales = {}
Tiago Peixoto's avatar
Tiago Peixoto committed
112

113
def register(name=None, title=None, scale="linear"):
Tiago Peixoto's avatar
Tiago Peixoto committed
114
115
116
117
118
119
120
    """Decorator that registers the function to the global analyses list, with a
    given name and title."""

    global analyses
    global titles

    titles[name] = title
121
    scales[name] = scale
Tiago Peixoto's avatar
Tiago Peixoto committed
122
123
124
125
126
127
128
129
130
131

    def reg(f):
        nonlocal name
        if name is None:
            name = f.__name__.split(".")[-1]
        analyses[name] = f
        return f

    return reg

132
@register("num_edges", "Number of edges", "log")
Tiago Peixoto's avatar
Tiago Peixoto committed
133
134
135
136
@cache_result
def get_E(g):
    return g.num_edges()

137
@register("num_vertices", "Number of vertices", "log")
Tiago Peixoto's avatar
Tiago Peixoto committed
138
139
140
141
@cache_result
def get_N(g):
    return g.num_vertices()

142
@register("is_directed", title="Directed")
Tiago Peixoto's avatar
Tiago Peixoto committed
143
144
145
146
@cache_result
def is_directed(g):
    return g.is_directed()

147
@register("average_degree", "Average degree", "log")
Tiago Peixoto's avatar
Tiago Peixoto committed
148
149
150
151
152
153
154
@cache_result
def get_ak(g):
    if g.is_directed():
        return g.num_edges() / g.num_vertices()
    else:
        return 2 * g.num_edges() / g.num_vertices()

155
@register("degree_std_dev", "Degree standard deviation", "symlog")
Tiago Peixoto's avatar
Tiago Peixoto committed
156
157
158
159
160
161
162
163
164
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
@cache_result
def get_kdev(g):
    g = GraphView(g, directed=False)
    k = g.get_out_degrees(g.get_vertices())
    return k.std()

@register("is_bipartite", "Bipartite")
@cache_result
def is_bip(g):
    return is_bipartite(g)

@register("global_clustering", "Global clustering")
@cache_result
def get_clustering(g):
    if is_bipartite(g):
        return 0.
    return global_clustering(g)[0]

@register("degree_assortativity", "Degree assortativity")
@cache_result
def get_assortativity(g):
    g = GraphView(g, directed=False)
    return scalar_assortativity(g, "out")[0]

@register("largest_component_fraction", "Size of largest component")
@cache_result
def get_S(g):
    c = label_largest_component(g, directed=False)
    return c.fa.sum() / g.num_vertices()

@register("edge_reciprocity", "Edge reciprocity")
@cache_result
def get_reciprocity(g):
    if g.is_directed():
        return edge_reciprocity(g)
    return 1.

@register("transition_gap", "Second eigenvalue of transition matrix")
@cache_result
def get_tgap(g):
    g = GraphView(g, directed=False)
    u = extract_largest_component(g)
    if u.num_vertices() != g.num_vertices():
        g = u
    if 2 >= g.num_vertices() - 1:
        return numpy.nan
    T = transition(g, operator=True)
203
204
205
206
207
208
209
210
211
212
213
    k = numpy.array(g.degree_property_map("out").fa, dtype="float")
    k /= numpy.linalg.norm(k)
    def matvec(x):
        return T.matvec(x) - numpy.dot(k, x) * k
    Tp = scipy.sparse.linalg.LinearOperator(T.shape, matvec=matvec)
    try:
        ew = scipy.sparse.linalg.eigs(Tp, k=1, which="LR",
                                      return_eigenvectors=False,
                                      tol=1e-6)
    except scipy.sparse.linalg.eigen.arpack.ArpackNoConvergence:
        return numpy.nan
Tiago Peixoto's avatar
Tiago Peixoto committed
214
215
    return float(min(ew.real))

216
@register("mixing_time", "Random walk mixing time", "log")
Tiago Peixoto's avatar
Tiago Peixoto committed
217
218
219
220
221
222
223
@uses(["transition_gap"])
@cache_result
def get_mixing(g, tgap):
    if tgap <= 0:
        return numpy.inf
    return -1/numpy.log(tgap)

224
@register("hashimoto_radius", "Largest eigenvalue of non-backtracking matrix", "log")
Tiago Peixoto's avatar
Tiago Peixoto committed
225
226
227
@cache_result
def get_hgap(g):
    g = GraphView(g, directed=False)
228
229
230
231
232
233
    l = label_parallel_edges(g, mark_only=True)
    if l.fa.max() > 0:
        l.a = numpy.logical_not(l.a)
        g = GraphView(g, efilt=l)
    else:
        del l
Tiago Peixoto's avatar
Tiago Peixoto committed
234
    T = hashimoto(g, compact=True, operator=True)
235
236
    try:
        ew = scipy.sparse.linalg.eigs(T, k=1, which="LR", return_eigenvectors=False)
237
    except (TypeError, scipy.sparse.linalg.eigen.arpack.ArpackNoConvergence):
238
        return numpy.nan
Tiago Peixoto's avatar
Tiago Peixoto committed
239
240
    return float(ew.real[0])

241
@register("diameter", "(Pseudo-) diameter", "log")
Tiago Peixoto's avatar
Tiago Peixoto committed
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
@cache_result
def get_diameter(g):
    g = GraphView(g, directed=False)
    u = extract_largest_component(g)
    if u.num_vertices() != g.num_vertices():
        g = u
    if g.num_vertices() > 10000:
        d = pseudo_diameter(g)[0]
    else:
        d = max([shortest_distance(g, source=v).a.max() for v in g.vertices()])
    return int(d)

@register("edge_properties")
@cache_result
def get_eprops(g):
    eprops = []
    for k, v in g.ep.items():
        eprops.append((k, v.value_type()))
    return eprops

@register("vertex_properties")
@cache_result
def get_vprops(g):
    vprops = []
    for k, v in g.vp.items():
        vprops.append((k, v.value_type()))
    return vprops

@register("pos")
271
@restrict(N=1000000, exclude=["openstreetmap"])
Tiago Peixoto's avatar
Tiago Peixoto committed
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
@cache_result
def get_pos(g):
    if g.num_vertices() < 1000:
        step = .99
    else:
        step = .95
    pos = sfdp_layout(g, multilevel=True, cooling_step=step)
    x, y = ungroup_vector_property(pos, [0, 1])
    return [x.a, y.a]

def analyze_entries(entries, names=[], skip=[], force=[], cache_only=True,
                    global_cache=False):
    global analyses

    analyze_cache = {}
    if global_cache:
        with acquire_lock_file("./cache/analyze_cache.lock", block=True) as lock:
            try:
290
291
                with open("./cache/analyze_cache.pickle", "rb") as f:
                    analyze_cache = pickle.load(f)
Tiago Peixoto's avatar
Tiago Peixoto committed
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
            except FileNotFoundError:
                pass

    for entry in entries:

        if hasattr(entry, "analyzes"):
            continue

        if entry.name in analyze_cache:
            entry.analyses, entry._analyses = analyze_cache[entry.name]
            continue

        flag = "rf" if cache_only else "c"

        with open_cache(entry, flag) as cache:
            entry.analyses = defaultdict(dict)
            max_alt = None
            Nmax = None
            for alt, g in entry.parse(lazy=True, cache_only=True):
                for a, f in analyses.items():
                    if a in skip:
                        continue
                    if len(names) > 0 and a not in names:
                        continue
                    v = f(entry, alt, g, cache, force=a in force,
                          cache_only=cache_only)
                    if isinstance(v, PropertyArray):
                        v = float(v)
                    entry.analyses[alt][a] = v

                N = entry.analyses[alt]["num_vertices"]

                if Nmax is None:
                    max_alt = alt
                    Nmax = N
                elif N > Nmax:
                    max_alt = alt
                    Nmax = N
                del g

            entry._analyses = entry.analyses[max_alt]

        if global_cache:
            analyze_cache[entry.name] = (entry.analyses, entry._analyses)

    if global_cache:
        with acquire_lock_file("./cache/analyze_cache.lock", block=True) as lock:
339
340
            with open("./cache/analyze_cache.pickle", "wb") as f:
                pickle.dump(analyze_cache, f)
Tiago Peixoto's avatar
Tiago Peixoto committed
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357

if __name__ == "__main__":
    if len(sys.argv) > 1:
        names = sys.argv[1:]
    else:
        names = None

    entries = process_entry.get_entries(names)

    for entry in entries.values():

        with acquire_lock(entry, block=False) as lock:
            if lock is None:
                continue

            print("analyzing:", entry.name)
            analyze_entries([entry], cache_only=False)