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.

import urllib2

filepath = 'http://block.arch.ethz.ch/labs/samples/saddle.obj'
response = urllib2.urlopen(filepath)
data     = iter(response.readlines())

xyz      = [] # xyz coordinates
vertices = [] # unique xyz coordinates
points   = [] # references to vertices
lines    = [] # pairs of references to vertices
 
deg = None
for line in data:
    parts = line.split()
    if not parts: 
        continue
    head = parts[0]
    tail = parts[1:]
    if 'deg' == head:
        deg = int(tail[0])
    elif 'end' == head:
        deg = None 
    elif 'v' == head: 
        xyz.append(map(float, tail))
        deg = None
    elif 'p' == head:
        points.append(int(tail[0]) - 1)
        deg = None
    elif 'curv' == head:
        if deg != 1: 
            continue
        if len(tail[2:]) != 2: 
            continue
        lines.append((int(tail[2]) - 1, int(tail[3]) - 1))
        deg = None

x2v = {}
tol = 0.001**2
for i, x in enumerate(iter(xyz)):
    found = False
    for j, v in enumerate(iter(vertices)):
        if (x[0] - v[0])**2 < tol \
           and (x[1] - v[1])**2 < tol \
           and (x[2] - v[2])**2 < tol:
            found = True
            x2v[i] = j
            break
    if not found:
        x2v[i] = len(vertices)
        vertices.append(x)

edges     = [(x2v[u], x2v[v]) for u, v in lines]
points[:] = [x2v[index] for index in points]

3 Responses to “Reading network data from a file”

Leave a Reply to Bepo Schira

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>