Beispiel #1
0
def randomMask( nOnes, length ):
    """
    Create random array of given lenght and number of ones.

    @param nOnes: number of ones
    @type  nOnes: int
    @param length: lenght of array
    @type  length: int

    @return: array with ones and zeros
    @rtype: array( 1|0 )
    """
    r = N.zeros( length )
    pos = []

    ## add random ones
    for i in range( nOnes ):
        pos += [ int( random.random() * length ) ]      
    N.put( r, pos, 1 ) 

    ## if two ones ended up on the same position
    while nOnes != N.sum(r):
        pos = int( random.random() * length )
        N.put( r, pos, 1 )

    return r
Beispiel #2
0
    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
Beispiel #3
0
    def mergeProfiles(self, p0, p1, maxOverlap=3):
        """
        Merge profile p0 with profile p1, as long as they overlap in
        at most maxOverlap positions

        @param p0: profile
        @type  p0: [float]
        @param p1: profile
        @type  p1: [float]
        @param maxOverlap: maximal allowed overlap between profiles
        @type  maxOverlap: int
        
        @return: array
        @rtype: 
        """
        p0 = self.__list2array(p0)
        p1 = self.__list2array(p1)

        overlap = N.greater(N.greater(p0, 0) + N.greater(p1, 0), 1)

        if N.sum(overlap) <= maxOverlap:
            ## one of the two profiles will in most cases not belong to these
            ## positions. We can't decide which one is wrong, let's eliminate
            ## both values. Alternatively we could keep one, or the average, ..
            N.put(p1, N.nonzero(overlap), 0)
            N.put(p0, N.nonzero(overlap), 0)

            p0 = p0 + p1

        return p0
Beispiel #4
0
    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
Beispiel #5
0
    def mergeProfiles( self, p0, p1, maxOverlap=3 ):
        """
        Merge profile p0 with profile p1, as long as they overlap in
        at most maxOverlap positions

        @param p0: profile
        @type  p0: [float]
        @param p1: profile
        @type  p1: [float]
        @param maxOverlap: maximal allowed overlap between profiles
        @type  maxOverlap: int
        
        @return: array
        @rtype: 
        """
        p0 = self.__list2array( p0 )
        p1 = self.__list2array( p1 )

        overlap = N.greater( N.greater(p0,0) + N.greater(p1,0), 1 )

        if N.sum( overlap ) <= maxOverlap:
            ## one of the two profiles will in most cases not belong to these
            ## positions. We can't decide which one is wrong, let's eliminate
            ## both values. Alternatively we could keep one, or the average, ..
            N.put( p1, N.nonzero( overlap ), 0 )
            N.put( p0, N.nonzero( overlap ), 0 )

            p0 = p0 + p1

        return p0
Beispiel #6
0
    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
Beispiel #7
0
    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
Beispiel #8
0
def randomMask(nOnes, length):
    """
    Create random array of given lenght and number of ones.

    @param nOnes: number of ones
    @type  nOnes: int
    @param length: lenght of array
    @type  length: int

    @return: array with ones and zeros
    @rtype: array( 1|0 )
    """
    r = N.zeros(length)
    pos = []

    ## add random ones
    for i in range(nOnes):
        pos += [int(random.random() * length)]
    N.put(r, pos, 1)

    ## if two ones ended up on the same position
    while nOnes != N.sum(r):
        pos = int(random.random() * length)
        N.put(r, pos, 1)

    return r
Beispiel #9
0
    def blockFit(self, ref=None, mask=None):
        """
        RMSD-fit the average of each member trajectory (i.e. the trajectory
        en block) onto the overall average (default) or a given structure.
        
        @param ref: reference structure (default: average structure)
        @type  ref: PDBModel
        @param mask: atoms to consider (default: None, all heavy)
        @type  mask: [1|0] OR None
        """
        ref = ref or self.avgModel()

        for m in range(self.n_members):

            indices = self.memberIndices(m)

            ## get a copy of this member's Trajectory
            traj = self.takeFrames(indices)
            m_avg = traj.avgModel()

            r, t = m_avg.transformation(ref, mask)
            traj.transform(r, t)

            ## replace original frames of this member
            N.put(self.frames, indices, traj.frames)
