Reading network data from a file

share on google plus share on facebook share on twitter share on linkedin share via email

The data describing large networks can obviously not be written out manually, as in a previous post. Here we will take a look at getting network data from an obj file.

01.import urllib2
02. 
04.response = urllib2.urlopen(filepath)
05.data     = iter(response.readlines())
06. 
07.xyz      = [] # xyz coordinates
08.vertices = [] # unique xyz coordinates
09.points   = [] # references to vertices
10.lines    = [] # pairs of references to vertices
11.  
12.deg = None
13.for line in data:
14.    parts = line.split()
15.    if not parts:
16.        continue
17.    head = parts[0]
18.    tail = parts[1:]
19.    if 'deg' == head:
20.        deg = int(tail[0])
21.    elif 'end' == head:
22.        deg = None
23.    elif 'v' == head:
24.        xyz.append(map(float, tail))
25.        deg = None
26.    elif 'p' == head:
27.        points.append(int(tail[0]) - 1)
28.        deg = None
29.    elif 'curv' == head:
30.        if deg != 1:
31.            continue
32.        if len(tail[2:]) != 2:
33.            continue
34.        lines.append((int(tail[2]) - 1, int(tail[3]) - 1))
35.        deg = None
36. 
37.x2v = {}
38.tol = 0.001**2
39.for i, x in enumerate(iter(xyz)):
40.    found = False
41.    for j, v in enumerate(iter(vertices)):
42.        if (x[0] - v[0])**2 < tol \
43.           and (x[1] - v[1])**2 < tol \
44.           and (x[2] - v[2])**2 < tol:
45.            found = True
46.            x2v[i] = j
47.            break
48.    if not found:
49.        x2v[i] = len(vertices)
50.        vertices.append(x)
51. 
52.edges     = [(x2v[u], x2v[v]) for u, v in lines]
53.points[:] = [x2v[index] for index in points]

3 Responses to “Reading network data from a file”

Leave a response

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>