Welcome, guest | Sign In | My Account | Store | Cart

This vector class stores elements in a list and hence allows the 'vector' to grow dynamically. Common mathematical functions (sin, cosh, etc) are supported elementwise and so are a number of 'external' operations (dot for the inner product between vectors, norm, sum etc.). This class does not rely on NumPy but can be used in conjunction with a 'sparse' matrix class to solve linear systems. Tested using Python 2.0 and Jython 2.0.

Python, 390 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/usr/bin/env python
# 
# a python vector class
# A. Pletzer 5 Jan 00/11 April 2002
#
import math

"""
A list based vector class that supports elementwise mathematical operations

In this version, the vector call inherits from list; this 
requires Python 2.2 or later.
"""

class vector(list):
	"""
        A list based vector class
	"""
	# no c'tor

	def __getslice__(self, i, j):
		try:
			# use the list __getslice__ method and convert
			# result to vector
			return vector(super(vector, self).__getslice__(i,j))
		except:
			raise TypeError, 'vector::FAILURE in __getslice__'
		
	def __add__(self, other):
		return vector(map(lambda x,y: x+y, self, other))

	def __neg__(self):
		return vector(map(lambda x: -x, self))
	
	def __sub__(self, other):
		return vector(map(lambda x,y: x-y, self, other))

	def __mul__(self, other):
	    """
	    Element by element multiplication
	    """
	    try:
		    return vector(map(lambda x,y: x*y, self,other))
	    except:
		    # other is a const
		    return vector(map(lambda x: x*other, self))


	def __rmul__(self, other):
		return (self*other)


	def __div__(self, other):
	    """
	    Element by element division.
	    """
	    try:
		    return vector(map(lambda x,y: x/y, self, other))
	    except:
		    return vector(map(lambda x: x/other, self))

	def __rdiv__(self, other):
	    """
	    The same as __div__
	    """
	    try:
		    return vector(map(lambda x,y: x/y, other, self))
	    except:
		    # other is a const
		    return vector(map(lambda x: other/x, self))

        def size(self): return len(self)

	def conjugate(self):
	    return vector(map(lambda x: x.conjugate(), self))

        def ReIm(self):
		"""
		Return the real and imaginary parts
		"""
		return [
			vector(map(lambda x: x.real, self)),
			vector(map(lambda x: x.imag, self)),
			]
	
        def AbsArg(self):
		"""
		Return modulus and phase parts
		"""
		return [
			vector(map(lambda x: abs(x), self)),
			vector(map(lambda x: math.atan2(x.imag,x.real), self)),
			]


	def out(self):
	    """
	    Prints out the vector.
	    """
	    print self

###############################################################################


def isVector(x):
    """
    Determines if the argument is a vector class object.
    """
    return hasattr(x,'__class__') and x.__class__ is vector

def zeros(n):
    """
    Returns a zero vector of length n.
    """
    return vector(map(lambda x: 0., range(n)))

def ones(n):
    """
    Returns a vector of length n with all ones.
    """
    return vector(map(lambda x: 1., range(n)))

def random(n, lmin=0.0, lmax=1.0):
    """
    Returns a random vector of length n.
    """
    import whrandom
    new = vector([])
    gen = whrandom.whrandom()
    dl = lmax-lmin
    return vector(map(lambda x: dl*gen.random(),
		       range(n)))
	
def dot(a, b):
    """
    dot product of two vectors.
    """
    try:
	return reduce(lambda x, y: x+y, a*b, 0.)
    except:
	raise TypeError, 'vector::FAILURE in dot'
	

def norm(a):
    """
    Computes the norm of vector a.
    """
    try:
	return math.sqrt(abs(dot(a,a)))
    except:
	raise TypeError, 'vector::FAILURE in norm'

def sum(a):
    """
    Returns the sum of the elements of a.
    """
    try:
	return reduce(lambda x, y: x+y, a, 0)
    except:
	raise TypeError, 'vector::FAILURE in sum'

# elementwise operations
	
def log10(a):
    """
    log10 of each element of a.
    """
    try:
	return vector(map(math.log10, a))
    except:
	raise TypeError, 'vector::FAILURE in log10'

def log(a):
    """
    log of each element of a.
    """
    try:
	return vector(map(math.log, a))
    except:
	raise TypeError, 'vector::FAILURE in log'
	    
def exp(a):
    """
    Elementwise exponential.
    """
    try:
	return vector(map(math.exp, a))
    except:
	raise TypeError, 'vector::FAILURE in exp'

def sin(a):
    """
    Elementwise sine.
    """
    try:
	return vector(map(math.sin, a))
    except:
	raise TypeError, 'vector::FAILURE in sin'
	    
def tan(a):
    """
    Elementwise tangent.
    """
    try:
	return vector(map(math.tan, a))
    except:
	raise TypeError, 'vector::FAILURE in tan'
	    