Beispiel #10
0
    def blockFit( self, ref=None, mask=None ):
        """
        RMSD-fit the average of each member trajectory (i.e. the trajectory
        en block) onto the overall average (default) or a given structure.
        
        @param ref: reference structure (default: average structure)
        @type  ref: PDBModel
        @param mask: atoms to consider (default: None, all heavy)
        @type  mask: [1|0] OR None
        """
        ref = ref or self.avgModel()

        for m in range( self.n_members ):

            indices = self.memberIndices( m )

            ## get a copy of this member's Trajectory
            traj = self.takeFrames( indices )
            m_avg = traj.avgModel()

            r, t = m_avg.transformation( ref, mask )
            traj.transform( r, t )

            ## replace original frames of this member
            N.put( self.frames, indices, traj.frames )
Beispiel #11
0
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)
Beispiel #12
0
    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
Beispiel #13
0
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 )
Beispiel #14
0
    def __unmaskedMatrix( self, contacts, rec_mask, lig_mask ):
        """
        Map contacts between selected rec and lig atoms back to all atoms
        matrix.
        
        @param contacts: contact matrix, array sum_rec_mask x sum_lig_mask
        @type  contacts: array
        @param rec_mask: atom mask
        @type  rec_mask: [1|0]
        @param lig_mask: atom mask
        @type  lig_mask: [1|0]

        @return: atom contact matrix, array N_atoms_rec x N_atoms_lig
        @rtype: array
        """
        l_rec = len( self.rec_model )
        l_lig = len( self.lig_model )

        ## map contacts back to all atoms matrix
        r = N.zeros( l_rec * l_lig )
        rMask = N.ravel( N.outerproduct( rec_mask, lig_mask ) )

        ## (Optimization: nonzero is time consuming step)
        N.put( r, N.nonzero( rMask ), N.ravel( contacts ) )

        return N.resize( r, (l_rec, l_lig))
Beispiel #15
0
def indices2condition(indices, length):
    """Input: indices=[0,3]; output: condition=[1,0,0,1]
    """
    indices = Numeric.asarray(indices)
    assert len(indices.shape) == 1
    assert length >= indices.shape[0]
    c = Numeric.zeros((length,), Numeric.Int)
    Numeric.put(c, indices, 1)
    return c
Beispiel #16
0
def rankData(n, inverse=False):
    """Returns ranks of 1D Numeric array in range 1...shape[0].
    """
    n = Numeric.asarray(n)
    assert Numeric.rank(n) == 1
    r = Numeric.zeros(n.shape[0], Numeric.Float)
    Numeric.put(r, Numeric.argsort(n), Numeric.arange(n.shape[0]))
    if inverse:
        return -1*r+n.shape[0]
    else:
        return r+1
    def patchAround(self, center, nAtoms):
        """
        patchAround( float_center, int_nAtoms ) -> mask for self.model
        Create single patch of nAtoms atoms that are closest to center.
        """
        dist = self.__distances(center)
        order = N.argsort(dist)

        r = N.zeros(len(self.model), 'i')
        N.put(r, order[:nAtoms], 1)

        return self.centerPatch(r)
Beispiel #18
0
 def __inverseIndices(self, model, i_atoms):
     """
     @param model: model
     @type  model: PDBMode
     @param i_atoms: atom index
     @type  i_atoms: [int]
 
     @return: remaining atom indices of m that are NOT in i_atoms
     @rtype: [int]
     """
     mask = N.zeros(len(model), N.Int)
     N.put(mask, i_atoms, 1)
     return N.nonzero(N.logical_not(mask))
Beispiel #19
0
 def __inverseIndices( self, model, i_atoms ):
     """
     @param model: model
     @type  model: PDBMode
     @param i_atoms: atom index
     @type  i_atoms: [int]
 
     @return: remaining atom indices of m that are NOT in i_atoms
     @rtype: [int]
     """
     mask = N.zeros( len( model ),N.Int )
     N.put( mask, i_atoms, 1 )
     return N.nonzero( N.logical_not( mask ) )
