Example #1
0
def arrayEqual(a, b):
    """
    Compare 2 arrays or lists of numbers for equality.

    @param a: first array (multi-dimensional is supported)
    @type  a: array / list
    @param b: second array (multi-dimensional is supported)
    @type  b: array / list

    @return: 1 if array/list a equals array/list b
    @rtype: 1|0
    """
    if a is None or b is None:
        return a is b

    if len(a) != len(b):
        return 0

    if type(a) is list: a = N.array(a)
    if type(b) is list: b = N.array(b)

    a = N.ravel(a)
    b = N.ravel(b)

    return N.sum(a == b) == len(a)
Example #2
0
    def avgRmsd( self, cluster, aMask=None, threshold=0. ):
        """
        Claculate the average pairwise rmsd (in Angstrom) for members
        of a cluter.

        @param cluster: cluster number
        @type  cluster: int       
        @param aMask: atom mask applied before calculation
        @type  aMask: [1|0]
        @param threshold: float 0-1, minimal cluster membership,
                          see L{memberTraj()}
        @type  threshold: float

        @return: average rmsd and the standard deviation 
        @rtype: float, float   
        """
        try:
            rms = self.memberTraj(cluster,threshold).pairwiseRmsd( aMask )
            rms = aboveDiagonal( rms )
        except:
            rms = []

        if len(N.ravel(rms)) == 1:
            ## was: return N.average(rms)[0], 0.0
            return N.average(rms), 0.0
        if len(N.ravel(rms)) == 0:
            return 0.0, 0.0

        return N.average( rms ), SD( rms )
Example #3
0
    def calcReducedContacts( self, soln, c ):
        """
        Get contact matrices and/or fnarc from reduced-atom models.

        @param soln: solution number
        @type  soln: int
        @param c: Complex
        @type  c: Complex       
        """
        if not (self.reduced_recs and self.reduced_ligs):
            return

        if not self.requested(c,'c_ratom_10','fnarc_10'):
            return

        try:
            ## create Complex with same orientation but reduced coordinates
            red_rec = self.reduced_recs[ c.rec_model.source ]
            red_lig = self.reduced_ligs[ c.lig_model.source ]
            red_com = Complex( red_rec, red_lig, c.ligandMatrix )

            contacts = red_com.atomContacts( 10.0, cache=1 )

            if self.requested(c, 'c_ratom_10'):
                c['c_ratom_10'] = MU.packBinaryMatrix(contacts)

            if self.c_ref_ratom_10 is not None:
                ref = N.ravel( self.c_ref_ratom_10 )
                c['fnarc_10'] = N.sum( N.ravel(contacts) * ref )\
                 / float( N.sum(ref))

        except:
            self.reportError('reduced contacts error', soln)
Example #4
0
    def avgRmsd(self, cluster, aMask=None, threshold=0.):
        """
        Claculate the average pairwise rmsd (in Angstrom) for members
        of a cluter.

        @param cluster: cluster number
        @type  cluster: int       
        @param aMask: atom mask applied before calculation
        @type  aMask: [1|0]
        @param threshold: float 0-1, minimal cluster membership,
                          see L{memberTraj()}
        @type  threshold: float

        @return: average rmsd and the standard deviation 
        @rtype: float, float   
        """
        try:
            rms = self.memberTraj(cluster, threshold).pairwiseRmsd(aMask)
            rms = aboveDiagonal(rms)
        except:
            rms = []

        if len(N.ravel(rms)) == 1:
            ## was: return N.average(rms)[0], 0.0
            return N.average(rms), 0.0
        if len(N.ravel(rms)) == 0:
            return 0.0, 0.0

        return N.average(rms), SD(rms)
Example #5
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))
Example #6
0
def arrayEqual( a, b ):
    """
    Compare 2 arrays or lists of numbers for equality.

    @param a: first array (multi-dimensional is supported)
    @type  a: array / list
    @param b: second array (multi-dimensional is supported)
    @type  b: array / list

    @return: 1 if array/list a equals array/list b
    @rtype: 1|0
    """
    if a is None or b is None:
        return a is b

    if len(a) != len(b):
        return 0

    if type(a) is list:  a = N.array( a )
    if type(b) is list:  b = N.array( b )

    a = N.ravel( a )
    b = N.ravel( b )

    return N.sum( a==b ) == len(a)
Example #7
0
    def calcReducedContacts(self, soln, c):
        """
        Get contact matrices and/or fnarc from reduced-atom models.

        @param soln: solution number
        @type  soln: int
        @param c: Complex
        @type  c: Complex       
        """
        if not (self.reduced_recs and self.reduced_ligs):
            return

        if not self.requested(c, 'c_ratom_10', 'fnarc_10'):
            return

        try:
            ## create Complex with same orientation but reduced coordinates
            red_rec = self.reduced_recs[c.rec_model.source]
            red_lig = self.reduced_ligs[c.lig_model.source]
            red_com = Complex(red_rec, red_lig, c.ligandMatrix)

            contacts = red_com.atomContacts(10.0, cache=1)

            if self.requested(c, 'c_ratom_10'):
                c['c_ratom_10'] = MU.packBinaryMatrix(contacts)

            if self.c_ref_ratom_10 is not None:
                ref = N.ravel(self.c_ref_ratom_10)
                c['fnarc_10'] = N.sum( N.ravel(contacts) * ref )\
                 / float( N.sum(ref))

        except:
            self.reportError('reduced contacts error', soln)
