Best Python code snippet using pyatom_python
Matrix.py
Source:Matrix.py
1# Matrix.py2# This class represents matrix.3#from __future__ import division4from DataType import DataType5from Number import Number6import Vector7# Somehow this avoids import problems.8from types import IntType, FloatType, ListType9from mit.cadlab.dome3.objectmodel.dataobject import DomeMatrixData10from mit.cadlab.dome3.objectmodel.dataobject import DomeVectorData1112#Known Bugs::13#Odd rounding occurs if the value type is Integer/int and14#operations involve a Real/float151617from math import fabs, sqrt1819class Matrix(DataType, DomeMatrixData):20 # Object Creation and Representation Methods21 def __init__(self,value0=0, value1=1):22 self.dataType = "Matrix"23 # Input is a DomeMatrixData24 if isinstance(value0, DomeMatrixData):25 DomeMatrixData.__init__(self, value0)26 elif (type(value0)==IntType and type(value1)==IntType):27 # row and column size specified28 DomeMatrixData.__init__(self, value0, value1)2930 #def __del__(self):3132 def __repr__(self):33 return str(self.getData())3435 def __str__(self):36 return str(self.getData())3738 def __cmp__(self,other):39 raise TypeError(str(self)+' cmp '+str(other))4041 #def __hash__(self):4243 def __nonzero__(self):44 # Return 0 if all elements are 045 for i in range(self.getRowCount()):46 for j in range(self.getColumnCount()):47 if self[i][j] != 0:48 return 149 return 05051 # Methods for Attribute Access52 #def __getattr__(self, name):53 #def __setattr__(self, name, value):54 #def __delattr__(self, name):5556 # Methods for Sequence and Mapping57 #def __len__(self):5859 def __getitem__(self, key):60 #print ' key: ' + str(key)61 if key < self.getRowCount():62 #return self.getRow(key)63 #return Vector.Vector(v[key])64 #return self.getData()[key]65 # KJT: changed return type from that above to that below66 return self.getData()[key]67 else:68 raise IndexError('Index '+str(key)+' out of range')6970 #def __setitem__(self, key, value):71 # print '...... setitem key: ' + str(key)72 # if key < self.getRowCount():73 # print '.... 2! setitem key: ' + str(key)74 # self.setItem(key, value)75 #else:76 # raise IndexError('Index '+str(key)+' out of range')7778 #def __delitem__(self, key):79 #def __getslice__(self,i,j,s):80 #def __setslice__(self,i,j,s):81 #def __delslice__(self,i,j):82 #def __contains__(self,obj):83848586 # Mathematical Operations methods87 def __add__(self,other):88 try:89 return self._add(other)90 except TypeError, e:91 try:92 return other.__radd__(self)93 except:94 raise e9596 def __sub__(self,other):97 try:98 return self._sub(other)99 except TypeError, e:100 try:101 return other.__rsub__(self)102 except:103 raise e104105 def __mul__(self,other):106 try:107 return self._mul(other)108 except TypeError, e:109 try:110 return other.__rmul__(self)111 except:112 raise e113114 def __div__(self,other):115 try:116 return self._div(other)117 except TypeError, e:118 try:119 return other.__rdiv__(self)120 except:121 raise e122123 #def __mod__(self,other):124 #def __divmod__(self,other):125 #def __pow__(self,other):126 #def __lshift__(self,other):127 #def __rshift__(self,other):128 #def __and__(self,other):129 #def __or__(self,other):130 #def __xor__(self,other):131 #def __radd__(self,other):132 #def __rsub__(self,other):133134 def __radd__(self,other):135 try:136 return self._add(other)137 except TypeError, e:138 try:139 return other.__radd__(self)140 except:141 raise e142143 def __rsub__(self,other):144 try:145 return self._sub(other)146 except TypeError, e:147 try:148 return other.__rsub__(self)149 except:150 raise e151152 def __rmul__(self,other):153 # case of scalar multiplication154 try:155 return self._mul(other)156 except TypeError, e:157 try:158 # is this a loop?159 return other.__rmul__(self)160 except:161 raise e162163164 def __rdiv__(self,other):165 raise TypeError("Cannot divide by a matrix.")166167 #def __rmod__(self,other):168 #def __rdivmod__(self,other):169 #def __rpow__(self,other):170 #def __rlshift__(self,other):171 #def __rrshift__(self,other):172 #def __rand__(self,other):173 #def __ror__(self,other):174 #def __rxor__(self,other):175 #def __iadd__(self,other):176 #def __isub__(self,other):177 #def __imul__(self,other):178 #def __idiv__(self,other):179 #def __imod__(self,other):180 #def __ipow__(self,other):181 #def __ilshift__(self,other):182 #def __irshift__(self,other):183 #def __iand__(self,other):184 #def __ior__(self,other):185 #def __ixor__(self,other):186187 def __neg__(self):188 return self*-1189190 #def __pos__(self):191 #def __abs__(self):192 #def __invert__(self):193 #def __int__(self):194 #def __long__(self):195 #def __float__(self):196 #def __complex__(self):197 #def __oct__(self):198 #def __hex__(self):199 #def __coerce__(self,other):200201202 # Comparison Operations203 #def __lt__(self,other):204 #def __le__(self,other):205 #def __gt__(self,other):206 #def __ge__(self,other):207208 def __eq__(self,other):209 #print '__eq__'210 if (isinstance(other,Matrix)) and (self.getRowCount()==other.getRowCount()) and (self.getColumnCount()==other.getColumnCount()):211 for i in range(self.getRowCount()):212 for j in range(self.getColumnCount()):213 if self[i][j] != other[i][j]:214 #print '... mismatch: ' + ' i=' + str(i) + ' j=' + str(j) + ' ' +str(self[i][j]) + ' ' + str(other[i][j])215 return 0216 return 1217 else:218 return 0219220 def __ne__(self,other):221 if (isinstance(other,Matrix)) and (self.getRowCount()==other.getRowCount()) and (self.getColumnCount()==other.getColumnCount()):222 for i in range(self.getRowCount()):223 for j in range(self.getColumnCount()):224 if self[i][j] != other[i][j]:225 return 1226 return 0227 else:228 return 1229230 # Overidding methods of DataType231 def _copyTo(self,other):232 # not implemented233 #if isinstance(other,Matrix):234 # other.value=self.value235 #else:236 DataType._copyTo(self,other)237238 # shallow copy239 def _copyFrom(self,other):240 if isinstance(other,Matrix):241 # check the size of other matrix if it's important.242 if self.isFixedSize() and ((self.getRowCount()!= other.getRowCount()) or (self.getColumnCount() != other.getColumnCount())):243 raise ValueError(str(self)+' copyFrom '+str(other)+': mis-matched sizes')244 else:245 self.setValueType(other.getValueType())246 # setData updates the units, initialValue, isFixedSize,247 self.setData(other)248 elif isinstance(other, Vector.Vector):249 if self.isFixedSize() and (self.getRowCount()!=other.getSize()) or (self.getColumnCount()!=1):250 raise ValueError(str(self)+' copyFrom '+str(other)+': mis-matched sizes')251 elif self.isFixedSize() and (self.getColumnCount()!=other.getSize()) or (self.getRowCount()!=1):252 raise ValueError(str(self)+' copyFrom '+str(other)+': mis-matched sizes')253 elif (self.isFixedSize() and self.getColumnCount()==1):254 self.setValueType(other.getValueType())255 self.setUnit(other.getUnit())256 self.setInitialValue(other.getInitialValue())257 self.setFixedSize(other.getFixedSize())258 for i in range(other.getSize()):259 self[i][0] = other[i]260 elif (self.isFixedSize() and self.getRowCount()==1):261 self.setValueType(other.getValueType())262 self.setUnit(other.getUnit())263 self.setInitialValue(other.getInitialValue())264 self.setFixedSize(other.getFixedSize())265 for i in range(other.getSize()):266 self[0][i] = other[i]267 else:268 self.setValueType(other.getValueType())269 self.setRowCount(1);270 self.setColumnCount(other.getSize());271 self.setUnit(other.getUnit())272 self.setInitialValue(other.getInitialValue())273 self.setFixedSize(other.getFixedSize())274 for i in range(other.getSize()):275 self[0][i] = other[i]276 elif isinstance(other, ListType):277 if self.isFixedSize() and (self.getRowCount()!=len(other)) or (self.getColumnCount()!=1):278 raise ValueError(str(self)+' copyFrom '+str(other)+': mis-matched sizes')279 elif self.isFixedSize() and (self.getColumnCount()!=len(other)) or (self.getRowCount()!=1):280 raise ValueError(str(self)+' copyFrom '+str(other)+': mis-matched sizes')281 elif (self.isFixedSize() and self.getColumnCount()==1):282 self.setValueType(other.getValueType())283 self.setUnit(other.getUnit())284 self.setInitialValue(other.getInitialValue())285 self.setFixedSize(other.getFixedSize())286 for i in range(len(other)):287 self[i][0] = other[i]288 elif (self.isFixedSize() and self.getRowCount()==1):289 self.setValueType(other.getValueType())290 self.setUnit(other.getUnit())291 self.setInitialValue(other.getInitialValue())292 self.setFixedSize(other.getFixedSize())293 for i in range(len(other)):294 self[0][i] = other[i]295 else:296 self.setValueType(other.getValueType())297 self.setRowCount(1);298 self.setColumnCount(len(other));299 self.setUnit(other.getUnit())300 self.setInitialValue(other.getInitialValue())301 self.setFixedSize(other.getFixedSize())302 for i in range(len(other)):303 self[0][i] = other[i]304 else:305 # raises TypeError306 DataType._copyFrom(self,other)307308309 def dup(self):310 # return a copy of one self311 #return Matrix(self.duplicate())312 # !!!!!!!! deep copy in Java is broken !!!!!!313 returnMatrix=Matrix(self.getRowCount(),self.getColumnCount())314 for i in range(self.getRowCount()):315 for j in range(self.getColumnCount()):316 if isNumberType(self[i][j]):317 returnMatrix[i][j]=self[i][j]318 else:319 returnMatrix[i][j]=self[i][j].dup()320 returnMatrix.setUnit(self.getUnit())321 returnMatrix.setInitialValue(self.getInitialValue())322 returnMatrix.setFixedSize(self.isFixedSize())323 returnMatrix.setValueType(self.getValueType())324 return returnMatrix325326327 # Matrix specific functions, probably will move to DMath.py328 def inverse(self):329 # eee... implement Gauss-Jordan elimination?330 # first matrix must be square331 if (not self.isSquare()):332 raise ValueError(str(self)+' must be sqaure to have an inverse.')333 elif (self.det()==0):334 raise ValueError(str(self)+' is not invertible, determinant == 0.')335 else:336 dim = self.getRowCount();337 augMatrix = self.catH(self.IdentityMatrix(dim,338 dim))339340 gauss = augMatrix.gaussianElimination()341 #print '.....Finished gaussian Elimination(): ' + str(gauss)342 # divide through by pivots343 #print '..... size of gauss, rows:' + str(gauss.getRowCount()) + ' cols:' + str(gauss.getColumnCount())344 for i in range(dim):345 pivot = gauss[i][i]346 #print '....pivot=' + str(pivot) + ' i=' + str(i)347 for j in range(2*dim):348 #print '.... j=' + str(j)349 #print '.......' + str(gauss[i][j])350 gauss[i][j]=gauss[i][j]/pivot351 if gauss[i][j] == 0:352 gauss[i][j] = 0353 return gauss.subMatrix(0, dim, dim-1, 2*dim-1)354355 def gaussianElimination(self):356 returnMatrix = self.dup()357 if (returnMatrix.getValueType()=='Integer'):358 returnMatrix.setValueType('real')359 diagonal = self.getColumnCount()360 if (self.getRowCount()<self.getColumnCount()):361 diagonal = self.getRowCount()362 for j in range(diagonal):363 rowIndex = returnMatrix._rowMax(j)364 returnMatrix._rowSwap(j, rowIndex)365 if (returnMatrix[j][j]==0.0):366 return Matrix(0,0)367 for k in range(self.getRowCount()):368 if (k!=j):369 returnMatrix._rowZero(j,j,k)370 return returnMatrix371372373 def catH(self, other):374 # return matrix of [self, other]375 # make sure the number of rows are equal376 ### MAYBE should use the java super's appendHorizontally()377 if not(isinstance(other, Matrix)):378 raise TypeError(str(other)+' is not a Matrix and cannnot be used in catH.')379 elif (self.getRowCount() != other.getRowCount()):380 raise ValueError(str(self)+' catH '+str(other)+' row number not the same.')381 else:382 tRow = self.getRowCount()383 tCol = self.getColumnCount() + other.getColumnCount()384 returnMatrix = Matrix(tRow, tCol)385 for i in range(tRow):386 for j in range(tCol):387 if j < self.getColumnCount():388 returnMatrix[i][j] = self[i][j]389 else:390 returnMatrix[i][j]=other[i][j-self.getColumnCount()]391 return returnMatrix392393 def catV(self, other):394 # return matrix of [self; other]395 # make sure the number of rows are equal396 ### MAYBE should use the java super's appendVertically()397 if not(isinstance(other, Matrix)):398 raise TypeError(str(other)+' is not a Matrix and cannnot be used in catV.')399 elif (self.getColumnCount() != other.getColumnCount()):400 raise ValueError(str(self)+' catV '+str(other)+' column number not the same.')401 else:402 tRow = self.getRowCount() + other.getRowCount()403 tCol = self.getColumnCount()404 returnMatrix = Matrix(tRow, tCol)405 for i in range(tRow):406 for j in range(tCol):407 if i < self.getRowCount():408 returnMatrix[i][j] = self[i][j]409 else:410 returnMatrix[i][j]=other[i-self.getRowCount()][j]411 return returnMatrix412413414415 def IdentityMatrix(self, rowCount, colCount):416 # errr, as close as it can get if it's not nxn.417 if (not(type(rowCount)==IntType) or not(type(colCount)==IntType)):418 raise TypeError(str(rowCount)+' or '+str(colCount)+' are not integer types')419 returnMatrix = Matrix(rowCount, colCount)420 cC=0421 for rC in range(rowCount):422 returnMatrix[rC][cC]=1423 cC=cC+1424 if cC >= colCount:425 return returnMatrix426 return returnMatrix427428 def transpose(self):429 # rows vs. columns.430 returnMatrix = Matrix(self.getColumnCount(), self.getRowCount())431 for i in range(self.getRowCount()):432 for j in range(self.getColumnCount()):433 returnMatrix[j][i] = self[i][j]434 return returnMatrix435436 def rowEchelon(self):437 numSwaps = 0438 return self._fwdElimination(numSwaps)[0]439440441442 def subMatrix(self, r1, c1, r2, c2):443 if r2 < r1:444 rHold = r2445 r2 = r1446 r1 = rHold447 if c2 < c1:448 cHold = c2449 c2 = c1450 c1 = cHold451 subRow = r2-r1+1452 subCol = c2-c1+1453 if (r2 < self.getRowCount()) and (c2 < self.getColumnCount()) and r1>=0 and r2 >=0:454 returnMatrix = Matrix(subRow, subCol)455 i2 = 0456 for i in range(r1,r2+1):457 j2 = 0458 for j in range(c1,c2+1):459 returnMatrix[i2][j2] = self[i][j]460 j2 = j2+1461 i2 = i2+1462 return returnMatrix463 else:464 raise IndexError('Indices not in range.')465466 def det(self):467 changedType = 0;468 if (self.isEmpty() or (not self.isSquare())):469 #print ' self is empty or not square'470 return 0.0471 if (self.getRowCount()==1):472 #print ' row count == 1'473 return self[0][0]474 if (self.getRowCount()==2):475 #print ' row count == 2'476 return ((self[0][0]*self[1][1])-(self[1][0]*self[0][1]))477 # matrix is not Empty, is Square, rows>2, use fwdElimination478 numSwaps = 0479 mtmp = self._fwdElimination(numSwaps)480 m = mtmp[0]481 numSwaps = mtmp[1]482 #print 'numSwaps: ' + str(numSwaps)483 if (m.isEmpty()):484 #print 'm is empty'485 return 0.0486 result = 1.0487 for i in range(self.getColumnCount()):488 result *= m[i][i]489 factor = -1490 if (numSwaps%2)==0:491 1492 result *= factor493 #print ' result: ' + str(result)494 return result495496497 def trace(self):498 result = 0.0499 diagonal = self.getColumnCount()500 if (self.getRowCount()<self.getColumnCount()):501 diagonal = self.getRowCount()502 for i in range(diagonal):503 result += self[i][i]504 return result505506507 def euclidNorm(self):508 return sqrt(self.sumOfSquares())509510511 def sumOfSquares(self):512 result = 0.0513 rows = self.getRowCount()514 cols = self.getColumnCount()515 value = 0.0516 for i in range(rows):517 for j in range(cols):518 value = self[i][j]519 result += value*value520 return result521522523 def absSum(self):524 result = 0.0525 for i in range(self.getRowCount()):526 for j in range(self.getColumnCount()):527 result += abs(self[i][j])528 return result529530531 def fill(self, value):532 # integer, real, float, int533 rows = self.getRowCount()534 cols = self.getColumnCount()535 if (isinstance(value, Number)):536 value = value.getValue()537 try:538 #print '...fill value: ' + str(value)539 for i in range(rows):540 for j in range(cols):541 #self.setItem(i,j,value)542 self[i][j] = value543 except TypeError, e:544 raise e545546 def getRow(self, index):547 # KJT, replaced following with line below: returnRow = self[index].dup()548 returnRow = DomeMatrixData.getRow(self, index)549 returnRow.setUnit(self.getUnit())550 return returnRow551552 def getCol(self, index):553 returnCol = DomeMatrixData.getCol(self, index)554 returnCol.setUnit(self.getUnit())555 return returnCol556 #KJT: changed implementation from that below to that above557 #returnVector = Vector.Vector()558 #returnVector.setSize(self.getRowCount())559 #returnVector.setValueType(self.getValueType())560 #returnVector.setInitialValue(self.getInitialValue())561 #returnVector.setUnit(self.getUnit())562 # assuming this is a column vector563 #for i in range(self.getRowCount()):564 # returnVector[i] = self[i][index]565 #return returnVector566567568 def numRows(self):569 return self.getRowCount()570571 def numCols(self):572 return self.getRowCount()573574 def size(self):575 return [self.getRowCount(), self.getColumnCount()]576 #KJT return self.getRowCount() * self.getColumnCount()577578 #def setSize(self, rows, cols):579 # self.setRowCount(rows)580 # self.setColumnCount(cols)581582 def setSize(self, rows, cols, value=0):583 oldRow = self.getRowCount()584 oldCol = self.getColumnCount()585 self.setRowCount(rows)586 self.setColumnCount(cols)587 if rows > oldRow:588 #print '...... set value of extra row'589 for i in range(oldRow, rows):590 for j in range(cols):591 #print 'i='+str(i)+' j='+str(j)+' val='+str(value)592 self[i][j] = value593 if cols > oldCol:594 #print '.... set value of extra col'595 for j in range(oldCol, cols):596 for i in range(rows):597 #print 'i='+str(i)+ ' j=' + str(j) + ' val=' + str(value)598 self[i][j] = value599600601 def setNumRows(self, rows, value=0):602 oldRow = self.getRowCount()603 self.setRowCount(rows)604 if rows > oldRow:605 for i in range(oldRow, rows):606 for j in range(self.getColumnCount()):607 self[i][j] = value608 #print 'i='+str(i)+' j='+ str(j)+' val='+str(value)609610611 def setNumCols(self, cols, value=0):612 oldCol = self.getColumnCount()613 self.setColumnCount(cols)614 if cols > oldCol:615 for j in range(oldCol, cols):616 for i in range(self.getRowCount()):617 self[i][j] = value618 #print 'i='+str(i)+' j='+str(j)+' val='+str(value)619620621 def setRow(self, index, value):622 if (not (isinstance(value, Vector.Vector))):623 raise TypeError('setRow(), ' +str(value)+': is not a Vector')624 if (value.getSize() != self.getColumnCount()) :625 raise ValueError('setRow(), '+str(value)+': mis-matched sizes')626 if (index >= self.getRowCount()):627 raise ValueError('setRow(), '+str(index)+': index out of range')628 else:629 for j in range(self.getColumnCount()):630 self[index][j] = value[j]631632633 def setCol(self, index, value):634 if (not (isinstance(value, Vector.Vector))):635 raise TypeError('setCol(), ' +str(value)+': is not a Vector')636 if (value.getSize() != self.getRowCount()) :637 raise ValueError('setCol(), '+str(value)+': mis-matched sizes')638 if (index >= self.getColumnCount()):639 raise ValueError('setCol(), '+str(index)+': index out of range')640 else:641 for i in range(self.getRowCount()):642 self[i][index] = value[i]643644 # Undefined645 def euclideanNorm():646 return sqrt(self.sumOfSquares())647648649650 # Actually implementation of mathematical operators651 def _add(self,other):652 if (isinstance(other, Number)):653 # scalar add654 returnMatrix = self.dup()655 if (isinstance(other, Real)):656 # automatically change return matrix type to real657 returnMatrix.setValueType("real")658 for i in range(returnMatrix.getRowCount()):659 for j in range(returnMatrix.getColumnCount()):660 returnMatrix[i][j] = returnMatrix[i][j]+other.value661 elif isNumberType(other):662 #scalar add663 returnMatrix = self.dup()664 if (type(other)==FloatType):665 # automatically change return matrix type to real666 returnMatrix.setValueType("real")667 for i in range(returnMatrix.getRowCount()):668 for j in range(returnMatrix.getColumnCount()):669 returnMatrix[i][j] = returnMatrix[i][j]+other670 return returnMatrix671 elif isinstance(other, Matrix):672 # check the size of other matrix673 if (self.getRowCount()== other.getRowCount()) and (self.getColumnCount() == other.getColumnCount()):674 returnMatrix = self.dup()675 for i in range(returnMatrix.getRowCount()):676 for j in range(returnMatrix.getColumnCount()):677 returnMatrix[i][j] = returnMatrix[i][j]+other[i][j]678 if (other.getValueType()=='real'):679 returnMatrix.setValueType('real')680 return returnMatrix681 else:682 raise ValueError(str(self)+' + '+str(other)+': mis-matched sizes')683 elif isinstance(other, Vector.Vector):684 if (self.getRowCount()==other.getSize()) and (self.getColumnCount()==1):685 returnMatrix = self.dup()686 for i in range(other.getSize()):687 returnMatrix[i][0] = returnMatrix[i][0] + other[i]688 return returnMatrix689 elif (self.getColumnCount()==other.getSize()) and (self.getRowCount()==1):690 returnMatrix = self.dup()691 for i in range(other.getSize()):692 returnMatrix[0][i] = returnMatrix[0][i] + other[i]693 return returnMatrix694 else:695 raise ValueError(str(self)+' + '+str(other)+': mis-matched sizes')696 elif isinstance(other, ListType):697 if ((self.getRowCount()==len(other)) and (self.getColumnCount()==1)):698 returnMatrix = self.dup()699 for i in range(len(other)):700 returnMatrix[i][0] = returnMatrix[i][0]+other[i]701 return returnMatrix702 elif (self.getColumnCount()==len(other)) and (self.getRowCount()==1):703 returnMatrix = self.dup()704 for i in range(len(other)):705 returnMatrix[0][i] = returnMatrix[0][i]+other[i]706 return returnMatrix707 else:708 raise ValueError(str(self)+' + '+str(other)+': mis-matched sizes')709710 else:711 raise TypeError('Matrix cannot be added to with '+712 other.getClass().getName())713714 def _sub(self,other):715 if isinstance(other, Number):716 #scalar sub717 returnMatrix = self.dup()718 for i in range(returnMatrix.getRowCount()):719 for j in range(returnMatrix.getColumnCount()):720 returnMatrix[i][j] = returnMatrix[i][j]-other.value721 elif isNumberType(other):722 #scalar sub723 returnMatrix = self.dup()724 for i in range(returnMatrix.getRowCount()):725 for j in range(returnMatrix.getColumnCount()):726 returnMatrix[i][j] = returnMatrix[i][j]-other727 return returnMatrix728 elif isinstance(other, Matrix):729 # check the size of other matrix730 if (self.getRowCount()== other.getRowCount()) and (self.getColumnCount() == other.getColumnCount()):731 returnMatrix = self.dup()732 for i in range(returnMatrix.getRowCount()):733 for j in range(returnMatrix.getColumnCount()):734 returnMatrix[i][j] = returnMatrix[i][j]-other[i][j]735 return returnMatrix736 else:737 raise ValueError(str(self)+' - '+str(other)+': mis-matched sizes')738 elif isinstance(other, Vector.Vector):739 if (self.getRowCount()==other.getSize()) and (self.getColumnCount()==1):740 returnMatrix = self.dup()741 for i in range(other.getSize()):742 returnMatrix[i][0] = returnMatrix[i][0] - other[i]743 return returnMatrix744 elif (self.getColumnCount()==other.getSize()) and (self.getRowCount()==1):745 returnMatrix = self.dup()746 for i in range(other.getSize()):747 returnMatrix[0][i] = returnMatrix[0][i] - other[i]748 return returnMatrix749 else:750 raise ValueError(str(self)+' - '+str(other)+': mis-matched sizes')751 elif isinstance(other, ListType):752 if ((self.getRowCount()==len(other)) and (self.getColumnCount()==1)):753 returnMatrix = self.dup()754 for i in range(len(other)):755 returnMatrix[i][0] = returnMatrix[i][0]-other[i]756 return returnMatrix757 elif (self.getColumnCount()==len(other)) and (self.getRowCount()==1):758 returnMatrix = self.dup()759 for i in range(len(other)):760 returnMatrix[0][i] = returnMatrix[0][i]-other[i]761 return returnMatrix762 else:763 raise ValueError(str(self)+' - '+str(other)+': mis-matched sizes')764 else:765 raise TypeError('Matrix cannot be subtracted to with a '+766 other.getClass().getName())767768 def _mul(self,other):769 if isinstance(other, Number):770 #scalar multiplication771 returnMatrix = self.dup()772 for i in range(returnMatrix.getRowCount()):773 for j in range(returnMatrix.getColumnCount()):774 returnMatrix[i][j] = returnMatrix[i][j]*other.value775 elif isNumberType(other):776 #scalar multiplication777 returnMatrix = self.dup()778779 for i in range(returnMatrix.getRowCount()):780 for j in range(returnMatrix.getColumnCount()):781 returnMatrix[i][j] = returnMatrix[i][j]*other782 return returnMatrix783 elif isinstance(other, Matrix):784 # check the size of other matrix, size of rows == size of columns785 # or number of columns == # of rows786 if (self.getColumnCount()== other.getRowCount()):787 # return has self # rows and other # columns788 returnMatrix = Matrix(self.getRowCount(),789 other.getColumnCount())790 for i in range(returnMatrix.getRowCount()):791 for j in range(returnMatrix.getColumnCount()):792 entry = 0793 for sC in range(selfMatrix.getColumnCount()):794 for oR in range(selfMatrix.getRowCount()):795 entry = self[i][sC]*other[oR][j]+entry796 returnMatrix[i][j] = entry797 return returnMatrix798 else:799 raise ValueError(str(self)+' * '+str(other)+': mis-matched sizes')800 elif isinstance(other, Vector.Vector):801 # !!!! Need to worry about reverse, Vector * Matrix802 if (self.getColumnCount()==other.getSize()):803 returnMatrix = Matrix(self.getRowCount(),804 1)805806 for i in range(returnMatrix.getRowCount()):807 entry = 0808 for sC in range(returnMatrix.getColumnCount()):809 entry = self[0][sC]*other[sC] + entry810 returnMatrix[i][0] = entry811 return returnMatrix812 else:813 raise ValueError(str(self)+' * '+str(other)+': mis-matched sizes')814 elif isinstance(other, ListType):815 if (self.getColumnCount()==len(other)):816 returnMatrix = Matrix(self.getRowCount(),817 1)818 for i in range(returnMatrix.getRowCount()):819 entry = 0820 for sC in range(returnMatrix.getColumnCount):821 entry = self[0][sC]*other[sC] + entry822 returnMatrix[i][0] = entry823 return returnMatrix824 else:825 raise ValueError(str(self)+' * '+str(other)+': mis-matched sizes')826 else:827 raise TypeError('Matrix cannot be multiplied by a '+828 other.getClass().getName())829830831 def _div(self,other):832 if isinstance(other, Number):833 #scalar multiplication834 returnMatrix = self.dup()835 for i in range(returnMatrix.getRowCount()):836 for j in range(returnMatrix.getColumnCount()):837 returnMatrix[i][j] = returnMatrix[i][j]/other.value838 elif isNumberType(other):839 #like scalar multiplication840 returnMatrix = self.dup()841842 for i in range(returnMatrix.getRowCount()):843 for j in range(returnMatrix.getColumnCount()):844 returnMatrix[i][j] = returnMatrix[i][j]/other845 return returnMatrix846 else:847 raise TypeError('Matrix cannot be divided by a '+848 other.getClass().getName())849850851 # Need to change852 #def _pow(self,other):853 #def __radd__(self,other):854 #def __rsub__(self,other):855 #def __rmul__(self,other):856 #def __rdiv__(self,other):857 #def __rmod__(self,other):858 #def __rpow__(self,other):859 #def __neg__(self):860 #def __pos__(self):861 #def __abs__(self):862 #def __int__(self):863 #def __float__(self):864 #def __long__(self):865 #def __complex__(self):866867868 # Undocumented helper functions869 def isEmpty(self):870 return (self.getRowCount()==0) or (self.getColumnCount()==0)871872 def isSquare(self):873 return self.getRowCount()==self.getColumnCount()874875 def isUpperTriangular(self):876 if (self.isEmpty()):877 return false878 rows = self.getRowCount()879 cols = self.getColumnCount()880 for i in range(1,rows):881 #if ((i<cols)&&((self[i][i]==0)) return false882 j = 0883 while (j<i) and (j<cols):884 if (self[i][j]!=0):885 return false886 j=j+1887 return true888889 def isNonSingular(self):890 if (self.isEmpty()):891 return false892 if (self.isUpperTriangular()):893 diagonal = self.getColumnCount()894 if (self.getRowCount()<self.getColumnCount()):895 diagonal = self.getRowCount()896 index = 0897 while (index<diagonal):898 if (self[index][index]==0):899 return false900 index=index+1901 return true902 rowEchelonForm = self.rowEchelon()903 rowEchelonForm.isNonSingular()904905906907908 # private helper functions doing row manipulations909910 def _fwdElimination(self, numSwaps):911 # numSwaps should be an int912 returnMatrix = self.dup()913 if (returnMatrix.getValueType() == 'Integer'):914 returnMatrix.setValueType('real')915 rows = self.getRowCount()916 cols = self.getColumnCount()917 diagonal = cols918 if (rows<cols):919 diagonal = rows920 numSwaps=0921 for j in range(diagonal):922 numSwaps += returnMatrix._rowSwap(j, returnMatrix._rowMax(j))923 if (returnMatrix[j][j]==0):924 #print 'found a 0 on the diagonal'925 # Not certain if this is what we really want to return...926 return [Matrix(0,0), numSwaps]927 for k in range(j+1, rows):928 #print '.... returnMatrix after rowSwap:' + str(returnMatrix)929 returnMatrix._rowZero(j,j,k)930 #print 'k=' + str(k) + ' matrix:' + str(returnMatrix)931 #print '???? ' + str(returnMatrix)932 return [returnMatrix, numSwaps]933934 def _rowSwap(self, r1, r2):935 # r1, r2 are int936 # assert r1 and r2 are valid937 if (r1==r2):938 return 0939 numCols = self.getColumnCount()940 tmp = 0.0941 for j in range(numCols):942 tmp = self[r1][j]943 self[r1][j]=self[r2][j]944 self[r2][j]=tmp945 return 1946947 def _rowScale(self, rIndex, factor):948 # rIndex is int, factor is real949 numCols = self.getColumnCount()950 for j in range(numCols):951 self[rIndex][j]*=factor952953 def _rowZero(self, col, r1, r2):954 # assert col, r1 and r2 are valid955 # adding a multiple of r1 to r2, r1 is left unchanged956 #print ' numerator: ' + str(self[r2][col])957 #print ' denominator ' + str(self[r1][col])958 numerator = float(self[r2][col])959 denominator = float(self[r1][col])960 factor = -1.0*(numerator/denominator)961 #print '_rowZero factor=' + str(factor) +' col=' + str(col) + ' r1='+ str(r1) + ' r2=' + str(r2)962 numCols = self.getColumnCount()963 for j in range(numCols):964 self[r2][j] += self[r1][j]*factor965 #print ' after rowZero: ' + str(self)966967968 def _rowMax(self, c):969 # returns number of row with highest absolute value in specified970 # column971 # starts searching at r=c972 # assert c is valid973 # c is an int974 r = c975 result = r976 #print '_rowMax c = ' + str(c)977 maxValue = fabs(self[result][c])978 #print '.... init maxValue ' + str(maxValue) + ' init result ' + str(result)979 for i in range(r, self.getRowCount()):980 #while r<self.getRowCount():981 currentValue = fabs(self[i][c])982 #print '...... currentValue at ' + str(i) + ' is:' + str(currentValue)983 if (currentValue > maxValue):984 result = i985 maxValue = currentValue986 #print '_rowMax result=' + str(result)987 return result988989990991 # Conversion functions992993 def array(self):994 returnList = []995 for i in range(self.getRowCount()):996 returnList.append(self[i].array())997 return returnList9989991000100110021003#Helper functions1004def isNumberType(x):1005 return type(x)==IntType or type(x)==FloatType100610071008
...
test_session.py
Source:test_session.py
1# Copyright (C) 2018-2021 CS GROUP - France. All Rights Reserved.2#3# This file is part of the Prewikka program.4#5# SPDX-License-Identifier: BSD-2-Clause6#7# Redistribution and use in source and binary forms, with or without8# modification, are permitted provided that the following conditions are met:9#10# 1. Redistributions of source code must retain the above copyright notice, this11# list of conditions and the following disclaimer.12#13# 2. Redistributions in binary form must reproduce the above copyright notice,14# this list of conditions and the following disclaimer in the documentation15# and/or other materials provided with the distribution.16#17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND18# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDi19# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE20# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR21# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES22# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;23# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND24# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS26# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.27"""28Tests for `prewikka.session.session`.29"""30from copy import deepcopy31import datetime32import time33from http import cookies34import pytest35from prewikka.config import ConfigSection36from prewikka.session.session import SessionInvalid, SessionExpired, SessionDatabase, Session37from prewikka.usergroup import User38from tests.fixtures import TEST_SESSION_ID39from tests.tests_session.utils import FakeAuthBackend, create_session, clean_sessions40def test_session_invalid():41 """42 Test `prewikka.session.session.SessionInvalid` error.43 """44 session_invalid = SessionInvalid()45 with pytest.raises(SessionInvalid):46 raise session_invalid47 session_invalid = SessionInvalid(login='test')48 with pytest.raises(SessionInvalid):49 raise session_invalid50def test_session_expired():51 """52 Test `prewikka.session.session.SessionExpired` error.53 """54 session_expired = SessionExpired()55 with pytest.raises(SessionExpired):56 raise session_expired57 session_expired = SessionExpired(login='test')58 with pytest.raises(SessionExpired):59 raise session_expired60def test_session_db_create_():61 """62 Test `prewikka.session.session.SessionDatabase.create_session` method.63 """64 user = User('anonymous')65 session_id = create_session(user)66 query = env.db.query('SELECT * from Prewikka_Session WHERE sessionid=%s', session_id)67 assert query.getRowCount() == 168 assert session_id in query.toString()69 assert user.name in query.toString()70 clean_sessions()71def test_session_db_update():72 """73 Test `prewikka.session.session.SessionDatabase.update_session` method.74 """75 session_database = SessionDatabase()76 user = User('anonymous')77 session_id = create_session(user)78 old_query = env.db.query('SELECT * from Prewikka_Session WHERE sessionid=%s', session_id)79 time_ = time.time() + 3600 # add 3600s80 session_database.update_session(session_id, time_)81 query = env.db.query('SELECT * from Prewikka_Session WHERE sessionid=%s', session_id)82 assert old_query.toString() != query.toString()83 assert query.getRowCount() == 184 assert session_id in query.toString()85 assert user.name in query.toString()86 assert datetime.datetime.utcfromtimestamp(time_).strftime('%Y-%m-%d %H:%M:%S')in query.toString()87 # wrong session_id: nothing happening88 fake_session_id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'89 session_database.update_session(fake_session_id, time_)90 clean_sessions()91def test_session_db_get():92 """93 Test `prewikka.session.session.SessionDatabase.get_session` method.94 """95 session_database = SessionDatabase()96 user = User('anonymous')97 session_id = create_session(user)98 query = env.db.query('SELECT * from Prewikka_Session WHERE sessionid=%s', session_id)99 assert query.getRowCount() == 1100 username, time_ = session_database.get_session(session_id)101 assert username == user.name102 assert datetime.datetime.utcfromtimestamp(time_).strftime('%Y-%m-%d %H:%M:%S')in query.toString()103 # wrong session_id: fail104 with pytest.raises(Exception):105 fake_session_id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'106 session_database.get_session(fake_session_id)107 clean_sessions()108def test_session_db_delete():109 """110 Test `prewikka.session.session.SessionDatabase.delete_session` method.111 """112 session_database = SessionDatabase()113 user = User('anonymous')114 # delete 1 session based on sessionid115 session_id = create_session(user)116 query = env.db.query('SELECT * from Prewikka_Session WHERE sessionid=%s', session_id)117 assert query.getRowCount() == 1118 session_database.delete_session(sessionid=session_id)119 query = env.db.query('SELECT * from Prewikka_Session WHERE sessionid=%s', session_id)120 assert query.getRowCount() == 0121 # delete 1 session based on userid122 session_id = create_session(user)123 query = env.db.query('SELECT * from Prewikka_Session WHERE userid=%s', user.id)124 assert session_id in query.toString()125 assert query.getRowCount() == 1126 session_database.delete_session(user=user)127 query = env.db.query('SELECT * from Prewikka_Session WHERE userid=%s', user.id)128 assert query.getRowCount() == 0129 # delete multiple sessions based on userid130 session_id_1 = create_session(user)131 session_id_2 = create_session(user)132 session_id_3 = create_session(user)133 query = env.db.query('SELECT * from Prewikka_Session WHERE userid=%s', user.id)134 assert session_id_1 in query.toString()135 assert session_id_2 in query.toString()136 assert session_id_3 in query.toString()137 assert query.getRowCount() == 3138 session_database.delete_session(user=user)139 query = env.db.query('SELECT * from Prewikka_Session WHERE userid=%s', user.id)140 assert query.getRowCount() == 0141 clean_sessions()142 # delete session based on invalid sessionid: nothing happening143 create_session(user)144 query = env.db.query('SELECT * from Prewikka_Session WHERE userid=%s', user.id)145 assert query.getRowCount() == 1146 fake_session_id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'147 session_database.delete_session(sessionid=fake_session_id)148 query = env.db.query('SELECT * from Prewikka_Session WHERE userid=%s', user.id)149 assert query.getRowCount() == 1150 # delete session based on invalid userid: nothing happening151 fake_user = User('fake')152 query = env.db.query('SELECT * from Prewikka_Session WHERE userid=%s', fake_user.id)153 assert query.getRowCount() == 0154 session_database.delete_session(user=fake_user)155 query = env.db.query('SELECT * from Prewikka_Session WHERE userid=%s', user.id)156 assert query.getRowCount() == 1157 query = env.db.query('SELECT * from Prewikka_Session WHERE userid=%s', fake_user.id)158 assert query.getRowCount() == 0159 # delete session with both userid and sessionid: fail160 with pytest.raises(Exception):161 fake_session_id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'162 fake_user_id = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'163 session_database.delete_session(sessionid=fake_session_id, user=fake_user_id)164 # delete session without userid and sessionid: nothing165 session_database.delete_session(sessionid=None, user=None)166 clean_sessions()167def test_session_db_delete_expired_():168 """169 Test `prewikka.session.session.SessionDatabase.delete_expired_sessions` method.170 """171 session_database = SessionDatabase()172 user = User('anonymous')173 t_now = time.time()174 t_before = t_now - 3600175 t_after = t_now + 3600176 # without sessions in database177 session_database.delete_expired_sessions(t_now)178 # with 1 session expired in database179 session_id = create_session(user, t_before)180 session_database.delete_expired_sessions(t_now)181 query = env.db.query('SELECT * from Prewikka_Session WHERE sessionid=%s', session_id)182 assert query.getRowCount() == 0183 # with 1 session NOT expired in database184 session_id = create_session(user, t_after)185 session_database.delete_expired_sessions(t_now)186 query = env.db.query('SELECT * from Prewikka_Session WHERE sessionid=%s', session_id)187 assert query.getRowCount() == 1188 clean_sessions()189 # with 2 sessions expired and 1 not expired190 session_id_1 = create_session(user, t_before)191 session_id_2 = create_session(user, t_before)192 session_id_3 = create_session(user, t_after)193 query = env.db.query('SELECT * from Prewikka_Session WHERE userid=%s', user.id)194 assert query.getRowCount() == 3195 session_database.delete_expired_sessions(t_now)196 query = env.db.query('SELECT * from Prewikka_Session WHERE userid=%s', user.id)197 assert query.getRowCount() == 1198 assert session_id_1 not in query.toString()199 assert session_id_2 not in query.toString()200 assert session_id_3 in query.toString()201 clean_sessions()202def test_session():203 """204 Test `prewikka.session.session.Session` class.205 """206 session_config = ConfigSection("")207 session_config.expiration = 60 # 1 hour208 create_session(env.request.user, session_id=TEST_SESSION_ID)209 req = deepcopy(env.request.web)210 # __init__()211 session = Session(session_config)212 # get_user()213 user_from_session = session.get_user(req)214 assert env.request.user == user_from_session215 # get_user() with old (but valid) cookie216 clean_sessions()217 create_session(env.request.user, time_=time.time()-3600, session_id=TEST_SESSION_ID)218 user_from_session = session.get_user(req)219 assert env.request.user == user_from_session220 # get_user() with invalid session (empty cookie)221 with pytest.raises(SessionInvalid):222 req = deepcopy(env.request.web)223 req.input_cookie = {}224 session.get_user(req)225 # get_user() with expired session (AJAX request)226 with pytest.raises(SessionExpired):227 req = deepcopy(env.request.web)228 req.input_cookie = {}229 req.is_xhr = True230 session.get_user(req)231 # get_user() with invalid session (bad session_id)232 with pytest.raises(SessionInvalid):233 req = deepcopy(env.request.web)234 req.input_cookie['sessionid'] = cookies.Morsel()235 req.input_cookie['sessionid'].value = 'invalid'236 session.get_user(req)237 # get_user() with expired session (cookie expired)238 with pytest.raises(SessionExpired):239 clean_sessions()240 req = deepcopy(env.request.web)241 create_session(env.request.user, time_=time.time()-3600*24, session_id=TEST_SESSION_ID)242 session = Session(session_config)243 session.get_user(req)244 # get_user() with invalid user245 backup_user = env.request.user246 with pytest.raises(SessionInvalid):247 req = deepcopy(env.request.web)248 env.request.user = User('test')249 session.get_user(req)250 env.request.user = backup_user251 # get_user() with changed backend252 backup_auth = env.auth253 with pytest.raises(SessionInvalid):254 req = deepcopy(env.request.web)255 clean_sessions()256 create_session(env.request.user, session_id=TEST_SESSION_ID)257 env.auth = FakeAuthBackend(ConfigSection(""))258 session.get_user(req)259 env.auth = backup_auth260 # logout()261 with pytest.raises(SessionInvalid):262 clean_sessions()263 create_session(env.request.user, session_id=TEST_SESSION_ID)264 session = Session(session_config)265 req = deepcopy(env.request.web)266 session.logout(req)267 # can_logout()268 assert session.can_logout()...
ParseBED.py
Source:ParseBED.py
1from __future__ import print_function2# This file is part of DQXServer - (C) Copyright 2014, Paul Vauterin, Ben Jeffery, Alistair Miles <info@cggh.org>3# This program is free software licensed under the GNU Affero General Public License.4# You can find a copy of this license in LICENSE in the top directory of the source code or at <http://opensource.org/licenses/AGPL-3.0>5from builtins import str6from DQXTableUtils import VTTable7import sys8basepath = '.'9#============= FAKE STUFF FOR DEBUGGING; REMOVE FOR PRODUCTION ==============10if True:11 basepath = '/Users/pvaut/Documents/Genome/SnpCrossData3'12 sys.argv = ['', 'genomeregions.bed']13#============= END OF FAKE STUFF ============================================14if len(sys.argv)<2:15 print('Usage: COMMAND BEDFileName')16 sys.exit()17sourcefile = sys.argv[1]18tb = VTTable.VTTable()19tb.AddColumn(VTTable.VTColumn('chromid', 'Text'))20tb.AddColumn(VTTable.VTColumn('fstart', 'Value'))21tb.AddColumn(VTTable.VTColumn('fend', 'Value'))22tb.AddColumn(VTTable.VTColumn('fname', 'Text'))23tb.AddColumn(VTTable.VTColumn('fid', 'Text'))24tb.AddColumn(VTTable.VTColumn('ftype', 'Text'))25tb.AddColumn(VTTable.VTColumn('fparentid', 'Text'))26tb.AddColumn(VTTable.VTColumn('fnames', 'Text'))27tb.AddColumn(VTTable.VTColumn('descr', 'Text'))28nr = 029with open(basepath + '/' + sourcefile, 'r') as fp:30 for line in fp:31 tokens = line.rstrip('\r\n').split('\t')32 print(str(tokens))33 tb.AddRowEmpty()34 tb.SetValue(tb.GetRowCount()-1, 0, tokens[0])35 tb.SetValue(tb.GetRowCount()-1, 1, int(tokens[1]))36 tb.SetValue(tb.GetRowCount()-1, 2, int(tokens[2]))37 tb.SetValue(tb.GetRowCount()-1, 3, tokens[3])38 tb.SetValue(tb.GetRowCount()-1, 4, str(nr))39 tb.SetValue(tb.GetRowCount()-1, 5, 'region')40 tb.SetValue(tb.GetRowCount()-1, 6, '')41 tb.SetValue(tb.GetRowCount()-1, 7, '')42 tb.SetValue(tb.GetRowCount()-1, 8, '')43 nr += 144tb.PrintRows(0, 9)45tb.SaveSQLCreation(basepath + '/' + sourcefile +'.create.sql', 'regions')...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!