Beispiel #20
0
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) )
Beispiel #21
0
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 centerPatch(self, patch_mask):
        """
        patch_mask - [ 1|0 ], mask of non-centered patch
        -> [ 1|0 ], mask of patch around geometric center of first patch
        """
        c = self.model.center(patch_mask)
        dist = self.__distances(c)

        n_atoms = len(N.nonzero(patch_mask))
        i_dist = N.argsort(dist)[:n_atoms]

        result = N.zeros(len(patch_mask))
        N.put(result, i_dist, 1)

        return result
Beispiel #23
0
    def toarray( self ):
        """
        Reconstruct dense array::
          L.toarray() -> Numeric.array, normal dense array

        @return: normal dense array
        @rtype: array
        """
        if self.default() is 0:
            a = N.zeros( ( self.shape ), self.typecode() )
        else:
            a = N.ones( (self.shape ), self.typecode() ) * self.default()

        N.put( a, self.nondefault(), self.nondefault_values() )

        return a
Beispiel #24
0
    def toarray(self):
        """
        Reconstruct dense array::
          L.toarray() -> Numeric.array, normal dense array

        @return: normal dense array
        @rtype: array
        """
        if self.default() is 0:
            a = N.zeros((self.shape), self.typecode())
        else:
            a = N.ones((self.shape), self.typecode()) * self.default()

        N.put(a, self.nondefault(), self.nondefault_values())

        return a
Beispiel #25
0
    def draw(self):
        # XXX This method is not speed-optimized. I just wrote it to
        # get the job done. (Nonetheless, it seems faster than the C
        # version commented out above.)

        p = self.parameters # shorthand

        now_sec = VisionEgg.time_func()
        if self.start_times_sec is not None:
            # compute extinct dots and generate new positions
            replace_indices = Numeric.nonzero( Numeric.greater( now_sec - self.start_times_sec, p.dot_lifespan_sec) )
            Numeric.put( self.start_times_sec, replace_indices, now_sec )

            new_centers = np.random.standard_normal((3,len(replace_indices)))
            for i in range(3):
                Numeric.put( self.centers[i,:], replace_indices, new_centers[i,:] )
        else:
            # initialize dot extinction values to random (uniform) distribution
            self.start_times_sec = RandomArray.uniform( now_sec - p.dot_lifespan_sec, now_sec,
                                                        (self.constant_parameters.num_dots,))

        time_delta_sec = now_sec - self.last_time_sec
        self.last_time_sec = now_sec # reset for next loop
        self.centers = self.centers + np.array(p.signal_vec)[:,np.newaxis]*time_delta_sec

        xyz = self.centers*p.start_position_variance + np.array(p.start_position_mean)[:,np.newaxis]
        xs = xyz[0,:]
        ys = xyz[1,:]
        zs = xyz[2,:]

        if p.on:
            gl.glEnable( gl.GL_POINT_SMOOTH )
            # allow max_alpha value to control blending
            gl.glEnable( gl.GL_BLEND )
            gl.glBlendFunc( gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA )

            gl.glPointSize(p.dot_size)

            # Clear the modeview matrix
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glPushMatrix()

            gl.glDisable(gl.GL_TEXTURE_2D)

            draw_dots(xs,ys,zs,self.colors)
            gl.glDisable( gl.GL_POINT_SMOOTH ) # turn off
            gl.glPopMatrix()
Beispiel #26
0
    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
Beispiel #27
0
    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
Beispiel #28
0
    def memberMask( self, member ):
        """
        Get mask for all frames belonging to a given ensemble member.
        
        @param member: member index starting with 0
        @type  member: int
        
        @return: member mask, N.array( N_frames x 1) of 1||0
        @rtype: [1|0]
        """
        result = N.zeros( self.lenFrames() )

        if isinstance( member , types.IntType):
            N.put( result, self.memberIndices( member ), 1 )

        if type( member ) == types.ListType:
            for m in member:
                N.put( result, self.memberIndices( m ), 1 )

        return result