Example #8
0
 def bounds(self):
     "Return the bounding box for the surface."
     w = self.cntrl[3, :, :]
     cx = numerix.sort(numerix.ravel(self.cntrl[0, :, :] / w))
     cy = numerix.sort(numerix.ravel(self.cntrl[1, :, :] / w))
     cz = numerix.sort(numerix.ravel(self.cntrl[2, :, :] / w))
     return numerix.asarray([cx[0], cy[0], cz[0], cx[-1], cy[-1], cz[-1]],
                            numerix.Float)
Example #9
0
 def bounds(self):
     "Return the bounding box for the surface."
     w = self.cntrl[3,:,:]
     cx = numerix.sort(numerix.ravel(self.cntrl[0,:,:]/w))
     cy = numerix.sort(numerix.ravel(self.cntrl[1,:,:]/w))
     cz = numerix.sort(numerix.ravel(self.cntrl[2,:,:]/w))
     return numerix.asarray([cx[0], cy[0], cz[0],
                             cx[-1], cy[-1], cz[-1]], numerix.Float)
Example #10
0
def triangularGet(m2d, upper=1):
    """Returns 1D masked array with elements from the upper (lower) triangular part of the given matrix.
    For a symetric matrix triangularGet(m2d, 0) and triangularGet(m2d, 1) return elements in different order.
    """
    assert upper in [0,1], "upper: [0|1] expected"
    m2d = MA.asarray(m2d)
    assert MA.rank(m2d) == 2, "2D (masked) array expected"
    if upper:
        takeInd = Numeric.compress(Numeric.ravel(Numeric.fromfunction(lambda i,j: i<j, m2d.shape)), Numeric.arange(0, Numeric.multiply.reduce(m2d.shape), typecode=Numeric.Int))
    else:
        takeInd = Numeric.compress(Numeric.ravel(Numeric.fromfunction(lambda i,j: i>j, m2d.shape)), Numeric.arange(0, Numeric.multiply.reduce(m2d.shape), typecode=Numeric.Int))
    return MA.ravel(m2d).take(takeInd)
Example #11
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))
Example #12
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) )
Example #13
0
    def test_ComplexTraj(self):
        """Dock.ComplexTraj test"""

        import Biskit.tools as T

        ## there is no complex trajectory in the test folder so will have
        ## to create a fake trajectory with a complex
        f =  [ T.testRoot()+ '/com/1BGS.pdb' ] * 5
        t = Trajectory( f, verbose=self.local )

        t = ComplexTraj( t, recChains=[0] )

        #if self.local:
            #print 'plotting contact density...'
            #t.plotContactDensity( step=2 )

        ## create a fake second chain in the ligand
        for i in range( 1093+98, 1968 ):
            t.ref.atoms['chain_id'][i] = 'B'

        t.ref.chainIndex( force=1, cache=1 )
        t.cl = [1,2]

        r = N.concatenate((range(1093,1191), range(0,1093), range(1191,1968)))

        tt = t.takeAtoms( r )

        contactMat = tt.atomContacts( 1 )
        
        if self.local:
            print 'Receptor chains: %s    Ligand chains: %s'%(t.cr, t.cl)
            
        self.assertEqual( N.sum(N.ravel(contactMat)), 308 )
Example #14
0
    def test_molTools(self):
        """molTools test"""
        from Biskit import PDBModel

        ## Loading PDB...
        self.m = PDBModel(T.testRoot() + '/lig/1A19.pdb')
        self.m = self.m.compress(self.m.maskProtein())

        hb = hbonds(self.m)

        xyz = xyzOfNearestCovalentNeighbour(40, self.m)

        if self.local:
            print '\nThe nearest covalently attached atom to the'
            print '  atom with index 40 has the coordinates:'
            print xyz

            print 'Potential h-bonds in model:'
            print '(donor index, acceptor index, distance and angle)'
            for h in hb:
                print h

            globals().update(locals())

        self.r = N.sum(N.ravel(hb[3:5])) + N.sum(xyz)

        self.assertAlmostEqual(self.r, self.EXPECT, 3)
Example #15
0
    def takeMembers( self, mIndices ):
        """
        Take all frames belonging to the members in mIndices::
          takeMembers( mIndices ) -> EnsembleTraj with frames of given members
        
        @param mIndices: list of member indices
        @type  mIndices: [int] OR array('i')
        
        @return: EnsembleTraj with specified members
        @rtype: EnsembleTraj
        
        @todo: return self.__class__ instead of EnsembleTraj
        """
        try:
            ## assumes that each member traj has same number of frames
            fi = N.array( [ self.memberIndices( i ) for i in mIndices ] )
            fi = N.ravel( N.transpose( fi ) )

            n_members = len( mIndices )

            ## has wrong n_members and member order
            t = self.takeFrames( fi )

            result = EnsembleTraj( n_members=n_members )

            result.__dict__.update( t.__dict__ )
            result.n_members = n_members
            result.resetFrameNames()

            return result

        except TypeError:
            raise EnsembleTrajError, 'takeMembers TypeError '+\
                  str(mIndices)+\
                  "\nlenFrames: %i; n_members: %i" %(len(self), self.n_members)