def cos(a):
    """
    Elementwise cosine.
    """
    try:
	return vector(map(math.cos, a))
    except:
	raise TypeError, 'vector::FAILURE in cos'

def asin(a):
    """
    Elementwise inverse sine.
    """
    try:
	return vector(map(math.asin, a))
    except:
	raise TypeError, 'vector::FAILURE in asin'

def atan(a):
    """
    Elementwise inverse tangent.
    """	
    try:
	return vector(map(math.atan, a))
    except:
	raise TypeError, 'vector::FAILURE in atan'

def acos(a):
    """
    Elementwise inverse cosine.
    """
    try:
	return vector(map(math.acos, a))
    except:
	raise TypeError, 'vector::FAILURE in acos'

def sqrt(a):
    """
    Elementwise sqrt.
    """
    try:
	return vector(map(math.sqrt, a))
    except:
	raise TypeError, 'vector::FAILURE in sqrt'

def sinh(a):
    """
    Elementwise hyperbolic sine.
    """
    try:
	return vector(map(math.sinh, a))
    except:
	raise TypeError, 'vector::FAILURE in sinh'

def tanh(a):
    """
    Elementwise hyperbolic tangent.
    """
    try:
	return vector(map(math.tanh, a))
    except:
	raise TypeError, 'vector::FAILURE in tanh'

def cosh(a):
    """
    Elementwise hyperbolic cosine.
    """
    try:
	return vector(map(math.cosh, a))
    except:
	raise TypeError, 'vector::FAILURE in cosh'


def pow(a,b):
    """
    Takes the elements of a and raises them to the b-th power
    """
    try:
        return vector(map(lambda x: x**b, a))
    except:
        try:
		return vector(map(lambda x,y: x**y, a, b))
	except:
		raise TypeError, 'vector::FAILURE in pow'
	
def atan2(a,b):    
    """
    Arc tangent
    
    """
    try:
	return vector(map(math.atan2, a, b))
    except:
	raise TypeError, 'vector::FAILURE in atan2'
	

###############################################################################
if __name__ == "__main__":

	print 'a = zeros(4)'
	a = zeros(4)

	print 'a.__doc__=',a.__doc__

	print 'a[0] = 1.0'
	a[0] = 1.0

	print 'a[3] = 3.0'
	a[3] = 3.0

	print 'a[0]=', a[0]
	print 'a[1]=', a[1]

	print 'len(a)=',len(a)
	print 'a.size()=', a.size()
			
	b = vector([1, 2, 3, 4])
	print 'a=', a
	print 'b=', b

	print 'a+b'
	c = a + b
	c.out()

	print '-a'
	c = -a
	c.out()
	a.out()

	print 'a-b'
	c = a - b
	c.out()

	print 'a*1.2'
	c = a*1.2
	c.out()


	print '1.2*a'
	c = 1.2*a
	c.out()
	print 'a=', a

	print 'dot(a,b) = ', dot(a,b)
	print 'dot(b,a) = ', dot(b,a)

	print 'a*b'
	c = a*b
	c.out()
	
	print 'a/1.2'
	c = a/1.2
	c.out()

	print 'a[0:2]'
	c = a[0:2]
	c.out()

	print 'a[2:5] = [9.0, 4.0, 5.0]'
	a[2:5] = [9.0, 4.0, 5.0]
	a.out()

	print 'sqrt(a)=',sqrt(a)
	print 'pow(a, 2*ones(len(a)))=',pow(a, 2*ones(len(a)))
	print 'pow(a, 2)=',pow(a, 2*ones(len(a)))

	print 'ones(10)'
	c = ones(10)
	c.out()

	print 'zeros(10)'
	c = zeros(10)
	c.out()	

	print 'del a'
	del a

	try:
		a = random(11, 0., 2.)
		a.out()

	except: pass

I'm using this class extensively in the context of a finite element code to store data on a mesh. 'vector' is really useful in conjunction with a corresponding 'sparse' matrix class to solve linear systems arising after discretizing a partial differiental equation. Nice features of 'vector' are: (1) the vector can grow dynamically and (2) it does not rely on NumPy so that this class runs equally well (except for the random number generator whrandom) with Jython.

--Alex.

2 comments

Bill Tate 22 years, 3 months ago  # | flag

This will be a great help to me. Nice job Alex. This is something I definitely could use. Bill Tate

Maxime Biais 17 years, 3 months ago  # | flag

replace lambda by module operator. The page: PythonSpeed http://wiki.python.org/moin/PythonSpeed recommands using module operator instead of lambdas. (http://docs.python.org/lib/module-operator.html)

For example:

import operator
[...]
def __add__(self, other):
    return vector(map(operator.add, self, other))



--
Maxime Biais
http://www.biais.org