Package Pyblio :: Module Arrays
[hide private]
[frames] | no frames]

Source Code for Module Pyblio.Arrays

  1  # This file is part of pybliographer 
  2  #  
  3  # Copyright (C) 1998-2006 Frederic GOBRY 
  4  # Email : gobry@pybliographer.org 
  5  #           
  6  # This program is free software; you can redistribute it and/or 
  7  # modify it under the terms of the GNU General Public License 
  8  # as published by the Free Software Foundation; either version 2  
  9  # of the License, or (at your option) any later version. 
 10  #    
 11  # This program is distributed in the hope that it will be useful, 
 12  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
 13  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 14  # GNU General Public License for more details.  
 15  #  
 16  # You should have received a copy of the GNU General Public License 
 17  # along with this program; if not, write to the Free Software 
 18  # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 19  #  
 20  """ 
 21  Result sets and indexes implemented on top of numpy arrays. 
 22   
 23  """ 
 24   
 25  import numpy 
 26   
 27  from numpy import array, resize, zeros, fromstring 
 28   
 29  from math import ceil, log 
 30   
 31  from Pyblio.Store import Key 
 32   
33 -def _to_power(size):
34 """ Return the power of two immediately above 'size' """ 35 try: 36 return 2 ** int(ceil(log(size, 2))) 37 except OverflowError: 38 return 1
39 40
41 -class KeyArray(object):
42 """ A growing array of Pyblio keys. """ 43
44 - def __init__(self, initial=1, a=None, s=None):
45 46 if a is not None: 47 self.a = a 48 elif s is not None: 49 self.a = fromstring(s, bool) 50 else: 51 self.a = zeros(_to_power(initial), bool) 52 return
53
54 - def tostring(self):
55 return self.a.tostring()
56
57 - def add(self, k):
58 """ Set the key 'k' in the array """ 59 k -= 1 60 61 try: 62 self.a[k] = True 63 except IndexError: 64 c = len(self.a) 65 66 largest = max(c, _to_power(k+1)) 67 self.a = resize(self.a, (largest,)) 68 self.a[c:] = False 69 70 self.a[k] = True 71 return
72
73 - def __delitem__(self, k):
74 """ Remove key 'k' from the array """ 75 self.a[k-1] = False 76 return
77
78 - def __len__(self):
79 return numpy.sum(self.a)
80
81 - def __iter__(self):
82 for key, status in enumerate(self.a): 83 if status: 84 yield Key(key + 1) 85 return
86 87
88 -def match_arrays(a,b):
89 """ Ensure a and b have the same size, enlarging the smallest of 90 the two if needed.""" 91 92 la = len(a) 93 lb = len(b) 94 95 if la == lb: 96 return a,b 97 98 if la > lb: 99 b = resize(b, la) 100 b[lb:] = False 101 102 elif lb > la: 103 a = resize(a, lb) 104 a[la:] = False 105 106 return a, b
107