Example #16
0
    def takeMembers(self, mIndices):
        """
        Take all frames belonging to the members in mIndices::
          takeMembers( mIndices ) -> EnsembleTraj with frames of given members
        
        @param mIndices: list of member indices
        @type  mIndices: [int] OR array('i')
        
        @return: EnsembleTraj with specified members
        @rtype: EnsembleTraj
        
        @todo: return self.__class__ instead of EnsembleTraj
        """
        try:
            ## assumes that each member traj has same number of frames
            fi = N.array([self.memberIndices(i) for i in mIndices])
            fi = N.ravel(N.transpose(fi))

            n_members = len(mIndices)

            ## has wrong n_members and member order
            t = self.takeFrames(fi)

            result = EnsembleTraj(n_members=n_members)

            result.__dict__.update(t.__dict__)
            result.n_members = n_members
            result.resetFrameNames()

            return result

        except TypeError:
            raise EnsembleTrajError, 'takeMembers TypeError '+\
                  str(mIndices)+\
                  "\nlenFrames: %i; n_members: %i" %(len(self), self.n_members)
Example #17
0
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 setData(self, data,calib,config):
        try:
            if config["file"]:
                self._configure(config)
            x = Numeric.array(data[:,0]).astype(Numeric.Float)
            y = Numeric.array(data[:,1]).astype(Numeric.Float)
            xmin = float(config["min"])
            xmax = float(config["max"])
            self.mcafit.refreshWidgets()
            calib = Numeric.ravel(calib).tolist()
            kw = {}
            kw.update(config)
            kw['xmin'] = xmin
            kw['xmax'] = xmax
            kw['calibration'] = calib
            self.mcafit.setdata(x, y, **kw)# xmin=xmin, xmax=xmax, calibration=calib)
            self.mcafit._energyAxis = False
            self.mcafit.toggleEnergyAxis()
            result = self._fit()
            #pyarch file name and directory
            pf = config["legend"].split(".")
            pd = pf[0].split("/")
            outfile = pd[-1]
            outdir = config['htmldir']
            sourcename = config['legend']
            report = McaAdvancedFit.QtMcaAdvancedFitReport.QtMcaAdvancedFitReport(None, outfile=outfile, outdir=outdir,fitresult=result, sourcename=sourcename, plotdict={'logy':False}, table=2)

            text = report.getText()
            report.writeReport(text=text)
  
        except:
            logging.getLogger().exception('McaSpectrumBrick: problem fitting %s %s %s' % (str(data),str(calib),str(config)))
            raise
Example #19
0
    def test_rmsFit(self):
        """rmsFit test"""
        import Biskit.tools as T

        self.traj = T.load(T.testRoot() + '/lig_pcr_00/traj.dat')

        rt, rmsdLst = match(self.traj.ref.xyz, self.traj[-1].xyz)

        if self.local:
            print 'RMSD: %.2f' % rmsdLst[0][1]

        # return rotation matrix
        r = abs(N.sum(N.ravel(rt[0])))
        e = abs(N.sum(N.ravel(self.EXPECT)))

        self.assertAlmostEqual(r, e, 6)
Example #20
0
    def test_rmsFit( self ):
        """rmsFit test"""
        import Biskit.tools as T

        self.traj = T.load( T.testRoot() + '/lig_pcr_00/traj.dat' )

        rt, rmsdLst = match( self.traj.ref.xyz, self.traj[-1].xyz)

        if self.local:
            print 'RMSD: %.2f' % rmsdLst[0][1]

        # return rotation matrix
        r = abs( N.sum( N.ravel( rt[0] )))
        e = abs( N.sum( N.ravel( self.EXPECT )))

        self.assertAlmostEqual(r, e, 6)
Example #21
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
Example #22
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
Example #23
0
def compressIndices(ma):
    """Returns 1D compressed Numeric array and the indices of the non-masked places.
    usage:  nu,ind = compressIndices(ma)
            nu = Numeric.elementwise_function(nu)
            ma = MA.put(ma, ind, nu)
    """
    ma = MA.asarray(ma)
    nonMaskedInd = Numeric.compress(1-Numeric.ravel(MA.getmaskarray(ma)), Numeric.arange(Numeric.multiply.reduce(ma.shape)))
    return MA.filled(ma.compressed()), nonMaskedInd
Example #24
0
def zScores(data, ravel=None):
    import numpy.oldnumeric as Numeric  #@Reimport

    if ravel is None:
        d = Numeric.array(data)
    else:
        d = Numeric.ravel(Numeric.array(data))
    average = average(d)
    sd = standardDeviation(d)

    return (data - average) / sd