Beispiel #29
0
    def memberMask(self, member):
        """
        Get mask for all frames belonging to a given ensemble member.
        
        @param member: member index starting with 0
        @type  member: int
        
        @return: member mask, N.array( N_frames x 1) of 1||0
        @rtype: [1|0]
        """
        result = N.zeros(self.lenFrames())

        if isinstance(member, types.IntType):
            N.put(result, self.memberIndices(member), 1)

        if type(member) == types.ListType:
            for m in member:
                N.put(result, self.memberIndices(m), 1)

        return result
Beispiel #30
0
def compareSequences( seqAA_1, seqAA_2 ):
    """
    """
    seqAA_1 = list( seqAA_1 )
    seqAA_2 = list( seqAA_2 )
    seqNr_1 = range( len( seqAA_1 ) )
    seqNr_2 = range( len( seqAA_2 ) )

    # get mask
    mask_1 = N.zeros( len( seqNr_1 ) )
    mask_2 = N.zeros( len( seqNr_2 ) )

    # compare sequences
    seqDiff = getOpCodes( seqAA_1, seqAA_2)

    # get delete lists
    del_1, del_2 =  getSkipLists( seqDiff )
    
    del_1 = [ expandRepeats( seqAA_1, *pos ) for pos in del_1 ]
    del_2 = [ expandRepeats( seqAA_2, *pos ) for pos in del_2 ]
    
    mask1 = del2mask( seqAA_1, *del_1 )
    mask2 = del2mask( seqAA_2, *del_2 )
 
    seqAA_1 = N.compress( mask1, seqAA_1 ).tolist()
    seqNr_1 = N.compress( mask1, seqNr_1 ).tolist()
    seqAA_2 = N.compress( mask2, seqAA_2 ).tolist()
    seqNr_2 = N.compress( mask2, seqNr_2 ).tolist()
    
    # get equal parts
    seqDiff = getOpCodes( seqAA_1, seqAA_2 )
    equal_1, equal_2 = getEqualLists( seqDiff ) 
    seqAA_1, seqNr_1 = getEqual( seqAA_1, seqNr_1, equal_1)
    seqAA_2, seqNr_2 = getEqual( seqAA_2, seqNr_2, equal_2 )

    N.put( mask_1, seqNr_1 , 1 )
    N.put( mask_2, seqNr_2 , 1 )

    return mask_1, mask_2
Beispiel #31
0
def compareSequences(seqAA_1, seqAA_2):
    """
    """
    seqAA_1 = list(seqAA_1)
    seqAA_2 = list(seqAA_2)
    seqNr_1 = range(len(seqAA_1))
    seqNr_2 = range(len(seqAA_2))

    # get mask
    mask_1 = N.zeros(len(seqNr_1))
    mask_2 = N.zeros(len(seqNr_2))

    # compare sequences
    seqDiff = getOpCodes(seqAA_1, seqAA_2)

    # get delete lists
    del_1, del_2 = getSkipLists(seqDiff)

    del_1 = [expandRepeats(seqAA_1, *pos) for pos in del_1]
    del_2 = [expandRepeats(seqAA_2, *pos) for pos in del_2]

    mask1 = del2mask(seqAA_1, *del_1)
    mask2 = del2mask(seqAA_2, *del_2)

    seqAA_1 = N.compress(mask1, seqAA_1).tolist()
    seqNr_1 = N.compress(mask1, seqNr_1).tolist()
    seqAA_2 = N.compress(mask2, seqAA_2).tolist()
    seqNr_2 = N.compress(mask2, seqNr_2).tolist()

    # get equal parts
    seqDiff = getOpCodes(seqAA_1, seqAA_2)
    equal_1, equal_2 = getEqualLists(seqDiff)
    seqAA_1, seqNr_1 = getEqual(seqAA_1, seqNr_1, equal_1)
    seqAA_2, seqNr_2 = getEqual(seqAA_2, seqNr_2, equal_2)

    N.put(mask_1, seqNr_1, 1)
    N.put(mask_2, seqNr_2, 1)

    return mask_1, mask_2
