nwt.py 2.32 KB
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 19 12:38:30 2018

@author: david
"""

import numpy

class Vertex:
    def __init__(self, f):                                                      #load a vertex given a file ID at that vertex location
        self.p = numpy.fromfile(f, dtype=numpy.float32, count=3)                                     #load the vertex coordinates
        
        EO = int.from_bytes(f.read(4), "little")                                #get the number of edges moving out of and into this vertex
        EI = int.from_bytes(f.read(4), "little")
        
        self.Eout = numpy.fromfile(f, dtype=numpy.uint32, count=EO)             #get the incoming and outgoing edge lists
        self.Ein = numpy.fromfile(f, dtype=numpy.uint32, count=EI)
        
    def __str__(self):
        sp = "(" + str(self.p[0]) + ", " + str(self.p[1]) + ", " + str(self.p[2]) + ")"
        
        seo = "["
        for e in self.Eout:
            seo = seo + " " + str(e)
        seo = seo + " ]"
            
        sei = "["
        for e in self.Ein:
            sei = sei + " " + str(e)
        sei = sei + " ]"
        
        return sp + "  out = " + seo + "  in = " + sei
        
class Edge:
    def __init__(self, f):
        self.v = numpy.fromfile(f, dtype=numpy.uint32, count=2)
        P = int.from_bytes(f.read(4), "little")
        p1d = numpy.fromfile(f, dtype=numpy.float32, count=4*P)
        self.p = numpy.reshape(p1d, (P, 4))
        
    def __str__(self):
        sv = "[ " + str(self.v[0]) + "---> " + str(self.v[1]) + " ]"
        return sv + str(self.p)

class NWT:
    def __init__(self, fname):
        f = open(fname, "rb")                                                        #open the NWT file for binary reading
        self.filetype = f.read(14)                                                           #this should be "nwtfileformat "
        self.desc = f.read(58)                                                               #NWT file description
        V = int.from_bytes(f.read(4), "little")                                         #retrieve the number of vertices (graph)
        E = int.from_bytes(f.read(4), "little")
              
        self.v = []
        for i in range(0, V):
            self.v.append(Vertex(f))
            
        self.e = []
        for i in range(1, E):
            self.e.append(Edge(f))