Example #25
0
def zScores(data, ravel = None):
    import numpy.oldnumeric as Numeric #@Reimport

    if ravel is None:
        d = Numeric.array(data)
    else:
        d = Numeric.ravel(Numeric.array(data))
    average = average(d)
    sd = standardDeviation(d)

    return (data-average)/sd
Example #26
0
def diagonalPut(m1d, m2d):
    """Puts the given 1D masked array into the diagonal of the given 2D masked array and returns a new copy of the 2D array.
    """
    m1d = MA.asarray(m1d)
    m2d = MA.asarray(m2d)
    assert MA.rank(m1d) == 1 and MA.rank(m2d) == 2, "1D and 2D masked array expected"
    assert m1d.shape[0] == m2d.shape[0] == m2d.shape[1], "the shape of the given arrays does not match"
    putIndices = Numeric.compress(Numeric.ravel(Numeric.fromfunction(lambda i,j: i==j, m2d.shape)), Numeric.arange(0, Numeric.multiply.reduce(m2d.shape), typecode=Numeric.Int))
    m2dShape = m2d.shape
    m2d = MA.ravel(m2d)
    MA.put(m2d, putIndices, m1d)
    return MA.reshape(m2d, m2dShape)
Example #27
0
    def plotContactDensity( self, step=1, cutoff=4.5 ):
        """
        Example. plot histogramm of contact density. Somehing wrong??

        @raise ComplexTrajError: if gnuplot program is not installed
        """
        if not gnuplot.installed:
            raise ComplexTrajError, 'gnuplot program is not installed'
        r = self.averageContacts( step, cutoff )
        r = N.ravel( r )
        r = N.compress( r, r )
        gnuplot.plot( hist.density( r, 10 ) )
Example #28
0
    def setData(self, data, calib, config):
        print('McaSpectrumBrick: setData')
        print('data', data)
        print('calib', calib)
        print('config', config)
        #calib = [0, 10, 0]
        try:
            #if config["file"]:
            #self._configure(config)
            x = Numeric.array(data[0]).astype(Numeric.Float)
            y = Numeric.array(data[1]).astype(Numeric.Float)
            xmin = x[0]  #float(config["min"])
            xmax = x[-1]  #float(config["max"])

            #x = Numeric.array(data[:,0]).astype(Numeric.Float)
            #y = Numeric.array(data[:,1]).astype(Numeric.Float)
            #xmin = float(config["min"])
            #xmax = float(config["max"])
            self.mcafit.refreshWidgets()
            calib = Numeric.ravel(calib).tolist()
            kw = {}
            kw.update(config)
            kw['xmin'] = xmin
            kw['xmax'] = xmax
            kw['calibration'] = calib
            self.mcafit.setdata(
                x, y, **kw)  # xmin=xmin, xmax=xmax, calibration=calib)
            self.mcafit._energyAxis = False
            self.mcafit.toggleEnergyAxis()
            result = self._fit()
            #pyarch file name and directory
            pf = config["legend"].split(".")
            pd = pf[0].split("/")
            outfile = pd[-1]
            outdir = config['htmldir']
            sourcename = config['legend']
            report = McaAdvancedFit.QtMcaAdvancedFitReport.QtMcaAdvancedFitReport(
                None,
                outfile=outfile,
                outdir=outdir,
                fitresult=result,
                sourcename=sourcename,
                plotdict={'logy': False},
                table=2)

            text = report.getText()
            report.writeReport(text=text)

        except:
            logging.getLogger().exception(
                'McaSpectrumBrick: problem fitting %s %s %s' %
                (str(data), str(calib), str(config)))
            raise
Example #29
0
    def calcContacts( self, soln, c ):
        """
        Calculate contact matrices and fraction of native contacts, residue-
        and atom-based, with different distance cutoffs.

        @param soln: solution number
        @type  soln: int
        @param c: Complex
        @type  c: Complex
        """
        try:
            if self.requested(c, 'fnac_4.5') and self.c_ref_atom_4_5 != None:
                ## cache pairwise atom distances for following calculations
                contacts = c.atomContacts( 4.5, self.mask_rec, self.mask_lig,
                                           cache=1, map_back=0 )
                ref = N.ravel( self.c_ref_atom_4_5 )

                c['fnac_4.5'] = N.sum( N.ravel(contacts) * ref )\
                 / float( N.sum(ref))

            if self.requested(c, 'fnac_10') and self.c_ref_atom_10 != None:

                contacts = c.atomContacts( 10., self.mask_rec, self.mask_lig,
                                           cache=1, map_back=0 )

                ref = N.ravel( self.c_ref_atom_10 )
                c['fnac_10'] = N.sum( N.ravel(contacts) * ref ) \
                 / float( N.sum(ref))

            if self.requested(c, 'c_res_4.5') \
               or ( self.c_ref_res_4_5 != None \
                    and (self.requested(c,'fnrc_4.5','fnSurf_rec'))):

                res_cont = c.resContacts( 4.5,
                                          cache=self.requested(c, 'c_res_4.5'))

                if self.c_ref_res_4_5 != None \
                   and self.requested(c, 'fnrc_4.5' ):
                    ref = N.ravel( self.c_ref_res_4_5 )
                    c['fnrc_4.5'] = N.sum(N.ravel(res_cont)*ref) \
                     /float(N.sum(ref))

                if self.c_ref_res_4_5 != None \
                   and self.requested(c, 'fnSurf_rec'):
                    r, l = c.fractionNativeSurface(res_cont,
                                                   self.c_ref_res_4_5 )
                    c['fnSurf_rec'] = r
                    c['fnSurf_lig'] = l

        except:
            m1 = m2 = s = 0
            try:
                m1, m2, s = c.get('model1',0), c.get('model2',0),\
                  c.get('soln',0)
            except:
                pass
            self.reportError('contact error (r %i : l %i, #%i)'%\
                             (m1,m2,s), soln)