Beispiel #32
0
    def memberMap(self, traj):
        """
        Tell which traj frame belongs to which member trajectory.

        @param traj: Trajectory
        @type  traj: Trajectory

        @return: member index of each frame OR None if traj is
                 not a EnsembleTraj
        @rtype: [ int ] OR None
        """
        if not isinstance( traj, EnsembleTraj ):
            return None

        r = N.zeros( len(traj), N.Int )

        for i in range( traj.n_members ):

            mi = traj.memberIndices( i )
            N.put( r, mi, i )

        return r.tolist()
Beispiel #33
0
    def go(self, model_list = None, reference = None):
        """
        Run benchmarking.

        @param model_list: list of models
                           (default: None S{->} outFolder/L{F_PDBModels})
        @type  model_list: ModelList
        @param reference: reference model
                        (default: None S{->} outFolder/L{F_INPUT_REFERENCE})
        @type  reference: PDBModel
        """
        model_list = model_list or self.outFolder + self.F_PDBModels
        reference = reference or self.outFolder + self.F_INPUT_REFERENCE

        pdb_list = T.load('%s'%model_list)
        reference = PDBModel(reference)

        # check with python 2.4
        iref, imodel = reference.compareAtoms(pdb_list[0])

        mask_casting = N.zeros(len(pdb_list[0]))
        N.put(mask_casting, imodel, 1)

        reference = reference.take(iref)
        #reference_mask_CA = reference_rmsd.maskCA()

        atom_mask = N.zeros(len(pdb_list[0]))
        N.put(atom_mask,imodel,1)

        rmask = pdb_list[0].profile2mask("n_templates", 1,1000)
        amask = pdb_list[0].res2atomMask(rmask)

        mask_final_ref = N.compress(mask_casting, amask)
        mask_final = mask_casting * amask

        reference = reference.compress(mask_final_ref)

        for i in range(len(pdb_list)):

            #self.cad(reference, pdb_list[i])

            pdb_list[i], pdb_wo_if = self.output_fittedStructures(\
                pdb_list[i], reference, i, mask_final)

            fitted_model_if = pdb_list[i].compress(mask_final)
            fitted_model_wo_if = pdb_wo_if.compress(mask_final)

            coord1 = reference.getXyz()
            coord2 = fitted_model_if.getXyz()

            aprofile = self.rmsd_res(coord1,coord2)

            self.calc_rmsd(fitted_model_if, fitted_model_wo_if,
                           reference, pdb_list[i])

            pdb_list[i].atoms.set('rmsd2ref_if', aprofile,
                                  mask=mask_final, default = -1,
                                  comment="rmsd to known reference structure")

        self.output_rmsd_aa(pdb_list)
        self.output_rmsd_ca(pdb_list)
        self.output_rmsd_res(pdb_list)

        self.write_PDBModels(pdb_list)
