def GetMatrix(self, root=None, instance=None, scale=True, transpose=True): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Returns the matrix by which this object is transformed scale = False: returns the rotation and translation. no scaling info included Used to save the transformed geom --> coords --> new pdb file instance is a list of integer instance indices for all parents """ if root is None: root = self.viewer.rootObject if instance is None: instance = [0] p = self.parent while p: instance.append(0) p = p.parent GL.glPushMatrix() GL.glLoadIdentity() #print 'GetMatrix', instance self.BuildMat(self, root, scale, instance) #GL.glMultMatrixf(self.instanceMatricesFortran[instanceList[0]]]) m = Numeric.array(GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX)).astype('f') GL.glPopMatrix() if Numeric.alltrue(m==Numeric.zeros(16).astype('f')): # this happens when Pmv has no GUI m = Numeric.identity(4) if transpose: return Numeric.transpose(Numeric.reshape(m, (4,4))) else: return Numeric.reshape(m, (4,4))
def FrameTransform(self, camera=None): """Build the R an RI, the object's frame transformation and inverse""" GL.glPushMatrix() self.Si = Numeric.ones((3, )) GL.glLoadIdentity() m = Numeric.reshape(self.object.rotation, (4, 4)) upd = Numeric.reshape(Numeric.transpose(m), (16, )) GL.glMultMatrixf(self.object.Ri) GL.glMultMatrixf(upd) GL.glMultMatrixf(self.object.MatrixRotInv) self.Si = self.Si * self.object.Si / (self.object.scale * self.object.MatrixScale) self.Ri = Numeric.array(GL.glGetDoublev( GL.GL_MODELVIEW_MATRIX)).astype('f') GL.glPopMatrix() #self.Ri = Numeric.reshape(glCleanRotMat(self.Ri), (4,4) ) self.Ri = glCleanRotMat(self.Ri) self.R = Numeric.reshape(Numeric.transpose(self.Ri), (16, )).astype('f') self.Ri = Numeric.reshape(self.Ri, (16, )).astype('f') if self.redirectXform: self.redirectXform.FrameTransform(camera) for o in self.copyXform: o.FrameTransform(camera)
def computeBlurCurvature(radii, coords, blobbiness, points): # Compute Blur curvatures analytically by UTmolderivatives (since Novemeber 2005) from UTpackages.UTmolderivatives import molderivatives import numpy.oldnumeric as Numeric # Read input npoints = len(points) numberOfGaussians = len(coords) gaussianCenters = Numeric.zeros((numberOfGaussians, 4)).astype('d') for i in range(numberOfGaussians): gaussianCenters[i, 0:3] = coords[i] gaussianCenters[i, 3] = radii[i] numberOfGridDivisions = 10 # as in Readme.htm of UTmolderivatives maxFunctionError = 0.001 # as in Readme.htm of UTmolderivatives # Compute HandK, normals, k1Vector, k2Vector HandK, normals, k1Vector, k2Vector = molderivatives.getGaussianCurvature( gaussianCenters, numberOfGridDivisions, maxFunctionError, blobbiness, points) k1Vector = Numeric.reshape(k1Vector, (npoints, 3)) k2Vector = Numeric.reshape(k2Vector, (npoints, 3)) HandK = Numeric.reshape(HandK, (npoints, 2)) normals = Numeric.reshape(normals, (npoints, 3)) * ( -1) # change normal directions to outwards return normals
def prepareBillboardAndNormalForAllTextLines(self): if self.billboard: m = self.GetMatrix() m = Numeric.reshape(m, (16, )) rot = glCleanRotMat(m) #much faster than self.Decompose4x4(m) if self.includeCameraRotationInBillboard: # this permit billboarding even if the camera is not in the Z axis lCameraTransformation = self.viewer.currentCamera.GetMatrix() lCameraTransformation = Numeric.reshape( lCameraTransformation, (16, )) lCameraRotation = glCleanRotMat( lCameraTransformation ) #much faster than self.Decompose4x4(m) lCameraRotation = Numeric.transpose(lCameraRotation) rot = Numeric.dot(lCameraRotation, rot) rot = Numeric.reshape(rot, (16, )) self.billboardRotation = rot.astype('f') else: c = self.vertexSet.vertices.array n = self.vertexSet.normals.array lenn = len(n) if lenn > 0 and lenn != len(c): lMat = rotax.rotVectToVect(n[0], (0, 0, 1)) self.orientation = [ lMat[0][0], lMat[0][1], lMat[0][2], lMat[0][3], lMat[1][0], lMat[1][1], lMat[1][2], lMat[1][3], lMat[2][0], lMat[2][1], lMat[2][2], lMat[2][3], lMat[3][0], lMat[3][1], lMat[3][2], lMat[3][3] ]
def test_HSVBitmap(self): a = [j for i in range(16) for j in range(16)] b = [i for i in range(16) for j in range(16)] c = [max(i,j) for i in range(16) for j in range(16)] a = Numeric.reshape(a,(16,16)) / 255.0 b = Numeric.reshape(b,(16,16)) / 255.0 c = Numeric.reshape(c,(16,16)) / 255.0 hsv = HSVBitmap(a,b,c)
def test_HSVBitmap(self): a = [j for i in range(16) for j in range(16)] b = [i for i in range(16) for j in range(16)] c = [max(i, j) for i in range(16) for j in range(16)] a = Numeric.reshape(a, (16, 16)) / 255.0 b = Numeric.reshape(b, (16, 16)) / 255.0 c = Numeric.reshape(c, (16, 16)) / 255.0 hsv = HSVBitmap(a, b, c)
def End(self): import math # center the points around the origin sca = (1.0 / self.griddingSize) * self.gridToWorld points = Numeric.array(self.shape, 'f') * sca xsum, ysum = 0, 0 if points: repeat = 0 comp = points[-1] - points[0] if abs(comp[0]) < .01 and abs(comp[1]) < .01: repeat = -1 for i in range(len(points) + repeat): xsum = xsum + points[i][0] ysum = ysum + points[i][1] xcenter = xsum / (len(points) + repeat) ycenter = ysum / (len(points) + repeat) origin = (xcenter, ycenter) points = points - origin points[:, 1:] = points[:, 1:] * -1 # 3D o = Numeric.ones((len(points), 1)) points = Numeric.concatenate((points, o), 1) # calculate normals to each side normals = Numeric.zeros((len(points) - 1, 3), 'f') for i in range(len(points) - 1): diff = points[i + 1] - points[i] if diff[1] == 0: normals[i][0] = 0.0 normals[i][1] = diff[0] / abs(diff[0]) else: slope = -diff[0] / diff[1] size = -math.sqrt(1 + slope**2) * (diff[1] / abs(diff[1])) normals[i][0] = 1.0 / size normals[i][1] = slope / size # duplicate vertices if self.dup.get(): pts = Numeric.concatenate((points, points), 1) self.points = Numeric.reshape(pts, (2 * len(points), 3)) norms1 = Numeric.concatenate( (Numeric.reshape(normals[-1], (1, 3)), normals)) norms2 = Numeric.concatenate( (normals, Numeric.reshape(normals[0], (1, 3)))) norms = Numeric.concatenate((norms1, norms2), 1) self.normals = Numeric.reshape(norms, (2 * len(points), 3)) # single vertices: average normals else: self.points = points self.normals = Numeric.zeros((len(points), 3)).astype('f') for i in range(len(points) - 1): n = (normals[i - 1] + normals[i]) / 2 self.normals[i] = n.astype('f') self.normals[len(points) - 1] = self.normals[0] print self.points else: self.points, self.normals = [], []
def _FirstValues(self, data=None, shape=None, datatype=None): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Set the initial set of values, always returns a copy""" if data is not None: if len(data) == 0: self.ashape = (0, ) + self.ashape[1:] return Numeric.zeros(self.ashape, self.type) elif isarray(data): # data is an Numeric array if not datatype: if self.type: datatype = self.type else: raise AttributeError('I Need a datatype') if data.typecode() == self.type: # right type if shape is None: self.ashape = data.shape if data.shape == self.ashape: return Numeric.array(data) else: return Numeric.reshape(data, shape) else: # bad type data = data.astype(datatype) if shape is None: self.ashape = data.shape # if data.shape == self.ashape: return Numeric.array(data) if data.shape == self.ashape: return data else: return Numeric.reshape(data, shape) else: # data is not an array if datatype and shape: data = Numeric.array(data, self.type) return Numeric.reshape(data, shape) elif datatype: d = Numeric.array(data, datatype) self.ashape = d.shape return d else: try: d = Numeric.array(data, self.type) except ValueError: raise ValueError('Bad argument') if d.dtype.char in Numeric.typecodes['Integer'] or \ d.dtype.char in Numeric.typecodes['UnsignedInteger']: d = Numeric.array(data, viewerConst.IPRECISION) else: d = Numeric.array(data, viewerConst.FPRECISION) self.ashape = d.shape return d else: # No data if datatype and shape: d = Numeric.zeros((0, ), self.type) d.shape = shape return d else: raise AttributeError('I Need a datatype and a shape')
def _FirstValues(self, data=None, shape=None, datatype=None): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Set the initial set of values, always returns a copy""" if data is not None: if len(data)==0: self.ashape = (0,) + self.ashape[1:] return Numeric.zeros( self.ashape, self.type) elif isarray(data): # data is an Numeric array if not datatype: if self.type: datatype = self.type else: raise AttributeError('I Need a datatype') if data.typecode() == self.type: # right type if shape is None: self.ashape = data.shape if data.shape == self.ashape: return Numeric.array(data) else: return Numeric.reshape(data, shape ) else: # bad type data = data.astype(datatype) if shape is None: self.ashape = data.shape # if data.shape == self.ashape: return Numeric.array(data) if data.shape == self.ashape: return data else: return Numeric.reshape(data, shape) else: # data is not an array if datatype and shape: data = Numeric.array( data, self.type) return Numeric.reshape( data, shape ) elif datatype: d=Numeric.array( data, datatype) self.ashape = d.shape return d else: try: d=Numeric.array( data, self.type) except ValueError: raise ValueError('Bad argument') if d.dtype.char in Numeric.typecodes['Integer'] or \ d.dtype.char in Numeric.typecodes['UnsignedInteger']: d=Numeric.array( data, viewerConst.IPRECISION) else: d=Numeric.array( data, viewerConst.FPRECISION) self.ashape = d.shape return d else: # No data if datatype and shape: d = Numeric.zeros( (0,), self.type) d.shape = shape return d else: raise AttributeError('I Need a datatype and a shape')
def __init__(self, points, k, normalization=NORM_NORM_T0_1, force=False): """ calculate k polynomials of degree 0 to k-1 orthogonal on a set of distinct points map points to interval [-1,1] INPUT: points: array of dictinct points where polynomials are orthogonal k: number of polynomials of degree 0 to k-1 force=True creates basis even if orthogonality is not satisfied due to numerical error USES: x: array of points mapped to [-1,1] T_: matrix of values of polynomials calculated at x, shape (k,len(x)) TT_ = T_ * Numeric.transpose(T_) TTinv_ = inverse(TT_) sc_: scaling factors a, b: coefficients for calculating T (2k-4 different from 0, i.e. 6 for k=5) n: number of points = len(points) normalization = {0|1|2} """ self.k = k # number of basis polynomials of order 0 to k-1 self._force = force self.points = Numeric.asarray(points, Numeric.Float) self.pointsMin = min(points) self.pointsMax = max(points) # scaling x to [-1,1] results in smaller a and b, T is not affected; overflow is NOT a problem! self.xMin = -1 self.xMax = 1 self.x = self._map(self.points, self.pointsMin, self.pointsMax, self.xMin, self.xMax) # calculate basis polynomials self.n = len(points) # the number of approximation points t = Numeric.zeros((k,self.n),Numeric.Float) a = Numeric.zeros((k,1),Numeric.Float) b = Numeric.zeros((k,1),Numeric.Float) t[0,:] = Numeric.ones(self.n,Numeric.Float) if k > 1: t[1,:] = self.x - sum(self.x)/self.n for i in range(1,k-1): a[i+1] = Numeric.innerproduct(self.x, t[i,:] * t[i,:]) / Numeric.innerproduct(t[i,:],t[i,:]) b[i] = Numeric.innerproduct(t[i,:], t[i,:]) / Numeric.innerproduct(t[i-1,:],t[i-1,:]) t[i+1,:] = (self.x - a[i+1]) * t[i,:] - b[i] * t[i-1,:] self.a = a self.b = b # prepare for approximation self._T0 = t # orthonormal _TT0 = Numeric.matrixmultiply(self._T0, Numeric.transpose(self._T0)) self.sc1 = Numeric.sqrt(Numeric.reshape(Numeric.diagonal(_TT0),(self.k,1))) # scaling factors = sqrt sum squared self._T0 self._T1 = self._T0 / self.sc1 # orthonormal and T[0] == 1 self.sc2 = Numeric.sqrt(Numeric.reshape(Numeric.diagonal(_TT0),(self.k,1)) / self.n) # scaling factors = sqrt 1/n * sum squared self._T0 self._T2 = self._T0 / self.sc2 # T[:,-1] == 1 self.sc3 = Numeric.take(self._T0, (-1,), 1) # scaling factors = self._T0[:,-1] self._T3 = self._T0 / self.sc3 # set the variables according to the chosen normalization self.setNormalization(normalization)
def _ShapeValues(self, values): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Check type and shape, coerce if needed""" if isarray(values) and values.dtype.char == self.type: if values.shape[1:] == self.fixedShape: return values else: return Numeric.reshape(values, (-1, ) + self.fixedShape) else: values = Numeric.array(values, self.type) return Numeric.reshape(values, (-1, ) + self.fixedShape)
def _ShapeValues(self, values): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Check type and shape, coerce if needed""" if isarray(values) and values.dtype.char == self.type: if values.shape[1:] == self.fixedShape: return values else: return Numeric.reshape( values, ( -1,) + self.fixedShape ) else: values = Numeric.array( values, self.type) return Numeric.reshape( values, ( -1,) + self.fixedShape )
def random2DArray(matrix, ranNr=1, mask=None): """ Create randomized 2D array containing ones and zeros. @param matrix: matrix to randomize @type matrix: 2D array @param mask: mask OR None (default: None) @type mask: list(1|0) @param ranNr: number of matricies to add up (default: 1) @type ranNr: integer @return: 2D array or |ranNr| added contact matricies @rtype:2D array @raise MathUtilError: if mask does not fit matrix """ ## get shape of matrix a, b = N.shape(matrix) ## get array from matrix that is to be randomized if mask is not None: if len(mask) == len(N.ravel(matrix)): array = N.compress(mask, N.ravel(matrix)) if len(mask) != len(N.ravel(matrix)): raise MathUtilError( 'MatUtils.random2DArray - mask of incorrect length' + '\tMatrix length: %i Mask length: %i'\ %(len( N.ravel(matrix) ), len(mask))) if not mask: array = N.ravel(matrix) ## number of ones and length of array nOnes = int(N.sum(array)) lenArray = len(array) ranArray = N.zeros(lenArray) ## create random array for n in range(ranNr): ranArray += randomMask(nOnes, lenArray) ## blow up to size of original matix if mask is not None: r = N.zeros(a * b) N.put(r, N.nonzero(mask), ranArray) return N.reshape(r, (a, b)) if not mask: return N.reshape(ranArray, (a, b))
def random2DArray( matrix, ranNr=1, mask=None): """ Create randomized 2D array containing ones and zeros. @param matrix: matrix to randomize @type matrix: 2D array @param mask: mask OR None (default: None) @type mask: list(1|0) @param ranNr: number of matricies to add up (default: 1) @type ranNr: integer @return: 2D array or |ranNr| added contact matricies @rtype:2D array @raise MathUtilError: if mask does not fit matrix """ ## get shape of matrix a,b = N.shape( matrix ) ## get array from matrix that is to be randomized if mask is not None: if len(mask) == len( N.ravel(matrix) ): array = N.compress( mask, N.ravel(matrix) ) if len(mask) != len( N.ravel(matrix) ): raise MathUtilError( 'MatUtils.random2DArray - mask of incorrect length' + '\tMatrix length: %i Mask length: %i'\ %(len( N.ravel(matrix) ), len(mask))) if not mask: array = N.ravel(matrix) ## number of ones and length of array nOnes = int( N.sum( array ) ) lenArray = len( array ) ranArray = N.zeros( lenArray ) ## create random array for n in range(ranNr): ranArray += randomMask( nOnes, lenArray ) ## blow up to size of original matix if mask is not None: r = N.zeros(a*b) N.put( r, N.nonzero(mask), ranArray) return N.reshape( r, (a,b) ) if not mask: return N.reshape( ranArray, (a,b) )
def GetMatrixInverse(self, root=None, instance=None): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Returns the inverse of the matrix used to transform this object""" if root is None: root = self.viewer.rootObject m = self.GetMatrix(root, instance) m = Numeric.reshape(Numeric.transpose(m), (16,)).astype('f') rot, transl, scale = self.Decompose4x4(m) sc = Numeric.concatenate((Numeric.reshape(scale,(3,1)), [[1]])) n = Numeric.reshape(rot, (4,4))/sc tr = Numeric.dot(n, (transl[0], transl[1], transl[2],1) ) n[:3,3] = -tr[:3].astype('f') return n
def loadResContacts( self ): """ Uncompress residue contact matrix if necessary. @return: dict with contact matrix and parameters OR None @rtype: dict OR None """ ## Backwards compatibility if self.contacts != None and type( self.contacts ) == str: self.contacts = t.load( self.contacts ) EHandler.warning("loading old-style pickled contacts.") return self.contacts ## New, uncompression from list of indices into raveled array if self.contacts != None and \ len( N.shape( self.contacts['result'])) == 1: try: lenRec, lenLig = self.contacts['shape'] except: EHandler.warning("uncompressing contacts without shape") lenRec = self.rec().lenResidues() lenLig = self.lig().lenResidues() m = N.zeros( lenRec * lenLig ) N.put( m, self.contacts['result'], 1 ) self.contacts['result'] = N.reshape( m, (lenRec, lenLig) ) return self.contacts
def setUp(self): """ Uses topo/tests/unit/testbitmap.jpg in the unit tests directory """ miata = Image.open(resolve_path('topo/tests/unit/testbitmap.jpg')) miata = miata.resize((miata.size[0] / 2, miata.size[1] / 2)) self.rIm, self.gIm, self.bIm = miata.split() self.rseq = self.rIm.getdata() self.gseq = self.gIm.getdata() self.bseq = self.bIm.getdata() self.rar = Numeric.array(self.rseq) self.gar = Numeric.array(self.gseq) self.bar = Numeric.array(self.bseq) self.ra = Numeric.reshape(self.rar, miata.size) / 255.0 self.ga = Numeric.reshape(self.gar, miata.size) / 255.0 self.ba = Numeric.reshape(self.bar, miata.size) / 255.0
def update(self): vertices = self.geom.getVertices() normals = self.geom.getVNormals() pts = Numeric.concatenate((vertices, vertices + normals), 1) pts = Numeric.reshape(pts, (len(vertices), 2, -1)).astype('f') self.normalsGeom.Set(vertices=pts) self.viewer.Redraw()
def derivatives(self): # make array of numbers depthString = self.getDepthString() self.depth = Numeric.array(depthString, 'c')[2::4].astype(Numeric.Int8) self.dsq = Numeric.reshape(self.depth, (self.w, self.h)) self.fstD = Numeric.zeros((self.w, self.h), Numeric.Int8) self.sndD = Numeric.zeros((self.w, self.h), Numeric.Int8) self.deriv = Numeric.zeros((self.w, self.h), Numeric.Int8) for i in range(1, self.w-1): for j in range(1, self.h-1): a, b = self._derivatives(i,j) self.fstD[i][j] = a self.sndD[i][j] = b self.deriv[i][j] = max(a, b) # self.deriv = Numeric.choose( Numeric.greater(self.fstD,self.sndD), # (self.fstD,self.sndD) ) self.fstDim = Image.fromstring('P', (self.w,self.h), self.fstD.tostring()) self.sndDim = Image.fromstring('P', (self.w,self.h), self.sndD.tostring()) self.derivim = Image.fromstring('P', (self.w,self.h), self.deriv.tostring() )
def test_getSliceArray(self): assert hasattr(UTisocontour, 'getSliceArray') isovar=0 timestep=0 axis='x' sliceNum=10 step=1 sh = (1,1, self.auC.NELEMENTS[0], self.auC.NELEMENTS[1], self.auC.NELEMENTS[2]) da = Numeric.zeros(sh).astype('f') da[0][0] = Numeric.array( Numeric.reshape( Numeric.swapaxes( self.auC.array, 0, 2), self.auC.NELEMENTS ) ).astype('f') daSmall = Numeric.array(da[:,:,::step,::step,::step]).astype('f') center = Numeric.array(self.auC.CENTER).astype('f') dim = Numeric.array(self.auC.NELEMENTS).astype('f') span = Numeric.array(self.auC.SPACING).astype('f') print("span:", span) orig = center - ((dim-1)/2)*span print("orig: ", orig) the_data = UTisocontour.newDatasetRegFloat3D(daSmall, orig.astype('f'), (span*step,)*3 ) #the_data = UTisocontour.newDatasetRegFloat3D(daSmall) sld = UTisocontour.getSliceArray(the_data, isovar, timestep, axis, sliceNum) print('sld.shape' ,sld.shape) assert sld.shape == (61, 41)
def update(self): vertices = self.geom.getVertices() normals = self.geom.getVNormals() pts = Numeric.concatenate( (vertices, vertices+normals), 1) pts = Numeric.reshape( pts, (len(vertices),2,-1) ).astype('f') self.normalsGeom.Set(vertices = pts) self.viewer.Redraw()
def parse_xyzrn( self, output ): """ Extract xyz and r from output. @param output: STDOUT from pdb_to_xyzrn @type output: [str] @return: r, n - array with atom radii, list with atom names @rtype: array, array """ lines = output.split('\n') ## convert into lists that mslib will like xyzr = [] n = [] for l in lines: ## don't let the last empty line mess things up if len(l)!=0: l = string.split( l ) xyzr += [ float(l[0]), float(l[1]), \ float(l[2]), float(l[3]) ] n += [ l[5] ] xyzr = N.reshape( xyzr, ( len(xyzr)/4, 4 ) ) r = xyzr[:,3] ## xyz data is not passed on as it is not needed xyz = xyzr[:,:3] return r, n
def compute(self, coords, isHelix, nbrib=2, nbchords=10, width=1.5, offset=1.2, off_c=0.5): """ """ self.nrib = nbrib self.coords = coords natoms = len(self.coords) self.width = width self.chords = nbchords self.offset = offset self.isHelix = isHelix # Create a ribbon2D object self.smooth = Ribbon.ribbon2D(nbrib, width, nbchords, offset, natoms, coords, isHelix, off_c) self.oldsmooth = self.smooth self.addFirstLastPoints() self.verts2D_flat = Numeric.array( Numeric.reshape(self.smooth, (-1, 4))[:, :3]) path = (self.smooth[0, :, :3] + self.smooth[1, :, :3]) * 0.5 self.path = path.astype('f') self.faces2D = self.computeFaces2D() self.binormals = self.computeBinormals() self.normals = self.computeNormals() self.matrixTransfo = self.buildTransformationMatrix( self.path, self.normals, self.binormals)
def sortPoly(self, order=-1): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """None <- sortPoly(order=-1) Sorts the geometry polygons according to z values of polygon's geomtric centers. Order=-1 sorts by furthest z first, order=1 sorts by closest z first""" # FIXME will not work with instance matrices mat = self.GetMatrix() mat = Numeric.reshape(mat, (4,4)) vt = self.vertexSet.vertices*mat if vt is None: return triv = Numeric.take(vt, self.faceSet.faces.array) trig = Numeric.sum(triv,1)/3. trigz = trig[:,2] #triangle's center of gravity z value ind = Numeric.argsort(trigz) # sorted indices if len(self.faceSet.faces.array): faces = Numeric.take(self.faceSet.faces.array, ind[::order]) if self.shading==GL.GL_FLAT: # we also need to re-arrange the # face normals if self.normals is None: normals = None else: if len(self.normals)>1: normals = Numeric.take(self.normals, ind[::order]) else: normals = self.normals else: normals = None self.Set(faces=faces, fnormals=normals)
def derivatives(self): # make array of numbers depthString = self.getDepthString() self.depth = Numeric.array(depthString, 'c')[2::4].astype(Numeric.Int8) self.dsq = Numeric.reshape(self.depth, (self.w, self.h)) self.fstD = Numeric.zeros((self.w, self.h), Numeric.Int8) self.sndD = Numeric.zeros((self.w, self.h), Numeric.Int8) self.deriv = Numeric.zeros((self.w, self.h), Numeric.Int8) for i in range(1, self.w - 1): for j in range(1, self.h - 1): a, b = self._derivatives(i, j) self.fstD[i][j] = a self.sndD[i][j] = b self.deriv[i][j] = max(a, b) # self.deriv = Numeric.choose( Numeric.greater(self.fstD,self.sndD), # (self.fstD,self.sndD) ) self.fstDim = Image.fromstring('P', (self.w, self.h), self.fstD.tostring()) self.sndDim = Image.fromstring('P', (self.w, self.h), self.sndD.tostring()) self.derivim = Image.fromstring('P', (self.w, self.h), self.deriv.tostring())
def unpackBinaryMatrix( pcm, raveled=0 ): """ Uncompress array of 0 and 1 that was compressed with L{packBinaryMatrix}. @param pcm: {'shape':(X,Y,..), 'nonzero':[int]} @type pcm: dict @param raveled: return raveled (default: 0) @type raveled: 1|0 @return: N.array(X by Y by ..) of int @rtype: 2D array """ if type( pcm ) != dict: return pcm s = pcm['shape'] m = N.zeros( N.cumproduct( s )[-1], N.Int) pass ## m.savespace( 1 ) N.put( m, pcm['nonzero'], 1 ) if raveled: return m return N.reshape( m, s )
def doit(self, mobAtoms): """ mobAtoms: AtomSet that is being frozen. Assuming the AtomSet are from same molecule """ # fixme: need checking for mat (matrix) and mobAtoms geomContainer = mobAtoms[0].top.geomContainer mGeom = geomContainer.masterGeom mat = mGeom.rotation mat = Numeric.reshape(mat, (4, 4)) # update coords mobAtoms = mobAtoms.findType(Atom) coords = mobAtoms.coords hCoords = Numeric.concatenate((coords,Numeric.ones((len(coords),1),\ 'd')), 1) tCoords = Numeric.dot(hCoords, mat)[:, :3] tCoords = tCoords.tolist() mobAtoms.updateCoords(tCoords, 0) # overwritten the original coords # reset the rotation matrix of masterGeom identity = Numeric.identity(4, 'f').ravel() mGeom.SetRotation(Numeric.identity(4, 'f').ravel()) event = EditAtomsEvent('coords', mobAtoms) self.vf.dispatchEvent(event) mGeom.viewer.Redraw() return
def blurCoordsRadii(coords, radii, blobbyness=-0.1, res=0.5, weights=None, dims=None, padding=0.0): """blur a set of coordinates with radii """ # Setup grid resX = resY = resZ = res if not dims: minb, maxb = blur.getBoundingBox(coords, radii, blobbyness, padding) Xdim = int(round((maxb[0] - minb[0]) / resX + 1)) Ydim = int(round((maxb[1] - minb[1]) / resY + 1)) Zdim = int(round((maxb[2] - minb[2]) / resZ + 1)) else: Xdim, Ydim, Zdim = dims print "Xdim = %d, Ydim =%d, Zdim = %d" % (Xdim, Ydim, Zdim) # Generate blur map volarr, origin, span = blur.generateBlurmap(coords, radii, [Xdim, Ydim, Zdim], blobbyness, weights=weights, padding=padding) # Take data from blur map volarr.shape = [Zdim, Ydim, Xdim] volarr = Numeric.transpose(volarr).astype('f') origin = Numeric.array(origin).astype('f') stepsize = Numeric.array(span).astype('f') arrayf = Numeric.reshape(Numeric.transpose(volarr), (1, 1) + tuple(volarr.shape)) # Return data return arrayf, origin, stepsize
def loessMA(m, windowSize, axis=0, approxMasked=True, verbose=False, callback=None): """Returns a new array with values at the given axis smoothed by loess; if approxMasked==True: the masked values are approximated by loess; assumes equidistant spacing of points on the given axis. """ assert 0 < windowSize <= m.shape[axis]+0.1, "0 < windowSize[%s] <= 1 OR windowSize in range(1.1,m.shape[axis]+1) expected, got %f" % ("%", windowSize) m = MA.asarray(m) if m.dtype.char <> Numeric.Float: m = m.astype(Numeric.Float) shp_other = list(m.shape) shp_other.pop(axis) # get a transposed and reshaped mask and data from m; if m.mask() == None, construct a new array of zeros mask = Numeric.reshape(Numeric.transpose(MA.getmaskarray(m), [axis] + range(0,axis) + range(axis+1,len(m.shape))), (m.shape[axis], Numeric.multiply.reduce(shp_other))) data = MA.reshape(MA.transpose(m, [axis] + range(0,axis) + range(axis+1,len(m.shape))), (m.shape[axis], Numeric.multiply.reduce(shp_other))) maskInv = -1*(mask-1) xall = Numeric.arange(data.shape[0]) xallList = xall.tolist() for ii in Numeric.compress(Numeric.add.reduce(maskInv,0) > 1, range(data.shape[1])): # run loess if the profile contains more than 2 values try: data[:,ii] = MA.array(statc.loess(zip(MA.compress(maskInv[:,ii], xall).tolist(), MA.compress(maskInv[:,ii], data[:,ii]).tolist()), xallList, windowSize))[:,1] except: if verbose: print "Warning: loessMA: could not loess axis %i index %i" % (axis, ii) if callback: callback() if not approxMasked: data = MA.array(data, mask=mask) return MA.transpose(MA.reshape(data, [m.shape[axis]] + shp_other), [axis] + range(0,axis) + range(axis+1,len(m.shape)))
def LoadData(self): #load colormap from file import os myfile = open("ct_head.rawiv", "rb") print(("myfile: ", myfile)) if not myfile: print("Error: could not open file: ct_head.rawiv") else: #the header header = myfile.read(68) # unpack header following rawiv format,big endian h = unpack('>6f5I6f', header) width = int(h[8]) height = int(h[9]) depth = int(h[10]) # load the data l = myfile.read(width * height * depth) self.data = Numeric.fromstring(l, Numeric.UnsignedInt8, (width * height * depth)) self.size = (width, height, depth) print(("size: ", self.size)) #self.data = Numeric.reshape(self.data,(width,height,depth)) myfile.close() myfile = open("colormap.map", "rb") if not myfile: print("Error: Could not open file: colormap.map") else: l = myfile.read(256 * 4) self.byte_map = Numeric.fromstring(l, Numeric.UnsignedInt8, (256 * 4)) self.byte_map = Numeric.reshape(self.byte_map, (256, 4)) myfile.close()
def LoadData(self): #load colormap from file import os myfile = open("ct_head.rawiv", "rb" ) print(("myfile: ", myfile)) if not myfile: print("Error: could not open file: ct_head.rawiv") else: #the header header=myfile.read(68) # unpack header following rawiv format,big endian h = unpack('>6f5I6f',header) width=int(h[8]) height=int(h[9]) depth =int(h[10]) # load the data l = myfile.read(width*height*depth) self.data = Numeric.fromstring(l, Numeric.UnsignedInt8, (width*height*depth) ) self.size = (width, height, depth) print(("size: ", self.size)) #self.data = Numeric.reshape(self.data,(width,height,depth)) myfile.close() myfile = open("colormap.map", "rb" ) if not myfile: print("Error: Could not open file: colormap.map") else: l = myfile.read(256*4) self.byte_map =Numeric.fromstring(l, Numeric.UnsignedInt8, (256*4)) self.byte_map = Numeric.reshape(self.byte_map,(256,4)) myfile.close()
def unpackBinaryMatrix(pcm, raveled=0): """ Uncompress array of 0 and 1 that was compressed with L{packBinaryMatrix}. @param pcm: {'shape':(X,Y,..), 'nonzero':[int]} @type pcm: dict @param raveled: return raveled (default: 0) @type raveled: 1|0 @return: N.array(X by Y by ..) of int @rtype: 2D array """ if type(pcm) != dict: return pcm s = pcm['shape'] m = N.zeros(N.cumproduct(s)[-1], N.Int) pass ## m.savespace( 1 ) N.put(m, pcm['nonzero'], 1) if raveled: return m return N.reshape(m, s)
def inverse4X4(matrix): """ returns the inverse of the given 4x4 transformation matrix t_1: the negetive of Translation vector r_1: the inverse of rotation matrix inversed transformation is 1) t_1 applied first 2) then r_1 is applied to validate the result, N.dot(matrix, mat_inverse)==N.identity(4,'f') """ # check the shape if matrix.shape !=(4,4) and matrix.shape !=(16,) : raise ValueError("Argument must Numeric array of shape (4,4) or (16,)") return None if matrix.shape ==(16,): matrix=N.array(matrix,'f') matrix=N.reshape(matrix,(4,4)) # force the matrix to be (4,4) t_1=N.identity(4,'f') t_1[:2,3]= - matrix[:2, 3] r_1=N.identity(4,'f') r_1[:3,:3] = N.transpose(matrix[:3,:3]) mat_inverse=N.dot(r_1, t_1) #asert N.dot(matrix, mat_inverse) is N.identity(4,'f') return mat_inverse
def blurCoordsRadii(coords, radii, blobbyness=-0.1, res=0.5, weights=None, dims=None, padding = 0.0): """blur a set of coordinates with radii """ # Setup grid resX = resY = resZ = res if not dims: minb, maxb = blur.getBoundingBox(coords, radii, blobbyness, padding) Xdim = int(round( (maxb[0] - minb[0])/resX + 1)) Ydim = int(round( (maxb[1] - minb[1])/resY + 1)) Zdim = int(round( (maxb[2] - minb[2])/resZ + 1)) else: Xdim, Ydim, Zdim = dims print "Xdim = %d, Ydim =%d, Zdim = %d"%(Xdim, Ydim, Zdim) # Generate blur map volarr, origin, span = blur.generateBlurmap( coords, radii, [Xdim, Ydim, Zdim], blobbyness, weights=weights, padding=padding) # Take data from blur map volarr.shape = [Zdim, Ydim, Xdim] volarr = Numeric.transpose(volarr).astype('f') origin = Numeric.array(origin).astype('f') stepsize = Numeric.array(span).astype('f') arrayf = Numeric.reshape( Numeric.transpose(volarr), (1, 1)+tuple(volarr.shape) ) # Return data return arrayf, origin, stepsize
def setMatrixComponents(self, rot=None, trans=None, scale=None, redo=1): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Define MatrixRot, MatrixTransl, MatrixScale and MatrixRotInv from a rotation, translation and scale. rot should be a 4x4 matrix defining a 3D 3x3 rotation trans should be a 3D translation vector scale should be 3-vector of positive number larger than 0.0 """ self._modified = True if rot is not None: assert rot.shape==(4,4) self.MatrixRot = rot.ravel() RotInv = Numeric.transpose(rot) self.MatrixRotInv = Numeric.reshape(RotInv, (16,)) if trans is not None: assert len(trans)==3 self.MatrixTransl = trans if scale is not None: assert len(scale)==3 and scale[0]>0. and scale[1]>0. and scale[2]>0. self.MatrixScale = scale if redo: self.RedoDisplayList() self.viewer.Redraw()
def inverse4X4(matrix): """ returns the inverse of the given 4x4 transformation matrix t_1: the negetive of Translation vector r_1: the inverse of rotation matrix inversed transformation is 1) t_1 applied first 2) then r_1 is applied to validate the result, N.dot(matrix, mat_inverse)==N.identity(4,'f') """ # check the shape if matrix.shape != (4, 4) and matrix.shape != (16, ): raise ValueError("Argument must Numeric array of shape (4,4) or (16,)") return None if matrix.shape == (16, ): matrix = N.array(matrix, 'f') matrix = N.reshape(matrix, (4, 4)) # force the matrix to be (4,4) t_1 = N.identity(4, 'f') t_1[:2, 3] = -matrix[:2, 3] r_1 = N.identity(4, 'f') r_1[:3, :3] = N.transpose(matrix[:3, :3]) mat_inverse = N.dot(r_1, t_1) #asert N.dot(matrix, mat_inverse) is N.identity(4,'f') return mat_inverse
def transform_vertices(self,verts): v = Numeric.asarray(verts) homog = make_homogeneous_coord_rows(v) r = numpy.dot(homog,self.matrix) if len(homog.shape) > len(v.shape): r = Numeric.reshape(r,(4,)) return r
def setUp(self): """ Uses testbitmap.jpg in the topographica/tests directory """ miata = Image.open(resolve_path('tests/testbitmap.jpg')) miata = miata.resize((miata.size[0]/2,miata.size[1]/2)) self.rIm, self.gIm, self.bIm = miata.split() self.rseq = self.rIm.getdata() self.gseq = self.gIm.getdata() self.bseq = self.bIm.getdata() self.rar = Numeric.array(self.rseq) self.gar = Numeric.array(self.gseq) self.bar = Numeric.array(self.bseq) self.ra = Numeric.reshape(self.rar,miata.size) / 255.0 self.ga = Numeric.reshape(self.gar,miata.size) / 255.0 self.ba = Numeric.reshape(self.bar,miata.size) / 255.0
def ConcatTranslation(self, trans, redo=1): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Apply the translation trans to the object""" if self.redirectXform: obj = self.redirectXform else: obj = self obj._modified = True # MS. Feb 22 '99 obj.R does not contain the scaling factor # d = obj.Si * Numeric.array( trans ) #d = Numeric.array( trans ) #d = Numeric.concatenate( (d, [1.0]) ) # go to homogenous coords d = list(trans)+[1.0] rot = Numeric.reshape( obj.R, (4,4) ) ## obj.translation = obj.translation + \ ## Numeric.dot( rot, d )[:3] obj.translation = obj.translation + self.multMat4pt(rot, d) for o in self.copyXform: o.ConcatTranslation(trans) vi = self.viewer if vi.activeClippingPlanes > 0 or vi.activeScissor > 0 or \ (vi.currentObject!=vi.rootObject and not \ vi.redirectTransformToRoot) and redo and \ not self.immediateRendering: vi.deleteOpenglList() vi.Redraw() event = translateEvent('translate',obj) vi.dispatchEvent(event)
def normalize_homogeneous_rows(v): v = Numeric.asarray(v) homog = make_homogeneous_coord_rows(v) r = (homog/homog[:,3,Numeric.NewAxis])[:,:3] if len(homog.shape) > len(v.shape): r = Numeric.reshape(r,(3,)) return r
def doit(self,mobAtoms): """ mobAtoms: AtomSet that is being frozen. Assuming the AtomSet are from same molecule """ # fixme: need checking for mat (matrix) and mobAtoms geomContainer = mobAtoms[0].top.geomContainer mGeom = geomContainer.masterGeom mat = mGeom.rotation mat = Numeric.reshape(mat, (4,4)) # update coords mobAtoms = mobAtoms.findType(Atom) coords = mobAtoms.coords hCoords = Numeric.concatenate((coords,Numeric.ones((len(coords),1),\ 'd')), 1) tCoords = Numeric.dot(hCoords, mat)[:,:3] tCoords = tCoords.tolist() mobAtoms.updateCoords(tCoords, 0) # overwritten the original coords # reset the rotation matrix of masterGeom identity = Numeric.identity(4,'f').ravel() mGeom.SetRotation(Numeric.identity(4,'f').ravel() ) event = EditAtomsEvent('coords', mobAtoms) self.vf.dispatchEvent(event) mGeom.viewer.Redraw() return
def test_getSliceArray(self): assert hasattr(UTisocontour, 'getSliceArray') isovar = 0 timestep = 0 axis = 'x' sliceNum = 10 step = 1 sh = (1, 1, self.auC.NELEMENTS[0], self.auC.NELEMENTS[1], self.auC.NELEMENTS[2]) da = Numeric.zeros(sh).astype('f') da[0][0] = Numeric.array( Numeric.reshape(Numeric.swapaxes(self.auC.array, 0, 2), self.auC.NELEMENTS)).astype('f') daSmall = Numeric.array(da[:, :, ::step, ::step, ::step]).astype('f') center = Numeric.array(self.auC.CENTER).astype('f') dim = Numeric.array(self.auC.NELEMENTS).astype('f') span = Numeric.array(self.auC.SPACING).astype('f') print("span:", span) orig = center - ((dim - 1) / 2) * span print("orig: ", orig) the_data = UTisocontour.newDatasetRegFloat3D(daSmall, orig.astype('f'), (span * step, ) * 3) #the_data = UTisocontour.newDatasetRegFloat3D(daSmall) sld = UTisocontour.getSliceArray(the_data, isovar, timestep, axis, sliceNum) print('sld.shape', sld.shape) assert sld.shape == (61, 41)
def compute(self, coords , isHelix, nbrib = 2, nbchords = 10, width = 1.5, offset = 1.2, off_c = 0.5): """ """ self.nrib = nbrib self.coords = coords natoms = len(self.coords) self.width = width self.chords = nbchords self.offset = offset self.isHelix = isHelix # Create a ribbon2D object self.smooth = Ribbon.ribbon2D(nbrib, width, nbchords, offset, natoms, coords, isHelix, off_c) self.oldsmooth = self.smooth self.addFirstLastPoints() self.verts2D_flat = Numeric.array(Numeric.reshape(self.smooth, (-1,4))[:,:3]) path = (self.smooth[0,:,:3] + self.smooth[1,:,:3])*0.5 self.path = path.astype('f') self.faces2D = self.computeFaces2D() self.binormals = self.computeBinormals() self.normals = self.computeNormals() self.matrixTransfo= self.buildTransformationMatrix( self.path, self.normals, self.binormals)
def mul(self, coords, mat): shape = coords.shape assert shape[-1]==3 #coords = Numeric.reshape(coords, (-1, shape[-1])) one = Numeric.ones((shape[0],1),'f') c = Numeric.concatenate((coords, one),1) coords = Numeric.array(Numeric.reshape(coords, shape)) return Numeric.array(Numeric.dot(c, Numeric.transpose(mat))[:,:3])
def centers(self): """ Get 'center structure' for each cluster. @return: N.array( n_clusters x n_atoms_masked x 3 ) @rtype: array """ lenAtoms = N.shape(self.fcCenters)[1] / 3 return N.reshape(self.fcCenters, (self.n_clusters, lenAtoms, 3))
def __frame( self ): """Collect next complete coordinate frame @return: coordinate frame @rtype: array """ self.xyz = [ self.__nextLine() for i in range(self.lines_per_frame) ] return N.reshape(self.xyz, ( self.n, 3 ) ).astype(N.Float32)
def centers( self ): """ Get 'center structure' for each cluster. @return: N.array( n_clusters x n_atoms_masked x 3 ) @rtype: array """ lenAtoms = N.shape( self.fcCenters )[1] / 3 return N.reshape( self.fcCenters, ( self.n_clusters, lenAtoms, 3))
def updateVector(self, mat): mat = Numeric.reshape(mat, (4,4)) newPts = self.vector + [1] newPts = Numeric.dot( [newPts], mat )[0] self.vector = [newPts[0], newPts[1], newPts[2]] self.setEntries() self.drawVector() if self.continuous: self.callbacks.CallCallbacks(self.vector)
def updateVector(self, mat): mat = Numeric.reshape(mat, (4, 4)) newPts = self.vector + [1] newPts = Numeric.dot([newPts], mat)[0] self.vector = [newPts[0], newPts[1], newPts[2]] self.setEntries() self.drawVector() if self.continuous: self.callbacks.CallCallbacks(self.vector)
def __init__(self, name='Common2d3dObject', check=1, **kw): """Constructor """ #self.newList = GL.glGenLists(1) self.name = name self.viewer = None self.immediateRendering = False self.needsRedoDpyListOnResize = False self.protected = False # False == not protected against deletion self.replace = True # this is used to store in a geometry the # desired behavior when adding the geom to the Viewer. # in AddObject, if replace is not specified, geom.replace will be # used self.isExpandedInObjectList = 1 # set to 1 when children of that geom # are visible in ViewerGUI object list self.parent = None # parent object self.fullName = name # object's name including parent's name self.children = [] # list of children self.listed = True # When true the name of this object appears # in the GUI's object self.pickable = True # when set the object can be picked self.pickNum = 0 self.dpyList = None # display list for drawing self.pickDpyList = None # display list for picking # FIXME: quick hack. Flag set by SetCurrentXxxx. When set object's # transformation and material are saved in log file self.hasBeenCurrent = False self.depthMask = 1 # 0: zbuffer is readOnly for transparent objects # 1: zbuffer is read write for transparent objects self.srcBlendFunc = GL.GL_SRC_ALPHA #self.dstBlendFunc = GL.GL_ONE #GL.GL_ONE_MINUS_SRC_COLOR # ONE_MINUS_SRC_ALPHA works for colorMapEditor self.dstBlendFunc = GL.GL_ONE_MINUS_SRC_ALPHA self.transparent = False #viewerConst.NO self.visible = True m = Numeric.reshape( Numeric.identity(4), (1,16) ) self.instanceMatricesFortran = m.astype('f') self.ownGui = None self.animatable = True apply( self.Set, (check, 0), kw) self._modified = False # used to decide if we should save state
def translateCropbox(self, event, matrix, transXY, transZ): # FIXME won't work with instance matrices m = self.masterObject.GetMatrixInverse() for i in range(3): m[i][3] = 0 v = [transXY[0], transXY[1], 0, 1] v = Numeric.reshape(Numeric.array(v), (4, 1)) t = Numeric.dot(m, v) t = [t[0][0], t[1][0], t[2][0]] self.cropBox.Translate(t)
def FrameTransform(self, camera=None): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Build the R an RI, the object's frame transformation and inverse""" GL.glPushMatrix() self.Si = Numeric.ones( (3, ) ) GL.glLoadIdentity() if hasattr(self, 'parent'): if self.inheritXform: parent = self.parent while (parent): m = Numeric.reshape( parent.rotation, (4,4) ) upd = Numeric.reshape( Numeric.transpose(m), (16, ) ) GL.glMultMatrixf(upd) GL.glMultMatrixf(parent.MatrixRotInv) self.Si = self.Si / parent.scale self.Si = self.Si / parent.MatrixScale # we have to test here because we need to take into # account the first parent that does not inherit while # building R and Ri if not parent.inheritXform: break parent = parent.parent if camera: m = Numeric.reshape( camera.rotation, (4,4) ) upd = Numeric.reshape( Numeric.transpose(m), (16, ) ) GL.glMultMatrixf(upd) self.Si = self.Si / camera.scale self.Ri = Numeric.array(GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX)).astype('f') GL.glPopMatrix() self.Ri = glCleanRotMat(self.Ri).astype('f') self.Ri.shape = (4,4) self.R = Numeric.reshape( Numeric.transpose(self.Ri), (16, ) ).astype('f') self.Ri.shape = (16, ) if self.redirectXform: self.redirectXform.FrameTransform(camera) for o in self.copyXform: o.FrameTransform(camera)