Example #30
0
    def __init__(self, models, name=None, profileName='relAS', verbose=1):
        """
        @param models: List of models display a Ramachandran plot for
        @type  models: [ PDBModel ] OR PDBModel
        @param name: model name, will show up in plot
        @type  name: str
        @param profileName: name of profile to use for coloring
                            (default: 'relAS')
        @type  profileName: str
        @param verbose: verbosity level (default: 1)
        @type  verbose: 1|0
        """
        if not biggles:
            raise ImportError, 'biggles module could not be imported.'

        if type(models) != type([]):
            models = [models]

        self.psi = []
        self.phi = []

        self.gly = []
        self.pro = []

        self.prof = []
        self.profileName = profileName

        self.name = name

        self.verbose = verbose

        # calculate angles, profiles ...
        self.calc(models)

        self.prof = N.ravel(self.prof)
        self.gly = N.ravel(self.gly)
        self.pro = N.ravel(self.pro)
Example #31
0
def edge_average(a):
    "Return the mean value around the edge of an array."

    if len(ravel(a)) < 2:
        return float(a[0])
    else:
        top_edge = a[0]
        bottom_edge = a[-1]
        left_edge = a[1:-1,0]
        right_edge = a[1:-1,-1]

        edge_sum = sum(top_edge) + sum(bottom_edge) + sum(left_edge) + sum(right_edge)
        num_values = len(top_edge)+len(bottom_edge)+len(left_edge)+len(right_edge)

        return float(edge_sum)/num_values
Example #32
0
    def getFirstCrdLine( self ):
        """
        Return the first line of Amber crd.

        @return: first line of Amber crd formatted coordinate block
        @rtype: str
        """
        if not self.xyz:
            self.getXyz()

        result = ""
        for x in N.ravel( self.xyz )[:10]:
            result += "%8.3f" % x

        return result + "\n"
def edge_average(a):
    "Return the mean value around the edge of an array."

    if len(ravel(a)) < 2:
        return float(a[0])
    else:
        top_edge = a[0]
        bottom_edge = a[-1]
        left_edge = a[1:-1,0]
        right_edge = a[1:-1,-1]

        edge_sum = sum(top_edge) + sum(bottom_edge) + sum(left_edge) + sum(right_edge)
        num_values = len(top_edge)+len(bottom_edge)+len(left_edge)+len(right_edge)

        return float(edge_sum)/num_values
Example #34
0
def changeModel( inFile, prefix, sourceModel ):

    print '\nget ' + os.path.basename( inFile ) + '..',

    model = PDBModel( inFile )

    model.update()

    model = model.sort()

    eq = model.equals( sourceModel )
    if not eq[0] and eq[1]:
        raise ConvertError('source and other models are not equal: ' + str(eq))

#    model.validSource()
    model.setSource( sourceModel.validSource() )

    #model.atomsChanged = 0
    for k in model.atoms:
        model.atoms[k,'changed'] = N.all( model[k] == sourceModel[k] )

    model.xyzChanged = ( 0 != N.sum( N.ravel( model.xyz - sourceModel.xyz)) )

    model.update( updateMissing=1 )

    if model.xyzChanged:

        doper = PDBDope( model )

        if 'MS' in sourceModel.atoms.keys():
            doper.addSurfaceRacer( probe=1.4 )

        if 'density' in sourceModel.atoms.keys():
            doper.addDensity()

        if 'foldX' in sourceModel.info.keys():
            doper.addFoldX()
            
        if 'delphi' in sourceModel.info.keys():
            doper.addDelphi()

    outFile = os.path.dirname( inFile ) + '/' + prefix +\
            T.stripFilename( inFile ) + '.model' 

    T.dump( model, outFile )

    print '-> ' + os.path.basename( outFile )
Example #35
0
    def writeCrd( self, fcrd, append=1, lastAtom=None ):
        """
        Write/Append Amber-formatted block of coordinates to a file.
        If a file handle is given, the file will not be closed.

        @param fcrd: file to write to
        @type  fcrd: str or file object
        @param append: append to existing file (default: 1)
        @type  append: 0|1
        @param lastAtom: skip all atoms beyond this one (default: None)
        @type  lastAtom: int
        """
        if not self.xyz:
            self.getXyz()

        if type( fcrd ) == file:
            ## take file handle
            f = fcrd
        else:
            ## create new file handle
            mode = 'w'
            if append:
                mode = 'a'
            f = open( T.absfile( fcrd ), mode )

            newf = (mode=='w' or not os.path.exists( T.absfile(fcrd) ))
            if newf:
                f.write("\n")

        i = 0
        for x in N.ravel( self.xyz ):
            i = i + 1

            f.write( "%8.3f" % x )

            if (i % 10) == 0:
                f.write("\n")

            if lastAtom and i / 3.0 == lastAtom:
                break

        if ((i % 10) != 0):
            f.write("\n")

        if type( fcrd ) != file:
            ## don't close file that was already given
            f.close()