Beispiel #34
0
    def go(self, model_list=None, reference=None):
        """
        Run benchmarking.

        @param model_list: list of models
                           (default: None S{->} outFolder/L{F_PDBModels})
        @type  model_list: ModelList
        @param reference: reference model
                        (default: None S{->} outFolder/L{F_INPUT_REFERENCE})
        @type  reference: PDBModel
        """
        model_list = model_list or self.outFolder + self.F_PDBModels
        reference = reference or self.outFolder + self.F_INPUT_REFERENCE

        pdb_list = T.load('%s' % model_list)
        reference = PDBModel(reference)

        # check with python 2.4
        iref, imodel = reference.compareAtoms(pdb_list[0])

        mask_casting = N.zeros(len(pdb_list[0]))
        N.put(mask_casting, imodel, 1)

        reference = reference.take(iref)
        #reference_mask_CA = reference_rmsd.maskCA()

        atom_mask = N.zeros(len(pdb_list[0]))
        N.put(atom_mask, imodel, 1)

        rmask = pdb_list[0].profile2mask("n_templates", 1, 1000)
        amask = pdb_list[0].res2atomMask(rmask)

        mask_final_ref = N.compress(mask_casting, amask)
        mask_final = mask_casting * amask

        reference = reference.compress(mask_final_ref)

        for i in range(len(pdb_list)):

            #self.cad(reference, pdb_list[i])

            pdb_list[i], pdb_wo_if = self.output_fittedStructures(\
                pdb_list[i], reference, i, mask_final)

            fitted_model_if = pdb_list[i].compress(mask_final)
            fitted_model_wo_if = pdb_wo_if.compress(mask_final)

            coord1 = reference.getXyz()
            coord2 = fitted_model_if.getXyz()

            aprofile = self.rmsd_res(coord1, coord2)

            self.calc_rmsd(fitted_model_if, fitted_model_wo_if, reference,
                           pdb_list[i])

            pdb_list[i].atoms.set('rmsd2ref_if',
                                  aprofile,
                                  mask=mask_final,
                                  default=-1,
                                  comment="rmsd to known reference structure")

        self.output_rmsd_aa(pdb_list)
        self.output_rmsd_ca(pdb_list)
        self.output_rmsd_res(pdb_list)

        self.write_PDBModels(pdb_list)
Beispiel #35
0
    def draw(self):
        # XXX This method is not speed-optimized. I just wrote it to
        # get the job done. (Nonetheless, it seems faster than the C
        # version commented out above.)

        p = self.parameters  # shorthand
        if p.center is not None:
            if not hasattr(VisionEgg.config, "_GAVE_CENTER_DEPRECATION"):
                logger = logging.getLogger('VisionEgg.Dots')
                logger.warning("Specifying DotArea2D by deprecated "
                               "'center' parameter deprecated.  Use "
                               "'position' parameter instead.  (Allows "
                               "use of 'anchor' parameter to set to "
                               "other values.)")
                VisionEgg.config._GAVE_CENTER_DEPRECATION = 1
            p.anchor = 'center'
            p.position = p.center[0], p.center[
                1]  # copy values (don't copy ref to tuple)
        if p.on:
            # calculate center
            center = VisionEgg._get_center(p.position, p.anchor, p.size)

            if p.anti_aliasing:
                if len(p.color) == 4 and not self._gave_alpha_warning:
                    if p.color[3] != 1.0:
                        logger = logging.getLogger('VisionEgg.Dots')
                        logger.warning("The parameter anti_aliasing is "
                                       "set to true in the DotArea2D "
                                       "stimulus class, but the color "
                                       "parameter specifies an alpha "
                                       "value other than 1.0.  To "
                                       "acheive the best anti-aliasing, "
                                       "ensure that the alpha value for "
                                       "the color parameter is 1.0.")
                        self._gave_alpha_warning = 1
                gl.glEnable(gl.GL_POINT_SMOOTH)
                # allow max_alpha value to control blending
                gl.glEnable(gl.GL_BLEND)
                gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
            else:
                gl.glDisable(gl.GL_BLEND)

            now_sec = VisionEgg.time_func()
            if self.start_times_sec is not None:
                # compute extinct dots and generate new positions
                replace_indices = Numeric.nonzero(
                    Numeric.greater(now_sec - self.start_times_sec,
                                    p.dot_lifespan_sec))
                Numeric.put(self.start_times_sec, replace_indices, now_sec)

                new_x_positions = RandomArray.uniform(0.0, 1.0,
                                                      (len(replace_indices), ))
                Numeric.put(self.x_positions, replace_indices, new_x_positions)

                new_y_positions = RandomArray.uniform(0.0, 1.0,
                                                      (len(replace_indices), ))
                Numeric.put(self.y_positions, replace_indices, new_y_positions)

                new_random_directions_radians = RandomArray.uniform(
                    0.0, 2 * math.pi, (len(replace_indices), ))
                Numeric.put(self.random_directions_radians, replace_indices,
                            new_random_directions_radians)
            else:
                # initialize dot extinction values to random (uniform) distribution
                self.start_times_sec = RandomArray.uniform(
                    now_sec - p.dot_lifespan_sec, now_sec,
                    (self.constant_parameters.num_dots, ))

            signal_num_dots = int(
                round(p.signal_fraction * self.constant_parameters.num_dots))
            time_delta_sec = now_sec - self.last_time_sec
            self.last_time_sec = now_sec  # reset for next loop
            x_increment_normalized = math.cos(
                p.signal_direction_deg / 180.0 * math.pi
            ) * p.velocity_pixels_per_sec / p.size[0] * time_delta_sec
            y_increment_normalized = -math.sin(
                p.signal_direction_deg / 180.0 * math.pi
            ) * p.velocity_pixels_per_sec / p.size[1] * time_delta_sec
            self.x_positions[:signal_num_dots] += x_increment_normalized
            self.y_positions[:signal_num_dots] += y_increment_normalized

            num_random_dots = self.constant_parameters.num_dots - signal_num_dots
            random_x_increment_normalized = Numeric.cos(
                self.random_directions_radians[signal_num_dots:]
            ) * p.velocity_pixels_per_sec / p.size[0] * time_delta_sec
            random_y_increment_normalized = -Numeric.sin(
                self.random_directions_radians[signal_num_dots:]
            ) * p.velocity_pixels_per_sec / p.size[1] * time_delta_sec
            self.x_positions[signal_num_dots:] += random_x_increment_normalized
            self.y_positions[signal_num_dots:] += random_y_increment_normalized

            self.x_positions = Numeric.fmod(self.x_positions, 1.0)  # wrap
            self.y_positions = Numeric.fmod(self.y_positions, 1.0)

            self.x_positions = Numeric.fmod(self.x_positions + 1,
                                            1.0)  # wrap again for values < 1
            self.y_positions = Numeric.fmod(self.y_positions + 1, 1.0)

            xs = (self.x_positions - 0.5) * p.size[0] + center[0]
            ys = (self.y_positions - 0.5) * p.size[1] + center[1]

            if len(p.color) == 3:
                gl.glColor3f(*p.color)
            elif len(p.color) == 4:
                gl.glColor4f(*p.color)
            gl.glPointSize(p.dot_size)

            # Clear the modeview matrix
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glPushMatrix()

            gl.glDisable(gl.GL_TEXTURE_2D)

            if p.depth is None:
                depth = 0.0
            else:
                gl.glEnable(gl.GL_DEPTH_TEST)
                depth = p.depth
            zs = (depth, ) * len(xs)  # make N tuple with repeat value of depth
            draw_dots(xs, ys, zs)
            if p.anti_aliasing:
                gl.glDisable(gl.GL_POINT_SMOOTH)  # turn off
            gl.glPopMatrix()
