konect.py 4.01 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1
2
3
4
5
 #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
Tiago Peixoto's avatar
Tiago Peixoto committed
6
# Copyright (C) 2006-2020 Tiago de Paula Peixoto <tiago@skewed.de>
Tiago Peixoto's avatar
Tiago Peixoto committed
7
#
8
9
10
11
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.
Tiago Peixoto's avatar
Tiago Peixoto committed
12
#
13
14
15
16
# 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 Lesser General Public License for more
# details.
Tiago Peixoto's avatar
Tiago Peixoto committed
17
#
18
19
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
Tiago Peixoto's avatar
Tiago Peixoto committed
20
21
22

import os.path
import tempfile
23
24
from urllib.request import urlopen, URLError
from tempfile import TemporaryDirectory
Tiago Peixoto's avatar
Tiago Peixoto committed
25
26
27
28
29
30
31
32
33
34
35
import tarfile
import warnings
import numpy

from .. import Graph

def load_koblenz_dir(dirname):
    g = Graph()
    g.gp.meta = g.new_graph_property("string")
    g.gp.readme = g.new_graph_property("string")
    for root, dirs, files in os.walk(dirname):
36
37
38
39
40
41
42
43
        for f in files:
            if f.startswith("README"):
                g.gp.readme = open(os.path.join(root, f)).read()
            if f.startswith("meta."):
                g.gp.meta = open(os.path.join(root, f)).read()
            if f.startswith("out."):
                edges = numpy.loadtxt(os.path.join(root, f), comments="%")
                line = next(open(os.path.join(root, f)))
Tiago Peixoto's avatar
Tiago Peixoto committed
44
45
46
                if "asym" not in line:
                    g.set_directed(False)
                edges[:,:2] -= 1  # we need zero-based indexing
47
48
                if "bip" in line: # bipartite graphs have non-unique indexing
                    edges[:,1] += edges[:,0].max() + 1
Tiago Peixoto's avatar
Tiago Peixoto committed
49
50
                g.add_edge_list(edges[:,:2])
                if edges.shape[1] > 2:
51
                    g.ep.weight = g.new_edge_property("double")
Tiago Peixoto's avatar
Tiago Peixoto committed
52
53
54
55
                    g.ep.weight.a = edges[:,2]
                if edges.shape[1] > 3:
                    g.ep.time = g.new_edge_property("int")
                    g.ep.time.a = edges[:,3]
56
57
        for f in files:
            if f.startswith("ent."):
Tiago Peixoto's avatar
Tiago Peixoto committed
58
59
60
61
                try:
                    g.vp.meta = g.new_vertex_property("string")
                    meta = g.vp.meta
                    count = 0
62
                    for line in open(os.path.join(root, f)):
Tiago Peixoto's avatar
Tiago Peixoto committed
63
64
65
66
67
68
69
70
71
72
                        vals = line.split()
                        if len(vals) == 1 and vals[0] == "%":
                            continue
                        if vals[0] == "%":
                            g.gp.meta_desc = g.new_graph_property("string", line)
                            continue
                        v = g.vertex(count)
                        meta[v] = line.strip()
                        count += 1
                except ValueError as e:
73
                    warnings.warn("error automatically reading node metadata from file '%s': %s" % (f, str(e)))
Tiago Peixoto's avatar
Tiago Peixoto committed
74
75
76
77
    return g

def get_koblenz_network_data(name):
    with tempfile.TemporaryFile(mode='w+b') as ftemp:
78
79
80
81
        try:
            response = urlopen('http://konect.cc/files/download.tsv.%s.tar.bz2' % name)
        except URLError:
            response = urlopen('http://konect.uni-koblenz.de/downloads/tsv/%s.tar.bz2' % name)
82
83
84
85
86
87
        buflen = 1 << 20
        while True:
            buf = response.read(buflen)
            ftemp.write(buf)
            if len(buf) < buflen:
                break
Tiago Peixoto's avatar
Tiago Peixoto committed
88
        ftemp.seek(0)
89
        with TemporaryDirectory(suffix=name) as tempdir:
Tiago Peixoto's avatar
Tiago Peixoto committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
            with tarfile.open(fileobj=ftemp, mode='r:bz2') as tar:
                tar.extractall(path=tempdir)
            g = load_koblenz_dir(tempdir)
            return g

class LazyKoblenzDataDict(dict):
    def __getitem__(self, k):
        if k not in self:
            g = get_koblenz_network_data(k)
            dict.__setitem__(self, k, g)
            return g
        return dict.__getitem__(self, k)


konect_data = LazyKoblenzDataDict()