Example #36
0
def simplify(obj):
    """A helper function to convert results obtained from Octave.
    This will convert all 1x1 arrays to scalars, vectors to 1D arrays,
    1xN and 0x0 character arrays to strings, 1xN, Nx1 and 0x0 cell
    arrays to lists, and strip scalar dicts. It will work recursively."""

    def get_typecode(array):
	"""gets the typecode from both Numeric and NumPy array"""
	try:
	    tc = array.typecode()
	except:
	    tc = array.dtype.char
	return tc

    def vectordims(dims,column_allowed = True):
	return (len(dims) == 2 and 
		((dims[0] == 1 or (column_allowed and dims[1] == 1)) or
		(dims[0] == 0 and dims[1] == 0)))

    if isinstance(obj,Numeric.ArrayType):
	tc = get_typecode(obj)
	if tc == 'O':
	    if vectordims(Numeric.shape(obj)):
		return map(simplify,narrowlist(obj))
	elif tc == 'c':
	    if vectordims(Numeric.shape(obj), False):
		return obj.tostring()
	else:
	    dims = Numeric.shape(obj)
	    if dims == (1,1):
		return obj[0,0]
	    elif vectordims(dims):
		return Numeric.ravel(obj)
    elif isinstance(obj,dict):
	sobj = {}
	for key in obj:
	    sval = simplify(obj[key])
	    if isinstance(sval,list) and len(sval) == 1:
		sval = sval[0]
	    sobj[key] = sval
	return sobj
    elif isinstance(obj,tuple):
	return tuple(map(simplify,obj))
    ## default.
    return obj
Example #37
0
def simplify(obj):
    """A helper function to convert results obtained from Octave.
    This will convert all 1x1 arrays to scalars, vectors to 1D arrays,
    1xN and 0x0 character arrays to strings, 1xN, Nx1 and 0x0 cell
    arrays to lists, and strip scalar dicts. It will work recursively."""

    def get_typecode(array):
        """gets the typecode from both Numeric and NumPy array"""
        try:
            tc = array.typecode()
        except:
            tc = array.dtype.char
        return tc

    def vectordims(dims, column_allowed=True):
        return len(dims) == 2 and (
            (dims[0] == 1 or (column_allowed and dims[1] == 1)) or (dims[0] == 0 and dims[1] == 0)
        )

    if isinstance(obj, Numeric.ArrayType):
        tc = get_typecode(obj)
        if tc == "O":
            if vectordims(Numeric.shape(obj)):
                return map(simplify, narrowlist(obj))
        elif tc == "c":
            if vectordims(Numeric.shape(obj), False):
                return obj.tostring()
        else:
            dims = Numeric.shape(obj)
            if dims == (1, 1):
                return obj[0, 0]
            elif vectordims(dims):
                return Numeric.ravel(obj)
    elif isinstance(obj, dict):
        sobj = {}
        for key in obj:
            sval = simplify(obj[key])
            if isinstance(sval, list) and len(sval) == 1:
                sval = sval[0]
            sobj[key] = sval
        return sobj
    elif isinstance(obj, tuple):
        return tuple(map(simplify, obj))
        ## default.
    return obj
Example #38
0
def packBinaryMatrix(cm):
    """
    Compress sparse array of 0 and ones to list of one-positions
    (space saving function, upack with L{unpackBinaryMatrix}).

    @param cm: X by Y array of int
    @type  cm: 2D array 

    @return: {'shape':(X,Y), 'nonzero':[int] }
    @rtype: dict
    """
    if cm == None or type(cm) == dict:
        return cm

    result = {}
    result['shape'] = N.shape(cm)
    result['nonzero'] = N.nonzero(N.ravel(cm))
    result['nonzero'] = result['nonzero'].tolist()
    return result
