Package pype :: Module vectorops
[frames] | no frames]

Source Code for Module pype.vectorops

  1  # -*- Mode: Python; tab-width: 4; py-indent-offset: 4; -*- 
  2   
  3  """Simple vector operations 
  4   
  5  Implements a bunch of common but useful vector operations using 
  6  Numeric (if possible). If Numeric's not available, tries to fall 
  7  back to (slower) raw-python. 
  8   
  9  Author -- James A. Mazer (mazerj@gmail.com) 
 10   
 11  """ 
 12   
 13  import numpy as np 
 14   
 15  # take these direction from numpy! 
 16  mean = np.mean 
 17  std = np.std 
 18  diff = np.diff 
 19   
20 -def find(boolvec):
21 """Find indices of all TRUE elements in boolvec. 22 23 You can use like this:: 24 25 take(x, find(greater(x, 0))) 26 27 to select all elements of x greater than zero.. 28 29 """ 30 return np.compress(boolvec, np.arange(len(boolvec)))
31
32 -def sem(v, sig=None):
33 """Compute standard error of the mean of vector. 34 35 """ 36 if len(v) > 1: 37 if sig is None: 38 sig = std(v) 39 return sig/(float(len(v))**0.5) 40 else: 41 return 0.0
42
43 -def zeros(v):
44 """Count number of zero entries in vector. 45 46 """ 47 if not isinstance(v, np.ndarray): 48 v = np.array(v, np.float) 49 return len(v)-len(np.nonzero(v))
50
51 -def smooth_boxcar(v, kn=1):
52 """Smooth vector using a boxcar (square) filter (ie, running 53 average), where kn=1 is a 3pt average, kn=2 is a 5pt average etc.. 54 55 """ 56 if not isinstance(v, np.ndarray): 57 v = np.array(v, np.float) 58 n = len(v) 59 vout = np.zeros(v.shape) 60 for ix in range(0, n): 61 a = ix - kn 62 if a < 0: 63 a = 0 64 b = ix + kn 65 if b > n: 66 b = n 67 vout[ix] = mean(v[a:b]) 68 return vout
69
70 -def decimate(v, n):
71 """Simple decimatation (ie, downsampling) vector by n. No effort 72 to be smart about this -- integer decimation only! 73 74 """ 75 if not isinstance(v, np.ndarray): 76 v = np.array(v, np.float) 77 return np.take(v, range(0,len(v),n))
78
79 -def sparseness(v):
80 """Compute (Tove & Rolls) sparseness of vector. 81 82 """ 83 if not isinstance(v, np.ndarray): 84 v = np.array(v, np.float) 85 n = float(len(v)); 86 if np.sum(v) == 0: 87 return 0 88 else: 89 a = ((np.sum(v) / n) ** 2.0) / (np.sum((v**2.0) / n)) 90 return ((1.0 - a) / (1.0 - (1.0 / n)))
91
92 -def nanround(n, digits=0):
93 if n is not None: 94 n = round(n, digits) 95 return n
96 97 if __name__=='__main__' : 98 pass 99