Beispiel #36
0
    def draw(self):
        # XXX This method is not speed-optimized. I just wrote it to
        # get the job done. (Nonetheless, it seems faster than the C
        # version commented out above.)

        p = self.parameters # shorthand
        if p.center is not None:
            if not hasattr(VisionEgg.config,"_GAVE_CENTER_DEPRECATION"):
                logger = logging.getLogger('VisionEgg.Dots')
                logger.warning("Specifying DotArea2D by deprecated "
                               "'center' parameter deprecated.  Use "
                               "'position' parameter instead.  (Allows "
                               "use of 'anchor' parameter to set to "
                               "other values.)")
                VisionEgg.config._GAVE_CENTER_DEPRECATION = 1
            p.anchor = 'center'
            p.position = p.center[0], p.center[1] # copy values (don't copy ref to tuple)
        if p.on:
            # calculate center
            center = VisionEgg._get_center(p.position,p.anchor,p.size)

            if p.anti_aliasing:
                if len(p.color) == 4 and not self._gave_alpha_warning:
                    if p.color[3] != 1.0:
                        logger = logging.getLogger('VisionEgg.Dots')
                        logger.warning("The parameter anti_aliasing is "
                                       "set to true in the DotArea2D "
                                       "stimulus class, but the color "
                                       "parameter specifies an alpha "
                                       "value other than 1.0.  To "
                                       "acheive the best anti-aliasing, "
                                       "ensure that the alpha value for "
                                       "the color parameter is 1.0.")
                        self._gave_alpha_warning = 1
                gl.glEnable( gl.GL_POINT_SMOOTH )
                # allow max_alpha value to control blending
                gl.glEnable( gl.GL_BLEND )
                gl.glBlendFunc( gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA )
            else:
                gl.glDisable( gl.GL_BLEND )

            now_sec = VisionEgg.time_func()
            if self.start_times_sec is not None:
                # compute extinct dots and generate new positions
                replace_indices = Numeric.nonzero( Numeric.greater( now_sec - self.start_times_sec, p.dot_lifespan_sec) )
                Numeric.put( self.start_times_sec, replace_indices, now_sec )

                new_x_positions = RandomArray.uniform(0.0,1.0,
                                                      (len(replace_indices),))
                Numeric.put( self.x_positions, replace_indices, new_x_positions )

                new_y_positions = RandomArray.uniform(0.0,1.0,
                                                      (len(replace_indices),))
                Numeric.put( self.y_positions, replace_indices, new_y_positions )

                new_random_directions_radians = RandomArray.uniform(0.0,2*math.pi,
                                                                    (len(replace_indices),))
                Numeric.put( self.random_directions_radians, replace_indices, new_random_directions_radians )
            else:
                # initialize dot extinction values to random (uniform) distribution
                self.start_times_sec = RandomArray.uniform( now_sec - p.dot_lifespan_sec, now_sec,
                                                            (self.constant_parameters.num_dots,))

            signal_num_dots = int(round(p.signal_fraction * self.constant_parameters.num_dots))
            time_delta_sec = now_sec - self.last_time_sec
            self.last_time_sec = now_sec # reset for next loop
            x_increment_normalized =  math.cos(p.signal_direction_deg/180.0*math.pi) * p.velocity_pixels_per_sec / p.size[0] * time_delta_sec
            y_increment_normalized = -math.sin(p.signal_direction_deg/180.0*math.pi) * p.velocity_pixels_per_sec / p.size[1] * time_delta_sec
            self.x_positions[:signal_num_dots] += x_increment_normalized
            self.y_positions[:signal_num_dots] += y_increment_normalized

            num_random_dots = self.constant_parameters.num_dots - signal_num_dots
            random_x_increment_normalized =  Numeric.cos(self.random_directions_radians[signal_num_dots:]) * p.velocity_pixels_per_sec / p.size[0] * time_delta_sec
            random_y_increment_normalized = -Numeric.sin(self.random_directions_radians[signal_num_dots:]) * p.velocity_pixels_per_sec / p.size[1] * time_delta_sec
            self.x_positions[signal_num_dots:] += random_x_increment_normalized
            self.y_positions[signal_num_dots:] += random_y_increment_normalized

            self.x_positions = Numeric.fmod( self.x_positions, 1.0 ) # wrap
            self.y_positions = Numeric.fmod( self.y_positions, 1.0 )

            self.x_positions = Numeric.fmod( self.x_positions+1, 1.0 ) # wrap again for values < 1
            self.y_positions = Numeric.fmod( self.y_positions+1, 1.0 )

            xs = (self.x_positions - 0.5) * p.size[0] + center[0]
            ys = (self.y_positions - 0.5) * p.size[1] + center[1]

            if len(p.color)==3:
                gl.glColor3f(*p.color)
            elif len(p.color)==4:
                gl.glColor4f(*p.color)
            gl.glPointSize(p.dot_size)

            # Clear the modeview matrix
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glPushMatrix()

            gl.glDisable(gl.GL_TEXTURE_2D)

            if p.depth is None:
                depth = 0.0
            else:
                gl.glEnable(gl.GL_DEPTH_TEST)
                depth = p.depth
            zs = (depth,)*len(xs) # make N tuple with repeat value of depth
            draw_dots(xs,ys,zs)
            if p.anti_aliasing:
                gl.glDisable( gl.GL_POINT_SMOOTH ) # turn off
            gl.glPopMatrix()