Package pyxsd :: Package transforms :: Module vector
[hide private]
[frames] | no frames]

Source Code for Module pyxsd.transforms.vector

 1  import math 
2 -class Vector (tuple):
3 4 """ 5 6 ==================================== 7 Transform Library: CellSizer: Vector 8 ==================================== 9 10 :Author: Karl Norby <knorby@uchicago.edu> 11 :Date: Fri, 1 Sept 2006 12 :Category: Computational Materials Science 13 :Description: A class for vectors with some vector functions 14 :Copyright: pyXSD License 15 16 Included as part of the CellSizer Library 17 18 """ 19 20 #======================================================= 21 #
22 - def __init__(self, val):
23 24 tuple.__init__(val)
25 26 #======================================================= 27 #
28 - def __mul__(self, scalar):
29 if not isinstance(scalar, int) and not isinstance(scalar, float): 30 raise TypeError, "a scalar must be a int or float" 31 multiply = lambda x: x*scalar 32 return Vector(map(multiply, self))
33 34 #======================================================= 35 #
36 - def __add__(self, vector):
37 if not isinstance(vector, Vector): 38 raise TypeError, "a vector can only be added to another vector" 39 if not len(vector)==len(self): 40 raise TypeError, "vectors must have the same number of dimensions to be added" 41 listOfNewValues = [] 42 for a, b in zip(self, vector): 43 listOfNewValues.append(a+b) 44 return Vector(listOfNewValues)
45 46 #======================================================= 47 #
48 - def __sub__(self, vector):
49 if not isinstance(vector, Vector): 50 raise TypeError, "vector subtraction must be between two vectors" 51 if not len(vector)==len(self): 52 raise TypeError, "vectors must have the same number of dimensions to find the difference of two vectors" 53 listOfNewValues = [] 54 for a, b in zip(self, vector): 55 listOfNewValues.append(a-b) 56 return Vector(listOfNewValues)
57 58 #======================================================= 59 #
60 - def findDotProduct(self, vector):
61 product = 0 62 if not isinstance(vector, Vector): 63 raise TypeError, "the dot product is between two vectors" 64 if not len(vector)==len(self): 65 raise TypeError, "the dot product is between two vectors in the same vector space" 66 for a, b in zip(self, vector): 67 product+=(a*b) 68 return product
69 70 #======================================================= 71 #
72 - def distance(self, vector):
73 if not isinstance(vector, Vector): 74 raise TypeError, "the distance formula for vectors is between two vectors" 75 if not len(vector)==len(self): 76 raise TypeError, "the distance formula for vectors is between two vectors in the same vector space" 77 subtractedVector = self - vector 78 return subtractedVector.findLength()
79 80 #======================================================= 81 #
82 - def findLength(self):
83 return math.sqrt(self.findDotProduct(self))
84