def __init__(self, path3D, matrix, shape, cap1=0, cap2=0, arrow=0, larrow=3, warrow=2): """ Constructor: Takes as arguments a path3D, matrix, 2D shape, and optional cap1, cap2, and arrow. Calls getextrudeVertices() and getFaces() and stores the return values in self.vertices, self.vnormals , and self.faces. """ self.path3D = path3D self.matrix = matrix self.shape = shape self.arrow = arrow if not isinstance(self.shape, Rectangle2D): self.arrow = 0 self.larrow = larrow self.warrow = warrow self.cap1 = cap1 self.cap2 = cap2 if self.arrow: self.cap2 = 0 # no end cap if arrow self.norms = matrix[:, 0] self.vertices, self.vnormals = self.getextrudeVertices() self.faces = self.getFaces() # Here need to create a numeric array for each properties: # colors self.colors = Numeric.ones((len(self.faces), 3), 'f') # opacities self.opacities = Numeric.ones((len(self.faces), ), 'f')
def __init__(self, path3D, matrix, shape, cap1=0, cap2=0, arrow=0, larrow=3, warrow=2): """ Constructor: Takes as arguments a path3D, matrix, 2D shape, and optional cap1, cap2, and arrow. Calls getextrudeVertices() and getFaces() and stores the return values in self.vertices, self.vnormals , and self.faces. """ self.path3D = path3D self.matrix = matrix self.shape = shape self.arrow = arrow if not isinstance(self.shape, Rectangle2D): self.arrow = 0 self.larrow = larrow self.warrow = warrow self.cap1 = cap1 self.cap2 = cap2 if self.arrow: self.cap2 = 0 # no end cap if arrow self.norms = matrix[:,0] self.vertices, self.vnormals = self.getextrudeVertices() self.faces = self.getFaces() # Here need to create a numeric array for each properties: # colors self.colors = Numeric.ones((len(self.faces), 3),'f') # opacities self.opacities = Numeric.ones((len(self.faces),),'f')
def test_constructor_shape(self): """__init__ -- make refCoords and resultCoords homogeneous""" n = len(self.random_points) ncoords = Ncoords(self.random_points) ### tested call ### # confirm shape to be nx4 self.assertEqual((n, 4), Numeric.shape(ncoords.resultCoords)) self.assertEqual((n, 4), Numeric.shape(ncoords.refCoords)) # cofirm that the last column is all ones self.assertEqual( Numeric.ones(n).tolist(), ncoords.resultCoords[:, 3].tolist()) self.assertEqual( Numeric.ones(n).tolist(), ncoords.refCoords[:, 3].tolist())
def test_constructor_shape(self): """__init__ -- make refCoords and resultCoords homogeneous""" n = len(self.random_points) ncoords = Ncoords( self.random_points) ### tested call ### # confirm shape to be nx4 self.assertEqual( (n, 4), Numeric.shape(ncoords.resultCoords)) self.assertEqual( (n, 4), Numeric.shape(ncoords.refCoords)) # cofirm that the last column is all ones self.assertEqual(Numeric.ones(n).tolist(), ncoords.resultCoords[:,3].tolist()) self.assertEqual(Numeric.ones(n).tolist(), ncoords.refCoords[:,3].tolist())
def residusMaximus(self, atomValues, mask=None): """ Take list of value per atom, return list where all atoms of any residue are set to the highest value of any atom in that residue. (after applying mask) @param atomValues: list 1 x N, values per atom @type atomValues: [ float ] @param mask: list 1 x N, 0|1, 'master' atoms of each residue @type mask: [1|0] @return: Numpy array 1 x N of float @rtype: array """ if mask is None: mask = N.ones(len(self.frames[0]), N.int32) ## eliminate all values that do not belong to the selected atoms masked = atomValues * mask result = [] ## set all atoms of each residue to uniform value for res in range(0, self.resMap()[-1] + 1): ## get atom entries for this residue resAtoms = N.compress(N.equal(self.resMap(), res), masked) ## get maximum value masterValue = max(resAtoms) result += resAtoms * 0.0 + masterValue return N.array(result)
def doit(self, atom1, atom2, angle, mov_atoms, returnVal=0): mol = atom1.top if mov_atoms is None: mov_atoms = mol.subTree(atom1, atom2, mol.allAtoms) assert len(mov_atoms) mov_coords = Numeric.array(mov_atoms.coords) lenCoords = len(mov_coords) x = Numeric.array(atom1.coords) y = Numeric.array(atom2.coords) rot = (angle * 3.14159/180.)%(2 * Numeric.pi) matrix = rotax(x, y, rot) _ones = Numeric.ones(lenCoords, 'f') _ones.shape = (lenCoords,1) mov_coords = Numeric.concatenate((mov_coords, _ones),1) newcoords = Numeric.dot(mov_coords, matrix) nc = newcoords[:,:3].astype('f') for i in range(lenCoords): at = mov_atoms[i] at._coords[at.conformation] = nc[i].tolist() event = EditAtomsEvent('coords', mov_atoms) self.vf.dispatchEvent(event) #have to return nc for setTorsionGC if returnVal: return nc
def Reset(self): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Reset members to default values""" self.pattern = Numeric.ones((128, )) * 0xFF self.pattern = self.pattern.astype('B')
def SetMaterial(self, values, prop=1, tagModified=True): """Set the materials WARNING: when back face colors are set, two sided lighting has to be enabled we set RGB values for all properties except for shininess and opacity If an alpha value are specified they will be ignored Since IndexedGeomDSPL requires alpha values for all properties we set them automatically to 1.0 for all properties except for diffuse. The alpha channel of the diffuse component will be set later in fixOpacity which should be called after all properties of the material have been updated. """ if tagModified: self._modified = True if prop is None: prop = self.diff elif type(prop) is types.StringType: prop = getattr(self, prop) assert prop in (0, 1, 2, 3, 4, 5) values = array(values, 'f') if prop < self.shini: assert len(values.shape) == 2 and values.shape[1] in [3, 4] alpha = ones((values.shape[0], 1), 'f') values = concatenate((values[:, :3], alpha), 1) else: if len(values.shape) != 1: values = array([values], 'f') self.prop[prop] = values
def __make_rgb_matrices(self, rgb_matrices,shape,normalize,range_=False): """ Sub-function of plot() that return the h,s,v matrices corresponding to the current matrices in sliced_matrices_dict. The shape of the matrices in the dict is passed, as well as the normalize boolean parameter. The result specified a bitmap in hsv coordinate. Applies normalizing and cropping if required. """ zero=zeros(shape,Float) one=ones(shape,Float) r,g,b = rgb_matrices # Determine appropriate defaults for each matrix if r is None: r=zero if g is None: g=zero if b is None: b=zero # CEBALERT: have I checked this works? if normalize!='None': r = self._normalize(r,range_=range_) g = self._normalize(g,range_=range_) b = self._normalize(b,range_=range_) return (r,g,b)
def smooth(self): average = (Numeric.ones((3, 3), 'f') / 9.).astype('f') # average[1][1] = .0 print average self.redraw(filter=average) image = (self.imageAsArray()).astype('B') return image
def Map(values, colorMap, mini=None, maxi=None): """Get colors corresponding to values in a colormap""" values = Numeric.array(values) if len(values.shape)==2 and values.shape[1]==1: values.shape = ( values.shape[0], ) elif len(values.shape) > 1: print 'ERROR: values array has bad shape' return None cmap = Numeric.array(colorMap) if len(cmap.shape) !=2 or cmap.shape[1] not in (3,4): print 'ERROR: colorMap array has bad shape' return None if mini is None: mini = min(values) else: values = Numeric.maximum(values, mini) if maxi is None: maxi = max(values) else: values = Numeric.minimum(values, maxi) valrange = maxi-mini if valrange < 0.0001: ind = Numeric.ones( values.shape ) else: colrange = cmap.shape[0]-1 ind = ((values-mini) * colrange) / valrange col = Numeric.take(colorMap, ind.astype(viewerConst.IPRECISION)) return col
def castHmmDic(self, hmmDic, repete, hmmGap, key): """ Blow up hmmDic to the number of repetes of the profile used. Correct scores for possible deletions in the search sequence. @param hmmDic: dictionary from L{getHmmProfile} @type hmmDic: dict @param repete: repete information from L{align} @type repete: int @param hmmGap: information about gaps from L{align} @type hmmGap: [int] @param key: name of scoring method to adjust for gaps and repetes @type key: str @return: dictionary with information about the profile @rtype: dict """ s = hmmDic[key] for i in range(repete): mask = N.ones(len(s)) N.put(mask, hmmGap[i], 0) if i == 0: score = N.compress(mask, s, 0) if i > 0: score = N.concatenate((N.compress(mask, s, 0), score)) hmmDic[key] = score return hmmDic
def __make_hsv_matrices(self, hsc_matrices, shape, normalize, range_=False): """ Sub-function of plot() that return the h,s,v matrices corresponding to the current matrices in sliced_matrices_dict. The shape of the matrices in the dict is passed, as well as the normalize boolean parameter. The result specified a bitmap in hsv coordinate. Applies normalizing and cropping if required. """ zero = zeros(shape, Float) one = ones(shape, Float) s, h, c = hsc_matrices # Determine appropriate defaults for each matrix if s is None: s = one # Treat as full strength by default if c is None: c = one # Treat as full confidence by default if h is None: # No color, gray-scale plot. h = zero c = zero # If normalizing, offset the matrix so that the minimum # value is 0.0 and then scale to make the maximum 1.0 if normalize != 'None': s = self._normalize(s, range_=range_) # CEBALERT: I meant False, right? c = self._normalize(c, range_=False) # This translation from SHC to HSV is valid only for black backgrounds; # it will need to be extended also to support white backgrounds. hue, sat, val = h, c, s return (hue, sat, val)
def residusMaximus( self, atomValues, mask=None ): """ Take list of value per atom, return list where all atoms of any residue are set to the highest value of any atom in that residue. (after applying mask) @param atomValues: list 1 x N, values per atom @type atomValues: [ float ] @param mask: list 1 x N, 0|1, 'master' atoms of each residue @type mask: [1|0] @return: Numpy array 1 x N of float @rtype: array """ if mask is None: mask = N.ones( len( self.frames[0] ), N.int32 ) ## eliminate all values that do not belong to the selected atoms masked = atomValues * mask result = [] ## set all atoms of each residue to uniform value for res in range( 0, self.resMap()[-1]+1 ): ## get atom entries for this residue resAtoms = N.compress( N.equal( self.resMap(), res ), masked ) ## get maximum value masterValue = max( resAtoms ) result += resAtoms * 0.0 + masterValue return N.array( result )
def __make_hsv_matrices(self,hsc_matrices,shape,normalize,range_=False): """ Sub-function of plot() that return the h,s,v matrices corresponding to the current matrices in sliced_matrices_dict. The shape of the matrices in the dict is passed, as well as the normalize boolean parameter. The result specified a bitmap in hsv coordinate. Applies normalizing and cropping if required. """ zero=zeros(shape,Float) one=ones(shape,Float) s,h,c = hsc_matrices # Determine appropriate defaults for each matrix if s is None: s=one # Treat as full strength by default if c is None: c=one # Treat as full confidence by default if h is None: # No color, gray-scale plot. h=zero c=zero # If normalizing, offset the matrix so that the minimum # value is 0.0 and then scale to make the maximum 1.0 if normalize!='None': s=self._normalize(s,range_=range_) # CEBALERT: I meant False, right? c=self._normalize(c,range_=False) # This translation from SHC to HSV is valid only for black backgrounds; # it will need to be extended also to support white backgrounds. hue,sat,val=h,c,s return (hue,sat,val)
def array2DToImage( array2D, cmap, width=None, height=None, numComponents=4,texture=1, maxi=None, mini=None): #build the image: if width is None: width=array2D.shape[0] if height is None: height=array2D.shape[1] #texture sets the image dimensions to the smallest power of two if texture: dim1 = dim2=1 while dim1< width: dim1=dim1<<1 while dim2< height: dim2=dim2<<1 colors = Map(array2D.ravel(), cmap,mini=mini, maxi=maxi ) ###7/19: because these are Numeric arrays???!!!! ###7/19colors.shape = (width, height,3) colors.shape = (height, width,3) colors = colors*255 colors = colors.astype('B') tex2Dimage = Numeric.ones((dim2,dim1,numComponents), 'B') ###7/19: because these are Numeric arrays???!!!! ###7/19tex2Dimage = Numeric.ones((dim1,dim2,numComponents), 'B') ###7/19 tex2Dimage[:width,:height,:3] = colors tex2Dimage[:height,:width,:3] = colors return tex2Dimage
def doit(self, atom1, atom2, angle, mov_atoms, returnVal=0): mol = atom1.top if mov_atoms is None: mov_atoms = mol.subTree(atom1, atom2, mol.allAtoms) assert len(mov_atoms) mov_coords = Numeric.array(mov_atoms.coords) lenCoords = len(mov_coords) x = Numeric.array(atom1.coords) y = Numeric.array(atom2.coords) rot = (angle * 3.14159 / 180.) % (2 * Numeric.pi) matrix = rotax(x, y, rot) _ones = Numeric.ones(lenCoords, 'f') _ones.shape = (lenCoords, 1) mov_coords = Numeric.concatenate((mov_coords, _ones), 1) newcoords = Numeric.dot(mov_coords, matrix) nc = newcoords[:, :3].astype('f') for i in range(lenCoords): at = mov_atoms[i] at._coords[at.conformation] = nc[i].tolist() event = EditAtomsEvent('coords', mov_atoms) self.vf.dispatchEvent(event) #have to return nc for setTorsionGC if returnVal: return nc
def triangularPut(m1d, upper=1, lower=0): """Returns 2D masked array with elements of the given 1D array in the strictly upper (lower) triangle. Elements of the 1D array should be ordered according to the upper triangular part of the 2D matrix. The lower triangular part (if requested) equals to the transposed upper triangular part. If upper == lower == 1 a symetric matrix is returned. """ assert upper in [0,1] and lower in [0,1], "[0|1] expected for upper / lower" m1d = MA.asarray(m1d) assert MA.rank(m1d) == 1, "1D masked array expected" m2dShape0 = math.ceil(math.sqrt(2*m1d.shape[0])) assert m1d.shape[0] == m2dShape0*(m2dShape0-1)/2, "the length of m1d does not correspond to n(n-1)/2" if upper: if lower: mask = Numeric.fromfunction(lambda i,j: i==j, (m2dShape0, m2dShape0)) else: mask = Numeric.fromfunction(lambda i,j: i>=j, (m2dShape0, m2dShape0)) else: if lower: mask = Numeric.fromfunction(lambda i,j: i<=j, (m2dShape0, m2dShape0)) else: mask = Numeric.ones((m2dShape0, m2dShape0)) m2d = MA.ravel(MA.zeros((m2dShape0, m2dShape0), m1d.dtype.char)) condUpperTriang = Numeric.fromfunction(lambda i,j: i<j, (m2dShape0, m2dShape0)) putIndices = Numeric.compress(Numeric.ravel(condUpperTriang), Numeric.arange(0, m2dShape0**2, typecode=Numeric.Int)) MA.put(m2d, putIndices, m1d) m2d = MA.reshape(m2d, (m2dShape0, m2dShape0)) m2d = MA.where(condUpperTriang, m2d, MA.transpose(m2d)) return MA.array(m2d, mask=Numeric.logical_or(mask, MA.getmaskarray(m2d)))
def shuffledLists(self, n, lst, mask=None): """ shuffle order of a list n times, leaving masked(0) elements untouched @param n: number of times to shuffle the list @type n: int @param lst: list to shuffle @type lst: [any] @param mask: mask to be applied to lst @type mask: [1|0] @return: list of shuffeled lists @rtype: [[any]] """ if not mask: mask = N.ones(len(lst)) if type(lst) == list: lst = N.array(lst) pos = N.nonzero(mask) rand_pos = N.array([self.__shuffleList(pos) for i in range(n)]) result = [] for p in rand_pos: r = copy.copy(lst) N.put(r, p, N.take(lst, pos)) result += [r] return result
def test_booleans(): # numpy doesn't let you do boolean tests on arrays. Use a.all() instead a = N.ones(5) assert_raises(ValueError, lambda: not a) assert_true(a.all())
def shuffledLists( self, n, lst, mask=None ): """ shuffle order of a list n times, leaving masked(0) elements untouched @param n: number of times to shuffle the list @type n: int @param lst: list to shuffle @type lst: [any] @param mask: mask to be applied to lst @type mask: [1|0] @return: list of shuffeled lists @rtype: [[any]] """ if not mask: mask = N.ones( len(lst) ) if type( lst ) == list: lst = N.array( lst ) pos = N.nonzero( mask ) rand_pos = N.array( [ self.__shuffleList( pos ) for i in range(n) ] ) result = [] for p in rand_pos: r = copy.copy( lst ) N.put( r, p, N.take( lst, pos ) ) result += [r] return result
def castHmmDic( self, hmmDic, repete, hmmGap, key ): """ Blow up hmmDic to the number of repetes of the profile used. Correct scores for possible deletions in the search sequence. @param hmmDic: dictionary from L{getHmmProfile} @type hmmDic: dict @param repete: repete information from L{align} @type repete: int @param hmmGap: information about gaps from L{align} @type hmmGap: [int] @param key: name of scoring method to adjust for gaps and repetes @type key: str @return: dictionary with information about the profile @rtype: dict """ s = hmmDic[key] for i in range( repete ): mask = N.ones( len(s) ) N.put( mask, hmmGap[i], 0 ) if i == 0: score = N.compress( mask, s, 0 ) if i > 0: score = N.concatenate( ( N.compress( mask, s, 0 ), score ) ) hmmDic[key] = score return hmmDic
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 group( self, a_indices, maxPerCenter ): """ Group a bunch of integers (atom indices in PDBModel) so that each group has at most maxPerCenter items. @param a_indices: atom indices @type a_indices: [int] @param maxPerCenter: max entries per group @type maxPerCenter: int @return: list of lists of int @rtype: [[int],[int]..] """ ## how many groups are necessary? n_centers = len( a_indices ) / maxPerCenter if len( a_indices ) % maxPerCenter: n_centers += 1 ## how many items/atoms go into each group? nAtoms = N.ones(n_centers, N.Int) * int(len( a_indices ) / n_centers) i=0 while N.sum(nAtoms) != len( a_indices ): nAtoms[i] += 1 i += 1 ## distribute atom indices into groups result = [] pos = 0 for n in nAtoms: result += [ N.take( a_indices, N.arange(n) + pos) ] pos += n return result
def __init__(self, cntrl, uknots, vknots): self._bezier = None cntrl = numerix.asarray(cntrl, numerix.Float) (dim, nu, nv) = cntrl.shape if dim < 2 or dim > 4: raise NURBSError, 'Illegal control point format' elif dim < 4: self.cntrl = numerix.zeros((4, nu, nv), numerix.Float) self.cntrl[0:dim,:,:] = cntrl self.cntrl[-1,:,:] = numerix.ones((nu,nv), numerix.Float) else: self.cntrl = cntrl # Force the u knot sequence to be a vector in ascending order # and normalise between [0.0,1.0] uknots = numerix.sort(numerix.asarray(uknots, numerix.Float)) nku = uknots.shape[0] uknots = (uknots - uknots[0])/(uknots[-1] - uknots[0]) if uknots[0] == uknots[-1]: raise NURBSError, 'Illegal uknots sequence' self.uknots = uknots # Force the v knot sequence to be a vector in ascending order # and normalise between [0.0,1.0] vknots = -numerix.sort(-numerix.asarray(vknots, numerix.Float)) nkv = vknots.shape[0] vknots = (vknots - vknots[0])/(vknots[-1] - vknots[0]) if vknots[0] == vknots[-1]: raise NURBSError, 'Illegal vknots sequence' self.vknots = vknots # Spline Degree self.degree = [nku-nu-1, nkv-nv-1] if self.degree[0] < 0 or self.degree[1] < 0: raise NURBSError, 'NURBS order must be a positive integer'
def addDensity( self, radius=6, minasa=None, profName='density' ): """ Count the number of heavy atoms within the given radius. Values are only collected for atoms with |minasa| accessible surface area. @param minasa: relative exposed surface - 0 to 100% @type minasa: float @param radius: in Angstrom @type radius: float """ mHeavy = self.m.maskHeavy() xyz = N.compress( mHeavy, self.m.getXyz(), 0 ) if minasa and self.m.profile( 'relAS', 0 ) == 0: self.addASA() if minasa: mSurf = self.m.profile2mask( 'relAS', minasa ) else: mSurf = N.ones( self.m.lenAtoms() ) ## loop over all surface atoms surf_pos = N.nonzero( mSurf ) contacts = [] for i in surf_pos: dist = N.sum(( xyz - self.m.xyz[i])**2, 1) contacts += [ N.sum( N.less(dist, radius**2 )) -1] self.m.atoms.set( profName, contacts, mSurf, default=-1, comment='atom density radius %3.1fA' % radius, version= T.dateString() + ' ' + self.version() )
def Reset(self): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Reset members to default values""" self.pattern = Numeric.ones( (128,)) * 0xFF self.pattern = self.pattern.astype('B')
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 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 group(self, a_indices, maxPerCenter): """ Group a bunch of integers (atom indices in PDBModel) so that each group has at most maxPerCenter items. @param a_indices: atom indices @type a_indices: [int] @param maxPerCenter: max entries per group @type maxPerCenter: int @return: list of lists of int @rtype: [[int],[int]..] """ ## how many groups are necessary? n_centers = len(a_indices) / maxPerCenter if len(a_indices) % maxPerCenter: n_centers += 1 ## how many items/atoms go into each group? nAtoms = N.ones(n_centers, N.Int) * int(len(a_indices) / n_centers) i = 0 while N.sum(nAtoms) != len(a_indices): nAtoms[i] += 1 i += 1 ## distribute atom indices into groups result = [] pos = 0 for n in nAtoms: result += [N.take(a_indices, N.arange(n) + pos)] pos += n return result
def __init__(self, cntrl, uknots, vknots): self._bezier = None cntrl = numerix.asarray(cntrl, numerix.Float) (dim, nu, nv) = cntrl.shape if dim < 2 or dim > 4: raise NURBSError, 'Illegal control point format' elif dim < 4: self.cntrl = numerix.zeros((4, nu, nv), numerix.Float) self.cntrl[0:dim, :, :] = cntrl self.cntrl[-1, :, :] = numerix.ones((nu, nv), numerix.Float) else: self.cntrl = cntrl # Force the u knot sequence to be a vector in ascending order # and normalise between [0.0,1.0] uknots = numerix.sort(numerix.asarray(uknots, numerix.Float)) nku = uknots.shape[0] uknots = (uknots - uknots[0]) / (uknots[-1] - uknots[0]) if uknots[0] == uknots[-1]: raise NURBSError, 'Illegal uknots sequence' self.uknots = uknots # Force the v knot sequence to be a vector in ascending order # and normalise between [0.0,1.0] vknots = -numerix.sort(-numerix.asarray(vknots, numerix.Float)) nkv = vknots.shape[0] vknots = (vknots - vknots[0]) / (vknots[-1] - vknots[0]) if vknots[0] == vknots[-1]: raise NURBSError, 'Illegal vknots sequence' self.vknots = vknots # Spline Degree self.degree = [nku - nu - 1, nkv - nv - 1] if self.degree[0] < 0 or self.degree[1] < 0: raise NURBSError, 'NURBS order must be a positive integer'
def smooth(self): average = (Numeric.ones( (3,3) , 'f')/9.).astype('f') # average[1][1] = .0 print average self.redraw(filter=average) image = (self.imageAsArray()).astype('B') return image
def cluster( self, n_clusters, weight=1.13, converged=1e-11, aMask=None, force=0 ): """ Calculate new clusters. @param n_clusters: number of clusters @type n_clusters: int @param weight: fuzziness weigth @type weight: float (default: 1.13) @param converged: stop iteration if min dist changes less than converged (default: 1e-11) @type converged: float @param aMask: atom mask applied before clustering @type aMask: [1|0] @param force: re-calculate even if parameters haven't changed (default:0) @type force: 1|0 """ if aMask == None: aMask = N.ones( self.traj.getRef().lenAtoms() ) if self.fc == None or force or self.fcWeight != weight \ or self.n_clusters != n_clusters or N.any( self.aMask != aMask) \ or self.fcConverged != converged: self.n_clusters = n_clusters self.fcWeight = weight self.aMask = aMask self.fc = FuzzyCluster( self.__raveled(), self.n_clusters, self.fcWeight ) self.fcCenters = self.fc.go( self.fcConverged, 1000, nstep=10, verbose=self.verbose )
def SetMaterial(self, values, prop=1, tagModified=True): """Set the materials WARNING: when back face colors are set, two sided lighting has to be enabled we set RGB values for all properties except for shininess and opacity If an alpha value are specified they will be ignored Since IndexedGeomDSPL requires alpha values for all properties we set them automatically to 1.0 for all properties except for diffuse. The alpha channel of the diffuse component will be set later in fixOpacity which should be called after all properties of the material have been updated. """ if tagModified: self._modified = True if prop is None: prop = self.diff elif type(prop) is types.StringType: prop = getattr(self, prop) assert prop in (0,1,2,3,4,5) values = array( values, 'f' ) if prop < self.shini: assert len(values.shape)==2 and values.shape[1] in [3,4] alpha = ones( (values.shape[0], 1), 'f' ) values = concatenate( (values[:,:3], alpha), 1 ) else: if len(values.shape) != 1: values = array([values], 'f' ) self.prop[prop] = values
def scale(sxyz): ret = numerix.identity(4).astype(numerix.Float) s = numerix.ones(3, numerix.Float) s[0:len(sxyz)] = sxyz ret[0, 0] = s[0] ret[1, 1] = s[1] ret[2, 2] = s[2] return ret
def __init__(self, p00 = [-.5,-.5], p01 = [.5, -.5], p10 = [-.5, .5], p11 = [.5, .5]): coefs = numerix.zeros((4,2,2), numerix.Float) coefs[3,:,:] = numerix.ones((2,2), numerix.Float) coefs[0:len(p00),0,0] = p00 coefs[0:len(p01),0,1] = p01 coefs[0:len(p10),1,0] = p10 coefs[0:len(p11),1,1] = p11 Srf.__init__(self, coefs, [0.,0.,1.,1.], [0., 0., 1., 1.])
def del2mask(seq, *delpos): """convert list of (from, to) delete positions into a mask of 0 or 1""" mask = N.ones(len(seq)) for start, size in delpos: mask.put(range(start, start + size), 0) return mask
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 del2mask( seq, *delpos ): """convert list of (from, to) delete positions into a mask of 0 or 1""" mask = N.ones( len(seq) ) for start, size in delpos: mask.put( range( start, start+size), 0 ) return mask
def scale(sxyz): ret = numerix.identity(4).astype(numerix.Float) s = numerix.ones(3, numerix.Float) s[0:len(sxyz)] = sxyz ret[0,0] = s[0] ret[1,1] = s[1] ret[2,2] = s[2] return ret
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 runANOVA(self): """converts structured data [(name, [orngET1, orngET2, ...]),...] to a 3D masked array with the following axes: 0: examples, 1: variables, 2: ExampleTables; runs ANOVA computations and sets self.ps; """ if self.dataStructure and self.numExamples > 0: ma3d = MA.zeros((self.numExamples, self.numVariables, reduce(lambda a,b: a+len(b[1]), self.dataStructure, 0)), Numeric.Float) * MA.masked groupLens = [] etIdx = 0 for dsName, etList in self.dataStructure: for et in etList: ma3d[:,:,etIdx] = et.toNumpyMA("ac")[0] etIdx += 1 groupLens.append(len(etList)) # run ANOVA self.infoc.setText('ANOVA computation started...') self.progressBarInit() pbStep = 100./self.numExamples self.ps = Numeric.ones((3, self.numExamples), Numeric.Float) if self.anovaType == OWHypTest.St2AB or self.anovaType == OWHypTest.St2ABI: ps = self.anova2(ma3d, groupLens, addInteraction=self.anovaType==OWHypTest.St2ABI, repMeasuresOnA=False, callback=lambda: self.progressBarAdvance(pbStep)) for rIdx in range(ps.shape[0]): self.ps[rIdx] = ps[rIdx] elif self.anovaType == OWHypTest.St1B: self.ps[1] = self.anova1B(ma3d, groupLens, repMeasures=False, callback=lambda: self.progressBarAdvance(pbStep)) elif self.anovaType == OWHypTest.St1A: self.ps[0] = self.anova1A(ma3d, repMeasures=False, callback=lambda: self.progressBarAdvance(pbStep)) elif self.anovaType == OWHypTest.StSST: try: popMeanVal = float(self.popMean) except ValueError: print "Warning: cannot convert %s to float, using 0" % str(self.popMean) self.popMean = 0 popMeanVal = 0 self.ps[0] = self.ttest_ssmpl(ma3d, popMeanVal, callback=lambda: self.progressBarAdvance(pbStep)) elif self.anovaType == OWHypTest.StLPE: raise Exception, "NOT IMPLEMENTED" if self.numVariables == 2: self.ps[0] = self.lpeA(ma3d, callback=lambda: self.progressBarAdvance(pbStep)) elif self.numVariables == 1: self.ps[1] = self.lpeB(ma3d, groupLens, callback=lambda: self.progressBarAdvance(pbStep)) else: raise RuntimeError, "%s: expected 2 variables and 1 group, or 1 variable and 2 groups, got %s variables and %s groups" % (OWHypTest.StNames[self.anovaType], self.numVariables, len(groupLens)) elif self.anovaType == OWHypTest.StRST: if self.numVariables == 2 and len(groupLens) == 1: self.ps[0] = self.ttest_rsmplA(ma3d, callback=lambda: self.progressBarAdvance(pbStep)) elif self.numVariables == 1 and len(groupLens) == 2 and groupLens[0] == groupLens[1]: self.ps[1] = self.ttest_rsmplB(ma3d, groupLens, callback=lambda: self.progressBarAdvance(pbStep)) else: raise RuntimeError, "%s: expected 2 variables and 1 group, or 1 variable and 2 groups of equal length, got %s variables and %s groups of length %s" % (OWHypTest.StNames[self.anovaType], self.numVariables, len(groupLens), str(groupLens)) self.progressBarFinished()
def random_contacts(self, contMat, n, maskRec=None, maskLig=None): """ Create randomized surface contact matrix with same number of contacts and same shape as given contact matrix. @param contMat: template contact matrix @type contMat: matrix @param n: number of matrices to generate @type n: int @param maskRec: surface masks (or something similar) @type maskRec: [1|0] @param maskLig: surface masks (or something similar) @type maskLig: [1|0] @return: list of [n] random contact matricies @rtype: [matrix] """ a, b = N.shape(contMat) nContacts = N.sum(N.sum(contMat)) if not maskLig: r_size, l_size = N.shape(contMat) maskLig = N.ones(l_size) maskRec = N.ones(r_size) c_mask = N.ravel(N.outerproduct(maskRec, maskLig)) c_pos = N.nonzero(c_mask) # get array with surface positions from complex cont = N.take(N.ravel(contMat), c_pos) length = len(cont) result = [] for i in range(n): # create random array ranCont = mathUtils.randomMask(nContacts, length) # blow up to size of original matrix r = N.zeros(a * b) N.put(r, c_pos, ranCont) result += [N.reshape(r, (a, b))] return result
def anova2(self, ma3d, groupLens, addInteraction, repMeasuresOnA, callback): """Conducts two-way ANOVA on individual examples; returns a Numeric array of p-values in shape (2, numExamples) or (3, numExamples), depending whether we test for interaction; Note: levels of factors A and B that cause empty cells are removed prior to conducting ANOVA. """ groupLens = Numeric.asarray(groupLens) # arrays to store p-vals if addInteraction: ps = Numeric.ones((3, ma3d.shape[0]), Numeric.Float) else: ps = Numeric.ones((2, ma3d.shape[0]), Numeric.Float) # decide between non-repeated / repeated measures ANOVA for factor time if repMeasuresOnA: fAnova = Anova.AnovaRM12LR else: fAnova = Anova.Anova2wayLR # check for empty cells for all genes at once and remove them tInd2rem = [] ax2Ind = Numeric.concatenate(([0], Numeric.add.accumulate(groupLens))) for aIdx in range(ma3d.shape[1]): for rIdx in range(groupLens.shape[0]): if Numeric.add.reduce(MA.count(ma3d[:,aIdx,ax2Ind[rIdx]:ax2Ind[rIdx+1]],1)) == 0: tInd2rem.append(aIdx) break if len(tInd2rem) > 0: print "Warning: removing time indices %s for all genes" % (str(tInd2rem)) tInd2keep = range(ma3d.shape[1]) for aIdx in tInd2rem: tInd2keep.remove(aIdx) ma3d = ma3d.take(tInd2keep, 1) # for each gene... for eIdx in range(ma3d.shape[0]): # faster check for empty cells for that gene -> remove time indices with empty cells ma2d = ma3d[eIdx] cellCount = MA.zeros((ma2d.shape[0], groupLens.shape[0]), Numeric.Int) for g,(i0,i1) in enumerate(zip(ax2Ind[:-1], ax2Ind[1:])): cellCount[:,g] = MA.count(ma2d[:,i0:i1], 1) ma2dTakeInd = Numeric.logical_not(Numeric.add.reduce(Numeric.equal(cellCount,0),1)) # 1 where to take, 0 where not to take if Numeric.add.reduce(ma2dTakeInd) != ma2dTakeInd.shape[0]: print "Warning: removing time indices %s for gene %i" % (str(Numeric.compress(ma2dTakeInd == 0, Numeric.arange(ma2dTakeInd.shape[0]))), eIdx) ma2d = MA.compress(ma2dTakeInd, ma2d, 0) an = fAnova(ma2d, groupLens, addInteraction, allowReductA=True, allowReductB=True) ps[:,eIdx] = an.ps callback() return ps
def random_contacts( self, contMat, n, maskRec=None, maskLig=None ): """ Create randomized surface contact matrix with same number of contacts and same shape as given contact matrix. @param contMat: template contact matrix @type contMat: matrix @param n: number of matrices to generate @type n: int @param maskRec: surface masks (or something similar) @type maskRec: [1|0] @param maskLig: surface masks (or something similar) @type maskLig: [1|0] @return: list of [n] random contact matricies @rtype: [matrix] """ a,b = N.shape( contMat ) nContacts = N.sum( N.sum( contMat )) if not maskLig: r_size, l_size = N.shape( contMat ) maskLig = N.ones( l_size ) maskRec = N.ones( r_size ) c_mask = N.ravel( N.outerproduct( maskRec, maskLig ) ) c_pos = N.nonzero( c_mask ) # get array with surface positions from complex cont = N.take( N.ravel(contMat), c_pos ) length = len( cont ) result = [] for i in range( n ): # create random array ranCont = mathUtils.randomMask( nContacts,length ) # blow up to size of original matrix r = N.zeros(a*b) N.put( r, c_pos, ranCont) result += [ N.reshape( r, (a,b) ) ] return result
def Map(self, values, mini='not passed', maxi='not passed'): """Get colors corresponding to values in a colormap. if mini or maxi are provided, self.mini and self.maxi are not used and stay inchanged. if mini or maxi are not provided or set to None, self.mini and self.maxi are used instead. if mini or maxi are set to None, self.mini and self.maxi are ignored """ #print "Map", mini, maxi, self.mini, self.maxi, values values = Numeric.array(values) if len(values.shape)==2 and values.shape[1]==1: values.shape = ( values.shape[0], ) elif len(values.shape) > 1: raise ValueError('ERROR! values array has bad shape') ramp = Numeric.array(self.ramp) if len(ramp.shape) !=2 or ramp.shape[1] not in (3,4): raise ValueError('ERROR! colormap array has bad shape') if mini == 'not passed': mini = self.mini if maxi == 'not passed': maxi = self.maxi if mini is None: mini = min(values) else: # All the values < mini will be set to mini values = Numeric.maximum(values, mini) if maxi is None: maxi = max(values) else: values = Numeric.minimum(values, maxi) # mini and maxi are now set if mini >= maxi: txt = 'mini:%f must be < maxi:%f'%(mini, maxi) warnings.warn( txt ) valrange = maxi - mini if valrange < 0.0001: ind = Numeric.ones( values.shape ) else: colrange = ramp.shape[0] ind = (values - mini) * (colrange/float(valrange)) ind = ind.astype(viewerConst.IPRECISION) ind = Numeric.minimum(ind, colrange - 1) col = Numeric.take(self.ramp, ind ) self.lastMini = mini self.lastMaxi = maxi return col
def Map(self, values, mini='not passed', maxi='not passed'): """Get colors corresponding to values in a colormap. if mini or maxi are provided, self.mini and self.maxi are not used and stay inchanged. if mini or maxi are not provided or set to None, self.mini and self.maxi are used instead. if mini or maxi are set to None, self.mini and self.maxi are ignored """ #print "Map", mini, maxi, self.mini, self.maxi, values values = Numeric.array(values) if len(values.shape) == 2 and values.shape[1] == 1: values.shape = (values.shape[0], ) elif len(values.shape) > 1: raise ValueError('ERROR! values array has bad shape') ramp = Numeric.array(self.ramp) if len(ramp.shape) != 2 or ramp.shape[1] not in (3, 4): raise ValueError('ERROR! colormap array has bad shape') if mini == 'not passed': mini = self.mini if maxi == 'not passed': maxi = self.maxi if mini is None: mini = min(values) else: # All the values < mini will be set to mini values = Numeric.maximum(values, mini) if maxi is None: maxi = max(values) else: values = Numeric.minimum(values, maxi) # mini and maxi are now set if mini >= maxi: txt = 'mini:%f must be < maxi:%f' % (mini, maxi) warnings.warn(txt) valrange = maxi - mini if valrange < 0.0001: ind = Numeric.ones(values.shape) else: colrange = ramp.shape[0] ind = (values - mini) * (colrange / float(valrange)) ind = ind.astype(viewerConst.IPRECISION) ind = Numeric.minimum(ind, colrange - 1) col = Numeric.take(self.ramp, ind) self.lastMini = mini self.lastMaxi = maxi return col
def make_homogeneous_coord_rows(v): """Convert vertex (or row-wise vertices) into homogeneous coordinates.""" v = Numeric.array(v,typecode=Numeric.Float) # copy if len(v.shape) == 1: v = v[Numeric.NewAxis,:] # make a rank-2 array if v.shape[1] == 3: ws = Numeric.ones((v.shape[0],1),typecode=Numeric.Float) v = Numeric.concatenate( (v,ws), axis=1 ) return v
def sizedict(types): lst = [] for type in types: lst.append((Numeric.ones(1, type).itemsize, type)) lst.sort() result = {} for sz, typ in lst: if not result.has_key(sz): result[sz] = typ return result
def sizedict( types): lst = [] for type in types: lst.append((Numeric.ones(1, type).itemsize, type)) lst.sort() result = {} for sz, typ in lst: if not result.has_key( sz): result[ sz] = typ return result
def onDataInput(self, structuredData): """handles input data; sets self.dataStructure, self.numExamples, self.numVariables and self.ps; updates info, calls updateAnovaTypeBox(), runs ANOVA and sends out new data. """ self.dataStructure = structuredData self.numExamples = 0 self.numVariables = 0 self.ps = Numeric.ones((3,0), Numeric.Float) if structuredData: numFiles = reduce(lambda a,b: a+len(b[1]), structuredData, 0) lenSD = len(structuredData) self.infoa.setText("%d set%s, total of %d data file%s." % (lenSD, ["","s"][lenSD!=1], numFiles, ["","s"][numFiles!=1])) numExamplesList = [] numVariablesList = [] # construct a list of ExampleTable lengths and a list of number of variables for (name, etList) in structuredData: for et in etList: numExamplesList.append(len(et)) numVariablesList.append(len(et.domain.variables)) # test that all ExampleTables consist of equal number of examples and variables if len(numExamplesList) == 0 or Numeric.add.reduce(Numeric.equal(numExamplesList, numExamplesList[0])) != len(numExamplesList): self.dataStructure = None self.numExamples = -1 self.infob.setText("Error: data files contain unequal number of examples, aborting ANOVA computation.") self.infoc.setText('') elif len(numVariablesList) == 0 or Numeric.add.reduce(Numeric.equal(numVariablesList, numVariablesList[0])) != len(numVariablesList): self.dataStructure = None self.numVariables = -1 self.infob.setText("Error: data files contain unequal number of variables, aborting ANOVA computation.") self.infoc.setText('') else: self.numExamples = numExamplesList[0] self.numVariables = numVariablesList[0] self.infob.setText("%d variable%s, %d example%s in each file." % (self.numVariables, ["","s"][self.numVariables!=1], self.numExamples, ["","s"][self.numExamples!=1])) if self.numExamples > 0: self.infoc.setText('Press Commit button to start ANOVA computation.') else: self.infoc.setText('') self.boxAnovaType.setEnabled(1) self.boxSelection.setEnabled(1) self.btnCommit.setEnabled(True) else: self.infoa.setText('No data on input.') self.infob.setText('') self.infoc.setText('') # enable/disable anova type selection depending on the type of input data self.updateAnovaTypeBox() self.updateSelectorBox() if self.autoUpdateSelName: self.updateSelectorName() # run ANOVA if self.commitOnChange: self.runANOVA() self.senddata() self.updateSelectorInfos()
def _normalize(self, a, range_): """ Normalize an array s to be in the range 0 to 1.0. For an array of identical elements, returns an array of ones if the elements are greater than zero, and zeros if the elements are less than or equal to zero. """ if range_: # i.e. not False, not None (expecting a tuple) range_min = float(range_[0]) range_max = float(range_[1]) if range_min == range_max: if range_min > 0: resu = ones(a.shape) else: resu = zeros(a.shape) else: a_offset = a - range_min resu = a_offset / (range_max - range_min) return resu else: if range_ is None: if not hasattr(self, 'value_range'): self.value_range = (a.min(), a.max()) else: # If normalizing multiple matrices, take the largest values self.value_range = (min(self.value_range[0], a.min()), max(self.value_range[1], a.max())) return None # (indicate that array was not scaled) else: # i.e. range_ is False a_offset = a - a.min() max_a_offset = a_offset.max() if max_a_offset > 0: a = divide(a_offset, float(max_a_offset)) else: if min(a.ravel()) <= 0: a = zeros(a.shape, Float) else: a = ones(a.shape, Float) return a
def RedWhiteBlueARamp(size=256): ramp = Numeric.ones( (size, 4), 'f') mid = size/2 incr = 1./(mid-1) for i in xrange(mid): ramp[i][1] = i*incr ramp[i][2] = i*incr for i in xrange(mid): ramp[mid+i][0] = 1.-(i*incr) ramp[mid+i][1] = 1.-(i*incr) return ramp