Example #39
0
    def set_data(self, data, calib, config):
        try:
            configured = False
            if os.path.exists(config.get("file", "")):
                self._configure(config)
                configured = True
            data = Numeric.array(data)
            x = Numeric.array(data[:, 0]).astype(Numeric.Float)
            y = Numeric.array(data[:, 1]).astype(Numeric.Float)
            xmin = float(config["min"])
            xmax = float(config["max"])
            #self.mcafit_widget.refreshWidgets()
            calib = Numeric.ravel(calib).tolist()
            """kw = {}
            kw.update(config)
            kw['xmin'] = xmin
            kw['xmax'] = xmax
            kw['calibration'] = calib"""
            self.mcafit_widget.setdata(x, y)
            #elf.mcafit.setdata(x, y, **kw)# xmin=xmin, xmax=xmax, calibration=calib)
            self.mcafit_widget._energyAxis = False
            self.mcafit_widget.toggleEnergyAxis()
            #result = self._fit()
            #pyarch file name and directory
            pf = config["legend"].split(".")
            pd = pf[0].split("/")
            outfile = pd[-1]
            outdir = config['htmldir']
            sourcename = config['legend']

            result = self._fit()
            if configured:
                report = McaAdvancedFit.QtMcaAdvancedFitReport.\
                     QtMcaAdvancedFitReport(None, outfile=outfile, outdir=outdir,
                     fitresult=result, sourcename=sourcename,
                     plotdict={'logy':False}, table=2)

                text = report.getText()
                report.writeReport(text=text)

        except:
            logging.getLogger().exception("McaSpectrumWidget: problem fitting %s %s %s" % \
                                          (str(data), str(calib), str(config)))
Example #40
0
def packBinaryMatrix( cm ):
    """
    Compress sparse array of 0 and ones to list of one-positions
    (space saving function, upack with L{unpackBinaryMatrix}).

    @param cm: X by Y array of int
    @type  cm: 2D array 

    @return: {'shape':(X,Y), 'nonzero':[int] }
    @rtype: dict
    """
    if cm == None or type( cm ) == dict:
        return cm

    result = {}
    result['shape'] = N.shape( cm )
    result['nonzero'] = N.nonzero( N.ravel( cm ) )
    result['nonzero'] = result['nonzero'].tolist()
    return result
Example #41
0
    def color_array( self, a, resetLimits=1 ):
        """
        @param a: array of float
        @type  a: array of float
        @param resetLimits: re-define color range on max and min of values
                            (default: 1)
        @type  resetLimits: 1|0
        
        @return: matrix of color codes with same dimensions as a
        @rtype: array of float
        """
        s = N.shape( a )
        v = N.ravel( a )

        r = self.colors( v, resetLimits=resetLimits )

        r = N.reshape( r, s )

        return r
Example #42
0
    def slim(self):
        """
        Remove coordinates and atoms of ligand and receptor from memory,
        if they can be restored from file, compress contact matrix.
        @note: CALLED BEFORE PICKLING
        """
        self.lig_transformed = None
        self.pw_dist = None

##         self.ligandMatrix = self.ligandMatrix.tolist()

        if 'matrix' in self.info:
            del self.info['matrix']

        ## compress contact matrix array
        if self.contacts != None and \
               len(N.shape( self.contacts['result'] ) )==2:
            m = self.contacts['result']
            self.contacts['shape'] = N.shape( m )

            self.contacts['result'] = N.nonzero( N.ravel( m ) ).astype(N.Int32)
Example #43
0
def matrixToList(cm):
    """
    Convert matrix into standard python list remembering the dimensions.
    Unpack with L{listToMatrix}.

    @note: Not used right now.

    @param cm: array of int
    @type  cm: 2D array

    @return: {'shape':(int,..), 'lst':[..] }
    @rtype: dict
    """
    if cm == None or type(cm) == dict:
        return cm

    result = {}
    result['shape'] = N.shape(cm)
    result['lst'] = N.ravel(cm).tolist()

    return result
Example #44
0
def matrixToList( cm ):
    """
    Convert matrix into standard python list remembering the dimensions.
    Unpack with L{listToMatrix}.

    @note: Not used right now.

    @param cm: array of int
    @type  cm: 2D array

    @return: {'shape':(int,..), 'lst':[..] }
    @rtype: dict
    """
    if cm == None or type( cm ) == dict:
        return cm

    result = {}
    result['shape'] = N.shape( cm )
    result['lst'] = N.ravel( cm ).tolist()

    return result
Example #45
0
    def calcRmsd( self, window, f1, f2 ):
        """
        Calulate the rmsd between two frame chunks.
        
        @param window: start and end of two frame chunks within the
                       whole trajectory
        @type  window: ((int, int),(int,int))
        @param f1: frame chunk
        @type  f1: array
        @param f2: frame chunk
        @type  f2: array
        
        @return: the rms between the frames
        @rtype: [float]
        """
        try:
            i_start, i_stop = window[0]
            j_start, j_stop = window[1]

            a = N.zeros( (i_stop-i_start, j_stop-j_start), N.Float )

            i = j = -1

            ## block on the diagonal, only calculate one half of it
            S = (self.only_off_diagonal and window[0] == window[1])

            for i in range( i_start, i_stop ):
                for j in range( S * i - S * j_start + j_start, j_stop ):

                    if self.requested( i, j ):

                        rt, rmsdLst = rmsFit.match( f1[i-i_start],
                                                    f2[j-j_start], 1 )
                        a[i-i_start,j-j_start] = rmsdLst[0][1]

            return N.ravel(a).tolist()

        except Exception, why:
            self.reportError( 'ERROR '+str(why), (i,j) )
            return
