source: misc/tools/pytools/numtools.py @ 6324

Last change on this file since 6324 was 18, checked in by ole, 20 years ago

Added old pytools module from CVS

File size: 2.5 KB
Line 
1"""Functions for numerical computations
2"""
3
4epsilon = 1.0e-15
5
6
7
8
9
10def sum(x):
11  """
12    Attempt to sum up elements in x
13  """
14
15  import types, Numeric
16 
17  if type(x) == Numeric.ArrayType:
18    return Numeric.sum(x)
19  elif type(x) in [types.ListType, types.TupleType]:
20    s = x[0]
21    for e in x[1:]:
22      s += e
23    return s 
24
25def mvmul(A, x):
26  """Multiply matrix A onto vector x
27  """
28
29  from Numeric import dot, reshape
30
31  x = reshape(x, (A.shape[1], 1)) #Make x a column vector             
32
33  return dot(A, x)
34
35
36def all_equal(vec):
37
38  equal = 1
39  v0 = vec[0]
40  for v in vec:
41    if v != v0:
42      equal = 0   
43
44  return equal
45
46
47def meshgrid(N):
48  """Make meshgrid (a' la Matlab) 
49  """
50 
51  from Numeric import ones, arange, Float, multiply
52
53  d = len(N)
54
55  X = [] 
56  for s in range(d):
57    local_shape = ones(d)
58    local_shape[s] = N[s]
59    a = arange(N[s])
60    if N[s] > 1:
61      a = a.astype(Float)/(N[s]-1)
62    else:
63      a = a.astype(Float)
64   
65    # Put ones in all other dimensions
66    #
67    e = [] 
68    for t in range(d):
69      if s == t: 
70        e.append(a)
71      else:
72        e.append(ones(N[t]))
73   
74    # Take kronecker product of all dimensions
75    #
76    x = 1 
77    for t in range(d):
78      x=multiply.outer(x,e[t])
79
80    #print x, x.shape
81    X.append(x)
82   
83  return X   
84   
85
86def expand(x, mask):
87  """Expand vector x into into vector of length equal to vector
88     mask such that elements of x are placed where mask is one.
89     Number of ones in mask must equal len(x)."""
90
91  from Numeric import sum, ArrayType, zeros
92
93  assert type(x) == ArrayType
94  assert type(mask) == ArrayType
95  #FIXME: Assert that mask contains only ones and zeros
96  assert len(x) == sum(mask), 'Number of ones in mask must equal length of x'
97
98  d = len(mask)
99  y = zeros(d, x.typecode())
100
101  i = 0
102  for s in range(d):
103    if mask[s]:
104      y[s] = x[i] 
105      i += 1
106
107  return y   
108
109
110def pwr2trunc(N, e = None, dir = 0): 
111    """N1 = pwr2trunc(N, e, dir)
112
113    If e is None, let e be the largest integer such that N > 2**e.
114   
115    If dir = 0 (default)
116      Compute the nearest number smaller than N divisible by 2^e
117    if dir == 1
118      Compute the nearest number greater than N divisible by 2^e
119
120     
121    """ 
122
123    import math
124
125    if e is None:
126        e = int(math.log(N)/math.log(2))  # Maximal exponent
127
128    k = N % 2**e
129    N1 = N - k
130    if dir == 1:
131        N1  = 2*N1
132
133    return N1, e
Note: See TracBrowser for help on using the repository browser.