bindings/python/dionysus/distances.py
author Dmitriy Morozov <dmitriy@mrzv.org>
Fri May 11 17:06:55 2012 -0700 (2 weeks ago)
branchdev
changeset 251 870865d25958
parent 1322a737609b8bf
permissions -rw-r--r--
Merge
     1 from    math        import sqrt
     2 
     3 def l2(p):
     4     return sqrt(sum((x**2 for x in p)))
     5 
     6 # Pairwise distances between the elements of `points` with respect to some `norm`
     7 class PairwiseDistances:
     8     def __init__(self, points, norm = l2):
     9         self.points = points
    10         self.norm = norm
    11 
    12     def __len__(self):
    13         return len(self.points)
    14 
    15     def __call__(self, p1, p2):
    16         return self.norm((x - y for (x,y) in zip(self.points[p1], self.points[p2])))
    17 
    18 # Caches all distances specified by `distances`
    19 class ExplicitDistances:
    20     def __init__(self, distances):
    21         self.len = len(distances)
    22         self.distances = []
    23         for i in xrange(self.len): 
    24             self.distances.append([])
    25             for j in xrange(self.len):
    26                 self.distances[-1].append(distances(i,j))
    27 
    28     def __len__(self):
    29         return self.len
    30 
    31     def __call__(self, p1, p2):
    32         return self.distances[p1][p2]
    33 
    34 # Generator of all points in a file `filename` with one point per line
    35 def points_file(filename):
    36     fd = open(filename)
    37     for line in fd.xreadlines():
    38         if line.startswith('#'): continue
    39         yield map(float, line.strip().split())
    40     fd.close()