Example #46
0
    def setData(self, data, calib, config):
        try:
            configured = False
            if config.get("file", None):
                self._configure(config)
                configured = True
            data = Numeric.array(data)
            x = Numeric.array(data[:, 0]).astype(Numeric.Float)
            y = Numeric.array(data[:, 1]).astype(Numeric.Float)
            calib = Numeric.ravel(calib).tolist()
            self.mcafit.setdata(x, y)
            self.mcafit._energyAxis = False
            self.mcafit.toggleEnergyAxis()
            result = self._fit()
            # pyarch file name and directory
            pf = config["legend"].split(".")
            pd = pf[0].split("/")
            outfile = pd[-1]
            outdir = config["htmldir"]
            sourcename = config["legend"]

            if configured:
                report = McaAdvancedFit.QtMcaAdvancedFitReport.QtMcaAdvancedFitReport(
                    None,
                    outfile=outfile,
                    outdir=outdir,
                    fitresult=result,
                    sourcename=sourcename,
                    plotdict={"logy": False},
                    table=2,
                )

                text = report.getText()
                report.writeReport(text=text)

        except BaseException:
            logging.getLogger().exception(
                "McaSpectrumBrick: problem fitting %s %s %s"
                % (str(data), str(calib), str(config))
            )
Example #47
0
    def writeCrd( self, fname, frames=None ):
        """
        Write frames to Amber crd file (w/o box info).

        @param fname: output file name
        @type  fname: str
        @param frames: frame indices (default: all)
        @type  frames: [int]
        """
        if frames == None:
            frames = range( self.lenFrames() )

        template = " %7.3f" * 10 + '\n'

        ## open new file
        out = open( T.absfile(fname), 'w')
        __write = out.write  ## cache function address for speed

        __write('\n')

        n_lines = None

        for fi in frames:
            f = N.ravel( self.frames[ fi ] )

            if n_lines is None:
                n_lines = n_lines or len( f ) / 10
                overhang= ( 0 != len( f ) % 10 )
                i_lines = range( n_lines )

            for i in i_lines:
                __write( template % tuple( f[10*i:10*i+10] ) )

            if overhang:
                for x in f[i*10+10:]:
                    __write(" %7.3f" % x )
                __write('\n')

        out.close()
Example #48
0
    def thin( self, step=1 ):
        """
        Keep only each step'th frame from trajectory with 10 ensemble members.
        
        @param step: 1..keep all frames, 2..skip first and every second, ..
                     (default: 1)
        @type  step: int
        
        @return: reduced EnsembleTraj
        @rtype: EnsembleTraj
        """
        T.ensure( step, int, forbidden=[0] )

        ## 10 x lenFrames/10, frame indices of each member
        mI = [ self.memberIndices( i ) for i in range(self.n_members) ]

        mI = N.array( mI )

        mI = N.take( mI, range( -1, N.shape( mI )[1], step )[1:], 1 )

        mI = N.transpose( mI )

        return self.takeFrames( N.ravel( mI ))
Example #49
0
def narrowlist(objarray):
    """A helper function to convert cell arrays obtained from Octave.
    Octave cells are returned as Numeric object arrays. This function
    will flatten the array and convert it into a 1D list."""

    return Numeric.ravel(objarray).tolist()
Example #50
0
    def pcMovie( self, ev, steps, factor=1., ref=0, morph=1 ):
        """
        Morph between the two extreme values of a single principal
        component.

        @param ev: EigenVector to visualize
        @type  ev: int
        @param steps: number of intermediate frames
        @type  steps: int
        @param factor: exageration factor (default: 1 = No exageration)
        @type  factor: float
        @param ref: take other eigenvecors from this frame (default: 1)
        @type  ref: int
        @param morph: morph between min and max (1) or take real values (0)
                      (default: 1)
        @type  morph: 1|0

        @return: Trajectory with frames visualizing the morphing.
        @rtype: Trajectory
        """
        fit = 1
        if self.pc is not None:
            fit = self.pc['fit']
        pc = self.getPca( fit=fit )

        ## eigenvectors (rows)
        U = pc['u']

        ## raveled and centered frames
        x_avg = N.average(self.frames, 0)
        X = N.array( [N.ravel(x) for x in self.frames - x_avg] )

        ## ev'th eigenvector of reference frame
        alpha_0 = N.dot( X[ref], U[ev] )

        ## list of deviations of ev'th eigenvector of each frame from ref
        alpha_range = N.dot(X, U[ev]) - alpha_0

        ## get some representative alphas...
        if morph:
            a_min = factor * min(alpha_range)
            a_max = factor * max(alpha_range)
            delta = (a_max - a_min) / steps
            alpha_range = [ a_min + i*(delta) for i in range(0, steps) ]
        else:
            alpha_range = N.sort( alpha_range )
            delta = len(alpha_range) / (steps * 1.0)
            alpha_range = [ alpha_range[ int(round( i*delta )) ]
                            for i in range(0,steps) ]

        ## scale ev'th eigenvector of ref with different alphas 
        Y = N.array( [ X[ref] + alpha * U[ev] for alpha in alpha_range] )

        ## back convert to N x 3 coordinates
        Y = N.reshape(Y, (Y.shape[0], -1, 3))
        Y = x_avg + Y

        result = self.__class__()
        result.ref = self.ref

        result.frames = Y
        return result