numpy.oldnumeric.array

Here are the examples of the python api numpy.oldnumeric.array taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

74 Examples 7

3 Source : AutoDockBondClassifier.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def dist(c1, c2):       
    import numpy.oldnumeric as Numeric, math
    d = Numeric.array(c2) - Numeric.array(c1) 
    ans = math.sqrt(Numeric.sum(d*d))
    return round(ans, 3)


class AutoDockBondClassifier(BondClassifier):

3 Source : Conformation.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def dist(c1, c2):
    d = Numeric.array(c2) - Numeric.array(c1)
    ans = math.sqrt(Numeric.sum(d*d))
    return round(ans, 3)

def getAngle(at1, at2, at3 ):

3 Source : Conformation.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def getAngle(at1, at2, at3 ):
    pt1 = Numeric.array(at1.coords, 'f')
    pt2 = Numeric.array(at2.coords, 'f')
    pt3 = Numeric.array(at3.coords, 'f')
    v1 = Numeric.array(pt1 - pt2)
    v2 = Numeric.array(pt3 - pt2)
    dist1 = math.sqrt(Numeric.sum(v1*v1))
    dist2 = math.sqrt(Numeric.sum(v2*v2))
    sca = Numeric.dot(v1, v2)/(dist1*dist2)
    if sca>1.0:
        sca = 1.0
    elif sca  <  -1.0:
        sca = -1.0
    ang =  math.acos(sca)*180./math.pi
    return round(ang, 5)

def build_dict(mol):

3 Source : prepare_covalent_flexres.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def dist(a1, a2):
    c1 = Numeric.array(a1.coords)
    c2 = Numeric.array(a2.coords)
    d = c2-c1
    return sqrt(sum(d*d))


def getBondedAtoms(atom):

3 Source : alignmentEditor.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def makeMatrix(self):
        """ Sets up a matrix (nsequences x len(sequences), the elements of which are 0 for a gap,
        1 for anything else. Used by the trim command"""
        self.matrix = []
        for x in range(len(self.sequences)):
            numbers = self[x].gappednumbers
            line = map(lambda x: x != '',numbers)
            self.matrix.append(line)
        self.matrix = Numeric.array(self.matrix)

    
    def addSequence(self,sequence,index=None):

3 Source : colorWidgets.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def get(self, mode='HSV'):
	"""Get the current color"""
	if mode == 'RGB':
	    rgb = ToRGB(self.hsvColor)
	    #return OneColor(rgb)
            return rgb

	elif mode == 'HSV':
	    #return OneColor(self.hsvColor)
            return self.hsvColor

	elif mode == 'HEX':
	    col = Numeric.array(ToRGB(self.hsvColor[:]), 'f') * 255
	    return ToHEX(col)


    def set(self, color, mode='HSV', trigger=1):

3 Source : tablemaker.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def setIsoColor(self, iso_ind, rgb):
        tkcolor = colorUtil.TkColor(rgb)
        self.canvas.itemconfig('isodot%d'%(iso_ind,), fill=tkcolor)
        val = self.isoVals[iso_ind]['val']
        iso_rgb = (round(rgb[0],2), round(rgb[1],2), round(rgb[2],2))
        self.isoVals[iso_ind]['rgb'] = iso_rgb
        if self.continuous:
            self.callbacks['setcolor']([val, Numeric.array([rgb],'f')])
        self.callbacks['entries'](iso_rgb = iso_rgb)
        
    
    def bind_tags(self):

3 Source : rmsd.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def computeRMSD(self, listCoords):
        """rmsd   <  - computRMSD(listCoords)
        rmsd returns the overall root mean square distance (rmsd) and
        also sets self.distVect as the vector of distances between each
        pair of points.
        """
        if self.refCoords is None:
            raise ValueError("no reference coordinates set")
        if len(self.refCoords) != len(listCoords):
            raise ValueError("input vector length mismatch")

        deltaVect = Numeric.array(self.refCoords) - Numeric.array(listCoords)
        distSquaredVect = Numeric.sum(Numeric.transpose(deltaVect*deltaVect))
        self.distVect = Numeric.sqrt(distSquaredVect)
        self.rmsd = math.sqrt(Numeric.sum(distSquaredVect)/len(self.refCoords))
        return self.rmsd

3 Source : statetocoords.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def applyState(self, state):
        """
        """
        q = state.quaternion
        t = Numeric.array(state.translation)
        o = Numeric.array(state.origin)

        # construct rootNode transformation matrix
        #mtx = Transformation(t+o, q).getMatrix(transpose=1)
        # Corrected by AG 08/28/2008
        mtx = Transformation(t, q).getMatrix().transpose()

        # apply the torsions
        self.applyAngList(state.torsions, mtx)


    def applyStateOld(self, state):

3 Source : statetocoords.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def applyOrientation(self, q=(0.,0.,0.,0.), t=(0.,0.,0.), o=(0.,0.,0.)):
        """origin specifies where the local origin is in world coordinates
        (i.e., where is this object's origin in the world)
        """
        # center the coordinates
        self.resultCoords = (self.resultCoords -
                             Numeric.array([o[0], o[1], o[2], 0.0]))
        sum = Numeric.array(t) + Numeric.array(o)
        self.resultCoords = Transformation(sum, q).apply(self.resultCoords)
        return self.getResultCoords()


    def applyQuaternion(self, q, o=(0.,0.,0.)):

3 Source : statetocoords.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def applyQuaternion(self, q, o=(0.,0.,0.)):
        """Apply the given quaterion.
        """
        # center the coordinates
        self.resultCoords = (self.resultCoords -
                             Numeric.array([o[0], o[1], o[2], 0.0]))
        self.resultCoords = Transformation(o, q).apply(self.resultCoords)
        return self.getResultCoords()


    def applyTranslation(self, t=(0., 0., 0.)):

3 Source : statetocoords.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def applyTranslation(self, t=(0., 0., 0.)):
        """Translate by (x, y, z)
        """
        translation = Numeric.array([t[0], t[1], t[2], 0.0])
        self.resultCoords = self.resultCoords + translation
        return self.getResultCoords()

3 Source : statetocoordstest.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def test_applyTranslation01(self):
        """applyTranslation01 -- random pts x (random translation)"""
        state = StateToCoords(self.random_points, tolist=0)
        trn = RandomArray.uniform(self.min, self.max, (3,))
        expected = (Numeric.array(self.random_points) + trn)
        self.assertArrayEqual(expected, state.applyTranslation(trn))


    def test_applyTranslation02(self):

3 Source : TensorModule.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def __init__(self, elements, nocheck = None):
	self.array = Numeric.array(elements)
	if nocheck is None:
	    if not Numeric.logical_and.reduce(
		Numeric.equal(Numeric.array(self.array.shape), 3)):
		raise ValueError, 'Tensor must have length 3 along any axis'
	self.rank = len(self.array.shape)

    def __repr__(self):

3 Source : TensorModule.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def symmetricalPart(self):
        "Returns the symmetrical part of a rank-2 tensor."
	if self.rank == 2:
	    return Tensor(0.5*(self.array + \
			       Numeric.transpose(self.array,
						    Numeric.array([1,0]))),
			  1)
	else:
	    raise ValueError, 'Not yet implemented'

    def asymmetricalPart(self):

3 Source : TensorModule.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def asymmetricalPart(self):
        "Returns the asymmetrical part of a rank-2 tensor."
	if self.rank == 2:
	    return Tensor(0.5*(self.array - \
			       Numeric.transpose(self.array,
						    Numeric.array([1,0]))),
			  1)
	else:
	    raise ValueError, 'Not yet implemented'

    def eigenvalues(self):

3 Source : usr.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def centroid(points):
    """reuturn the centroid of points
    """
    points = N.array(points)
    num, dim = points.shape
    return N.add.reduce(points)/float(num)


def dist_array(point, points):

3 Source : usr.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def dist_array(point, points):
    """return array of distances from point to each of points
    """
    point  = N.array(point)
    points = N.array(points)
    return N.sqrt(N.add.reduce((points - point)**2, axis=1))


def mean_var_skew(data):

3 Source : usr.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def mean_var_skew(data):
    """return the mean, variance, and skewness of data
    """
    data = N.array(data)
    num = data.shape[0]
    mean = N.add.reduce(data)/float(num)
    var = N.add.reduce((data - mean)**2)/float(num-1)
    #
    std = math.sqrt(var)
    skew = N.add.reduce( (data - mean)**3)/(float(num-1)* std**3)
    return mean, var, skew

        
def usr_descriptors(points):

3 Source : usr.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def usr_similarity(x, y):
    """return similarity of two usr_descriptor vectors, x and y
    """
    x = N.array(x)
    num = float(x.shape[0])
    y = N.array(y)
    # normalized and montonically inverted Manhattan distance
    return num/(num + N.add.reduce(N.absolute(x-y)))


def print_usr_desc(val):

3 Source : usr.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def distance_matrix(points):
    """return NxN point to point distance matrix
    this works but is not needed for USR
    """
    points = N.array(points)
    num, dim = points.shape
    delta = N.zeros((num,num), 'd')
    for d in xrange(dim):
        data = points[:,d]
        delta += (data - data[:,N.NewAxis])**2
    return N.sqrt(delta)


def closest( point, points):

3 Source : VectorModule.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def __init__(self, x=None, y=None, z=None):
	if x is None:
	    self.array = [0.,0.,0.]
	elif y is None and z is None:
	    self.array = x
	else:
	    self.array = [x,y,z]
	self.array = Numeric.array(self.array)

    def __getstate__(self):

3 Source : __init__.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def norm (A):
    """     Return normalized vector A.
"""
    if type(A) == types.ListType:
        A=Numeric.array(A,'f')
        res= A/Numeric.sqrt(Numeric.dot(A,A))
        return res.tolist()    
    elif type(A)==Numeric.ArrayType:    
        return A/Numeric.sqrt(Numeric.dot(A,A))    
    else:
        print "Need a list or Numeric array"
        return None

def getCenter(coords):

3 Source : misc.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def deepCopySeq(sequence):
    """ returns the deep copy of the given sequence """
    import numpy.oldnumeric as Numeric
    from types import TupleType, ListType
    assert type(sequence) in (TupleType, ListType, type(Numeric.array([1,2,3])))
    if hasattr(sequence, 'copy'):
        dcSeq = sequence.copy()
    else:
        dcSeq = sequence[:]

    return dcSeq


def ensureFontCase(font):

3 Source : distanceSelector.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def setupCutoff(self, bAts, sAts, cutoff):
        #len(bAts)>len(sAts)
        lenC = len(bAts)
        lenK = len(sAts)
        #set up sum of radii cutoff matrix:
        checkRadii = Numeric.array(bAts.vdwRadius, 'f')
        bigRC = Numeric.resize(checkRadii, (lenC, lenC))
        bigR = bigRC[:lenK]

        keyRadii = Numeric.array(sAts.vdwRadius, 'f')
        keyRadii.shape = (lenK, 1)
        smallR = keyRadii
        cutoff = bigR + smallR
        return cutoff

 
class CloserThanVDWPlusConstantSelector(CloserThanVDWSelector):

3 Source : hydrogenBondBuilder.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def dist(c1, c2):
    d = Numeric.array(c2) - Numeric.array(c1) 
    ans = math.sqrt(Numeric.sum(d*d))
    return round(ans, 3)


def getAngle(ac, hat, don ):

3 Source : molecule.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def dist(a1, a2):
    c1 = array(a1.coords)
    c2 = array(a2.coords)
    d = c2-c1
    return sqrt(sum(d*d))
                  
            
class Molecule(TreeNode):

3 Source : molecule.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def closerThan(self, point, atomList, cut_off, sort=0):
        """ AtomSet   <  - closerThan(point, atomList, cut_off, sort=0)
        Return all atoms of atomList withing cut_off of atom.
        if sort==1 the returned atoms are sorted from closest to furthest
        """
        c1 = array(point)
        c2 = array(atomList.coords)
        diff = c2 - c1
        dist = sum(diff*diff, 1)
        close = less_equal(dist, cut_off*cut_off)
        closeAtoms = take( atomList, nonzero(close) )
        if sort:
            d = take(dist, nonzero(close) )
            closeAtoms = take( closeAtoms, argsort(d) )
        return AtomSet(list(closeAtoms))


    def _atomRadius(self, atom, united=1 ):

3 Source : MolKitNodes.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def setArguments(self, **kw):
        from string import split
        for k,v in kw.items():
            if k not in self.arguments.keys():
                raise RuntimeError (k+' is not a valid argument')
            
            if type(v) in (types.FloatType, types.IntType,
                           types.LongType, types.StringType):
                self.arguments[k] = v
            else:
                pat = re.compile("[\[,\]\012]")
                arrayStr = re.sub(pat, '', str(Numeric.array(v).ravel()) )
                c = split(arrayStr)
                c = map( float, c )
                c = re.sub(pat, '', str(c) )
                self.arguments[k] = c
                
            
class MsmsServer(PublicHttpServer):

3 Source : scorer.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def get_score_array(self):
        """return pairwise score
        """
        # construct 2D array
        array = []
        for at_a in self.ms.get_entities(self.ms.configuration[0]):
            array.append([]) # a new row for every entity in first set
            row = array[-1]
            for at_b in  self.ms.get_entities(self.ms.configuration[1]):
                atom_score = self._f(at_a, at_b)
                row.append(atom_score)
        self.array = Numeric.array(array)
        self.post_process()
        return self.array

    def post_process(self):

3 Source : trilinterp_scorer.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def get_score_array(self):
        array = []
        for at_a in self.ms.get_entities(self.ms.configuration[0]):
            if hasattr(at_a, 'ignore'):
                atom_score = 0
            else:
                atom_score = self._f(at_a)
            array.append(atom_score)
        self.array = Numeric.array(array)
        return self.array
            

    def get_score(self):

0 Source : rng_stats.py
with GNU General Public License v3.0
from Artikash

def average(data):
    data = Numeric.array(data)
    return Numeric.add.reduce(data)/len(data)

def variance(data):

0 Source : rng_stats.py
with GNU General Public License v3.0
from Artikash

def variance(data):
    data = Numeric.array(data)
    return Numeric.add.reduce((data-average(data, axis=0))**2)/(len(data)-1)

def standardDeviation(data):

0 Source : rng_stats.py
with GNU General Public License v3.0
from Artikash

def standardDeviation(data):
    data = Numeric.array(data)
    return Numeric.sqrt(variance(data))

def histogram(data, nbins, range = None):

0 Source : Conformation.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def getCoords(self):
        """Return your coordinates.

        If the coordinates haven't been computed yet,
            then compute, save, and return them.
        Otherwise, return the previously-computed coordinates.
        """
        #FIX THIS: how could it be None? or []?
        if not hasattr(self, 'coords') or self.coords is None or len(self.coords)==0:
            # then compute the coords
            oldCoords = self.mol.allAtoms.coords[:]
            oldConf = self.mol.allAtoms[0].conformation
            self.mol.allAtoms.setConformation(self.mol.stoc.confIndex)
            self.mol.stoc.applyState(self) # !!! attr's must match !!!
            # and save the coords (this makes a real copy of coords)
            self.coords = Numeric.array(self.mol.allAtoms.coords).tolist()
            self.mol.allAtoms.updateCoords(oldCoords, oldConf)
        return self.coords


    def getRMSD(self, refCoords=None, numCoords=None):

0 Source : ConfPlayer.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def updateColor(self,event=None):
        """None  <  -updateColor(mol, event=None)

        makes current molecule coordinates rmstool refCoords
        """
        #print 'in updateColor'
        confNum = self.form.ent2.get()
        #print 'confNum = ', confNum
        if hasattr(self, 'playModeForm'):
            colorType = self.playModeForm.ent3.get()
        else:
            colorType = 'atom'
        #this is already taken care of before
        at0 = self.mol.allAtoms[0]
        has_elec = hasattr(at0, 'estat_energy')
        has_vdw = hasattr(at0, 'vdw_energy')
        has_tot = hasattr(at0, 'total_energy')
        if colorType==None or colorType=='no change':
            return
        try:
            colormap = self.vf.colorMaps['rgb256']
        except:
            print 'setting colormap failed'
            return
        if confNum=='0': 
            if colorType=='molecule':
                self.vf.colorByMolecules(self.mol.allAtoms, ('lines',), topCommand = 0)
            else:
                self.vf.colorByAtomType(self.mol.allAtoms, ('lines',), topCommand = 0)
        elif colorType=='atom':
            self.vf.colorByAtomType(self.mol.allAtoms, ('lines',), topCommand = 0)
        elif colorType=='molecule':
            self.vf.colorByMolecules(self.mol.allAtoms, ('lines',), topCommand = 0)
        elif colorType=='elec_stat' and has_elec:
            val_list = Numeric.array(self.mol.allAtoms.estat_energy)
            mini = min(val_list)
            maxi = max(val_list)
            self.vf.colorByProperty(self.mol.allAtoms, ('lines',),
                'estat_energy',colormap='rgb256',propertyLevel='Atom',
                mini=mini, maxi=maxi, topCommand=0)
        elif colorType=='vdw' and has_vdw:
            val_list = Numeric.array(self.mol.allAtoms.vdw_energy)
            mini = min(val_list)
            maxi = max(val_list)
            self.vf.colorByProperty(self.mol.allAtoms, ('lines',),
                'vdw_energy', colormap='rgb256',propertyLevel='Atom',
                mini=mini, maxi=maxi, topCommand=0)
        elif colorType=='total' and has_tot:
            val_list = Numeric.array(self.mol.allAtoms.total_energy)
            mini = min(val_list)
            maxi = max(val_list)
            self.vf.colorByProperty(self.mol.allAtoms, ('lines',),
                'total_energy',colormap='rgb256',propertyLevel='Atom',
                mini=mini, maxi=maxi, topCommand=0)


#    def buildForm(self, titleStr):
#        #??FIX THIS:
#        mol = self.mol
#        at0 = mol.allAtoms[0]
#        if not titleStr:
#            titleStr = 'Show ' + mol.name + ' Sequence'
#        self.stop = 0
#        if hasattr(self, 'form'):
#            self.form.deiconify()
#            return
#        maxval = len(self.sequenceList)
#        self.doTorsionsOnly = Tkinter.IntVar()
#        self.rmsVar = Tkinter.StringVar()
#        self.rmsVar.set('rms(ref=0) 0.0000')
#        self.energyVar = Tkinter.StringVar()
#        ifd = mol.ifd2 = InputFormDescr(title=titleStr)
#        ifd.append({'name':'energyLab',
#            'widgetType': Tkinter.Label,
#            'textvariable': self.energyVar,
#            'tooltip':'docking and binding energies of current conf',
#            'wcfg':{'bd':4},
#            'gridcfg':{'sticky':'ew', 'columnspan':2}})
#            #'gridcfg':{'sticky':'ew','row':-1, 'column':1}}),
#        ifd.append({'name':'rmsLab',
#            'widgetType': Tkinter.Label,
#            'tooltip':'rms of current conf vs current rms ref conf',
#            'textvariable': self.rmsVar,
#            'wcfg':{'bd':4},
#            'gridcfg':{'sticky':'ew'}}),
#            #'gridcfg':{'sticky':'ew','row':-1, 'column':1}}),
#        colorTypeList = ['atom','molecule', 'no change']
#        #colorTypeList = ['atom','vdw','elec_stat','total','molecule']
#        ifd.append({'widgetType':Pmw.ComboBox,
#                            'name':'colorType',
#                            'tooltip':'used to set coloring scheme for confs',
#                            'wcfg':{'label_text':'Color by',
#		 		                    'entryfield_value':'atom',
#                                    'labelpos':'ew',
#                                    'listheight':'80',
#                                    'scrolledlist_items': colorTypeList,
#				                    'selectioncommand': self.updateColor,
#                                    },
#                            #'gridcfg':{'sticky':'ew'}})
#                            'gridcfg':{'sticky':'ew','row':-1, 'column':1}}),
#        ifd.append({'widgetType':Pmw.Counter,
#			    'name':'statesCounter',
#			    'required':1,
#                'tooltip':'used to show frames via random access',
#			    'wcfg':{#'labelpos': 'n,
#		 		    #'label_text':'conformation:  ',
#                    'autorepeat':0,
#		 		    'entryfield_value':self.idList[0],
#                    'datatype': self.custom_counter,
#		 		    'entry_width':9,
#		 		    'entryfield_validate': self.custom_validate },
#		 	    'gridcfg':{'sticky':'ew', 'columnspan':2}})
#        #ifd.append({'name':'selectCB',
#        #    'widgetType': Tkinter.Checkbutton,
#        #    'tooltip':"open a list showing ids of current conf sequence",
#        #    'text':'show id list',
#        #    'wcfg':{'bd':4},
#        #    'gridcfg':{'sticky':'ew', 'columnspan':1},
#        #    #'gridcfg':{'sticky':'ew', 'columnspan':2},
#        #    'command': self.showStatesList})
#        ifd.append({'name': 'doTransCB',
#            'widgetType': Tkinter.Checkbutton,
#            'text':'torsions only',
#            'tooltip':"show each conf's torsional transformations only",
#            #'text':'transform torsions only',
#            'variable': self.doTorsionsOnly,
#            'wcfg':{'bd':4},
#            'gridcfg':{'sticky':'ew', 'row':-1,'column':1}})
#            ##'gridcfg':{'sticky':'ew', 'columnspan':2}})
#        ifd.append({'name': 'playB',
#            'widgetType': Tkinter.Button,
#            'tooltip':'play from current sequence to last conf',
#            'text':'Play Sequence',
#            'wcfg':{'bd':4},
#            'gridcfg':{'sticky':'ew','columnspan':1},
#            'command':self.Play_cb})
#        ifd.append({'name': 'playRevB',
#            'widgetType': Tkinter.Button,
#            'tooltip':'play from current sequence to input conf',
#            'text':'Play it Reverse',
#            'wcfg':{'bd':4},
#            'gridcfg':{'sticky':'ew','row':-1, 'column':1},
#            'command':self.PlayRev_cb})
#        ifd.append({'name': 'stopB',
#            'widgetType': Tkinter.Button,
#            'text':'Stop',
#            'tooltip':'stop and reset to input conf',
#            'wcfg':{'bd':4},
#            'gridcfg':{'sticky':'ew'},
#            'command':self.Stop_cb})
#        ifd.append({'name': 'pauseB',
#            'widgetType': Tkinter.Button,
#            'tooltip':'pause at current conf',
#            'text':'Pause',
#            'wcfg':{'bd':4},
#            'gridcfg':{'sticky':'ew','row':-1, 'column':1},
#            'command':self.Pause_cb})
#        ifd.append({'name': 'rmsB',
#            'widgetType': Tkinter.Button,
#            'tooltip':'makes current conf rms ref',
#            'text':'Make rms refcoords',
#            'wcfg':{'bd':4},
#            'gridcfg':{'sticky':'ew'},
#            'command':self.MakeRef_cb})
#        ifd.append({'name': 'buildB',
#            'widgetType': Tkinter.Button,
#            'tooltip':'builds new molecule with current conf coords',
#            'text':'Build',
#            'wcfg':{'bd':4},
#            'gridcfg':{'sticky':'ew','row':-1, 'column':1},
#            'command':self.Build_cb})
#        ifd.append({'name':'selectCB',
#            'widgetType': Tkinter.Checkbutton,
#            'text':'Show IdList',
#            'tooltip':"open a list showing ids of current conf sequence",
#            'wcfg':{'bd':4},
#            'gridcfg':{'sticky':'ew', 'columnspan':1},
#            #'gridcfg':{'sticky':'ew', 'columnspan':2},
#            'command': self.showStatesList})

#        ifd.append({'name': 'closeB',
#            'widgetType': Tkinter.Button,
#            'tooltip':'closes player',
#            'text':'Close',
#            'wcfg':{'bd':4},
#            'gridcfg':{'sticky':'ew', 'columnspan':2},
#            'command':self.Close_cb})
#        form = self.vf.getUserInput(ifd, modal=0,blocking=0)
#        form.root.protocol('WM_DELETE_WINDOW',CallBackFunction(self.Close_cb,mol))

#        form.ifd = ifd
#        ctr = ifd.entryByName['statesCounter']['widget']
#        entF = ctr.component('entryfield')
#        form.ent2 = entF._entryFieldEntry
#        da = ctr.component('downarrow')
#        ua = ctr.component('uparrow')
#        for item in [da,ua]:
#            item.bind(' < ButtonPress-1>', self.SetState_cb, '+')
#        form.ent2.bind(' < Return>', self.SetState_cb, '+')
#        form.counter = form.ifd.entryByName['statesCounter']['widget']
#        form.showList = form.ifd.entryByName['selectCB']['widget']
#        form.showVar = form.ifd.entryByName['selectCB']['variable']
#        ctr2 = ifd.entryByName['colorType']['widget']
#        entF2 = ctr2.component('entryfield')
#        #all this to get a handle to the Tkinter.Entry buried in the pww
#        form.ent3 = entF2._entryFieldEntry
#        form.ent3.bind(' < Return>', self.updateColor, '+')
#        form.ent3.config(width=8)

#        #copied lines:
#        form.playB = form.ifd.entryByName['playB']['widget']
#        form.playRevB = form.ifd.entryByName['playRevB']['widget']
#        #set up link to balloon help which needs to change, also
#        form.playTT = form.ifd.entryByName['playB']['balloon']
#        form.playRevTT = form.ifd.entryByName['playRevB']['balloon']
#        if self.hasCounter:
#            ctr = ifd.entryByName['statesCounter']['widget']
#            entF = ctr.component('entryfield')
#            form.ent2 = entF._entryFieldEntry
#            da = ctr.component('downarrow')
#            ua = ctr.component('uparrow')
#            for item in [da,ua]:
#                item.bind(' < ButtonPress-1>', self.SetState_cb, '+')
#            form.ent2.bind(' < Return>', self.SetState_cb, '+')
#            form.counter = form.ifd.entryByName['statesCounter']['widget']
#        #print 'returning form'
#        return form


    def MakeRef_cb(self, event=None):

0 Source : ConfPlayer.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def updateColor(self,event=None):
        """None  <  -updateColor(mol, event=None)

        makes current molecule coordinates rmstool refCoords
        """
        #print 'in updateColor'
        confNum = self.form.ent2.get()
        #print 'confNum = ', confNum
        if hasattr(self, 'playModeForm'):
            colorType = self.playModeForm.ent3.get()
        else:
            colorType = 'atom'
        #this is already taken care of before
        at0 = self.mol.allAtoms[0]
        has_elec = hasattr(at0, 'estat_energy')
        has_vdw = hasattr(at0, 'vdw_energy')
        has_tot = hasattr(at0, 'total_energy')
        if colorType==None or colorType=='no change':
            return
        try:
            colormap = self.vf.colorMaps['rgb256']
        except:
            print 'setting colormap failed'
            return
        if confNum=='0': 
            if colorType=='molecule':
                self.vf.colorByMolecules(self.mol.allAtoms, ('lines',), topCommand = 0)
            else:
                self.vf.colorByAtomType(self.mol.allAtoms, ('lines',), topCommand = 0)
        elif colorType=='atom':
            self.vf.colorByAtomType(self.mol.allAtoms, ('lines',), topCommand = 0)
        elif colorType=='molecule':
            self.vf.colorByMolecules(self.mol.allAtoms, ('lines',), topCommand = 0)
        elif colorType=='elec_stat' and has_elec:
            val_list = Numeric.array(self.mol.allAtoms.estat_energy)
            mini = min(val_list)
            maxi = max(val_list)
            self.vf.colorByProperty(self.mol.allAtoms, ('lines',),
                'estat_energy',colormap='rgb256',propertyLevel='Atom',
                mini=mini, maxi=maxi, topCommand=0)
        elif colorType=='vdw' and has_vdw:
            val_list = Numeric.array(self.mol.allAtoms.vdw_energy)
            mini = min(val_list)
            maxi = max(val_list)
            self.vf.colorByProperty(self.mol.allAtoms, ('lines',),
                'vdw_energy', colormap='rgb256',propertyLevel='Atom',
                mini=mini, maxi=maxi,topCommand=0)
        elif colorType=='total' and has_tot:
            val_list = Numeric.array(self.mol.allAtoms.total_energy)
            mini = min(val_list)
            maxi = max(val_list)
            self.vf.colorByProperty(self.mol.allAtoms, ('lines',),
                'total_energy',colormap='rgb256',propertyLevel='Atom',
                mini=mini, maxi=maxi,topCommand=0)



    def updateSortList(self, event=None):

0 Source : DlgFilters.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def __init__(self, receptor_file):
        from PyBabel.babelElements import babel_elements
        self.babel_elements = babel_elements
        self.criteria = "Interactions"  
        Filter.__init__(self, self.criteria)
        self.receptor_file = receptor_file
        rptr = open(receptor_file)
        rec_lines = rptr.readlines()
        rptr.close()
        rec_coords =[]
        rec_vdw_rad =[]
        for ll in rec_lines:
            if ll.find("HETATM")>-1 or ll.find("ATOM")>-1:
                rec_coords.append([float(ll[30:38]), float(ll[38:46]),float(ll[46:54])])
                be_key = strip(ll[76:])
                if be_key=='A':
                    be_key = 'C'
                elif be_key=='OA':
                    be_key = 'O'
                elif be_key=='NA':
                    be_key = 'N'
                elif be_key=='SA':
                    be_key = 'S'
                elif be_key=='HD':
                    be_key = 'H'
                rec_vdw_rad.append(babel_elements[be_key]['vdw_rad'])
        # lenC and bigC are about the receptor...
        self.lenC = len(rec_vdw_rad)
        lenC = self.lenC
        #len(rec_vdw_rad)
        #1844
        #len(rec_coords)
        #1844
        checkRadii = Numeric.array(rec_vdw_rad, 'f')
        self.bigRC = Numeric.resize(checkRadii, (lenC, lenC)) #receptor info
        self.bigC = Numeric.resize(rec_coords, (lenC,lenC,3))
        ###bigR = bigRC[:lenK]
        

    def setup_ligand(self, lig_lines):

0 Source : DlgFilters.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def setup_ligand(self, lig_lines):
        lig_coords = []
        first_lig = False
        if not hasattr(self, 'lig_vdw_rad'):
            self.lig_vdw_rad = []
            first_lig = True
        for ll in lig_lines:
            #THESE LINES START WITH 'DOCKED: ' so indices +8
            if ll.find("HETATM")>-1 or ll.find("ATOM")>-1:
                lig_coords.append([float(ll[38:46]), float(ll[46:54]),float(ll[54:62])])
                #lig_coords.append([float(ll[30:38]), float(ll[38:46]),float(ll[46:54])])
                if first_lig: 
                    #indices  +8
                    be_key = strip(ll[84:])
                    if be_key=='A':
                        be_key = 'C'
                    elif be_key=='OA':
                        be_key = 'O'
                    elif be_key=='NA':
                        be_key = 'N'
                    elif be_key=='SA':
                        be_key = 'S'
                    elif be_key=='HD':
                        be_key = 'H'
                    self.lig_vdw_rad.append(self.babel_elements[be_key]['vdw_rad'])
        self.lig_coords = lig_coords
        self.smallM = Numeric.array(lig_coords, 'f')
        #setup variables for ligand arrays
        if first_lig:
            self.lenK=len(lig_coords)
            self.keyRadii = Numeric.array(self.lig_vdw_rad, 'f')
            self.keyRadii.shape = (self.lenK,1)
        self.smallM.shape = (self.lenK,1,3)

        

    def filter(self, dlg):

0 Source : DlgParser.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def makeModel(self, lines):
        coords = []
        vdW = []
        Elec = []
        d = {}
        corr = 0
        if hasattr(self, 'outlev') and self.outlev==-1:
            corr = -1
        binding_energy2 = None
        version = self.version
        for l in lines:
            ll = split(l)
            #if find(l, 'MODEL')>-1:
            #    d['num'] = int((ll)[1])
            if find(l, 'Run')>-1 and find(l, 'Rank')==-1:
                d['run'] = int((ll)[3])
            elif find(l, 'Estimated Free Energy of Binding')>-1:
                d['binding_energy'] = float((ll)[7])
                if version>=4.0: d['energy'] = float((ll)[7])
            elif find(l, 'vdW + Hbond + desolv Energy')>-1:
                d['vdw_hb_desolv_energy'] = float((ll)[8])
            elif find(l, 'Electrostatic Energy')>-1:
                if (ll[1] == 'Electrostatic'):
                    d['electrostatic_energy'] = float((ll)[4])
                elif (ll[1] == 'Intermol.'):
                    d['electrostatic_energy'] = float((ll)[5])
            elif find(l, 'Moving Ligand-Fixed Receptor')>-1:
                d['moving_ligand_fixed_receptor'] = float((ll)[5])
            elif find(l, 'Moving Ligand-Moving Receptor')>-1:
                d['moving_ligand_moving_receptor'] = float((ll)[5])
            elif find(l, 'Total Internal Energy')>-1:
                d['total_internal'] = float((ll)[7])
            elif find(l, 'Internal Energy Ligand')>-1:
                d['ligand_internal'] = float((ll)[5])
            elif find(l, 'Internal Energy Receptor')>-1:
                d['receptor_internal'] = float((ll)[5])
            elif find(l, 'Torsional Free Energy')>-1:
                d['torsional_energy'] = float((ll)[6])
            elif find(l, 'Estimated Inhibition Constant')>-1:
                if find(l, 'N/A')   <   0:
                    d['inhib_constant'] = float((ll)[6])
                    if version>=4.0:
                        d['inhib_constant_units'] = ll[7]
            elif find(l, 'Final Docked Energy')>-1:
                d['docking_energy'] = float((ll)[5])
            elif find(l, 'Final Intermolecular Energy')>-1:
                d['intermol_energy'] = float((ll)[6])
            elif find(l, 'Final Internal Energy of Ligand')>-1:
                d['internal_energy'] = float((ll)[8])
            elif find(l, 'Final Internal Energy')>-1:
                d['internal_energy'] = float((ll)[6])
            elif find(l, 'Torsional Free Energy')>-1:
                d['torsional_energy'] = float((ll)[6])
            elif find(l, 'NEWDPF tran0')>-1:
                d['trn_x'] = float(ll[3])
                d['trn_y'] = float(ll[4])
                d['trn_z'] = float(ll[5])
            elif find(l, 'NEWDPF quat0')>-1:
                d['qtn_nx'] = float(ll[3])
                d['qtn_ny'] = float(ll[4])
                d['qtn_nz'] = float(ll[5])
                d['qtn_ang_deg'] = float(ll[6])
            elif find(l, 'NEWDPF quaternion0')>-1:
                d['quaternion_nx'] = float(ll[3])
                d['quaternion_ny'] = float(ll[4])
                d['quaternion_nz'] = float(ll[5])
                d['quaternion_nw'] = float(ll[6])
            elif find(l, 'NEWDPF dihe0')>-1:
                angList = []
                for n in ll[3:]:
                    angList.append(float(n))
                d['torsion_values'] = angList
                d['num_torsions'] = len(angList)
            elif find(l, 'Intermol. vdW + Hbond Energy ')>-1:
                #AD4 specific model information:
                # USER         Intermol. vdW + Hbond Energy   =  -14.63 kcal/mol
                d['vdw_energy'] = float((ll)[7])
            elif find(l, 'Intermol. Electrostatic Energy')>-1:
                #USER         Intermol. Electrostatic Energy =   -0.62 kcal/mol
                d['estat_energy'] = float((ll)[5])
            elif find(l, '(3) Torsional Free Energy')>-1:
                #USER    (3) Torsional Free Energy           =   +3.84 kcal/mol
                d['torsional_energy'] = float((ll)[6])
            elif find(l, "(4) Unbound System's Energy")>-1:
                #USER    (4) Unbound System's Energy         =   -0.85 kcal/mol
                try:
                    d['unbound_energy'] = float((ll)[7])
                except:
                    d['unbound_energy'] = float((ll)[6])
            elif find(l, 'ATOM')>-1:
                coords.append([float(l[30:38]),float(l[38:46]),float(l[46:54])])
                try:
                    vdW.append(float(l[54:60]))
                except:
                    #print 'vdw:', l[54:60], ' RAISED!'
                    vdW.append(0.0)
                try:
                    Elec.append(float(l[60:66]))
                except:
                    #print 'estat:', l[60:66], ' RAISED!'
                    Elec.append(0.0)
                if len(l)>77:
                    try:
                        binding_energy2 = float(l[70:76])
                    except:
                        pass
            elif find(l, 'HETA')>-1:
                coords.append([float(l[30:38]),float(l[38:46]),float(l[46:54])])
                try:
                    vdW.append(float(l[54:60]))
                except:
                    vdW.append(0.0)
                try:
                    Elec.append(float(l[60:66]))
                except:
                    Elec.append(0.0)
            d['coords'] = coords
            d['vdw_energies'] = vdW
            d['estat_energies'] = Elec
            d['total_energies'] = Numeric.array(Numeric.array(vdW)+Numeric.array(Elec)).tolist()
            if binding_energy2 and not d.has_key('binding_energy'):
                d['binding_energy'] = binding_energy2
                d['docking_energy'] = binding_energy2
        return d



0 Source : energyCalculator.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def dist(self, a, b):
        """return distance between two atoms, a and b.
        """
        d = Numeric.array(b.coords) - Numeric.array(a.coords)
        return sqrt(Numeric.sum(d*d))

                        

    #def _get_energy_custom(self, a, b):
    #    """return energy between two atoms, a and b.
    #    """
    #    ax = self.data.index(a)
    #    bx = self.data.index(b)
#
#        if self.energy_matrix[ax][bx] >= 0.0:
#            # return previously saved energy
#            return self.energy_matrix[ax][bx]
#        else:
#            # compute, save, and return energy
#            #FIX THIS
#            dist = a.getRMSD_custom(b.getCoords())
#            self.energy_matrix[ax][bx] = self.energy_matrix[bx][ax] = dist
#            return dist


    def get_energy(self, a, b):

0 Source : InteractionDetector.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def detectPiInteractions(self, tolerance=0.95, debug=False, use_all_cycles=False):
        if debug: print "in detectPiInteractions"
        self.results['pi_pi'] = []        #stacked rings...?
        self.results['t_shaped'] = []     #one ring perpendicular to the other
        self.results['cation_pi'] = []    #
        self.results['pi_cation'] = []    #
        self.results['macro_cations'] = []#
        self.results['lig_cations'] = []  #
        #at this point have self.results
        if not len(self.results['lig_close_atoms']):
            return
        lig_atoms = self.results['lig_close_atoms'].parent.uniq().atoms
        macro_res = self.results['macro_close_atoms'].parent.uniq()
        if not len(macro_res):
            return
        macro_atoms = macro_res.atoms
        l_rf = RingFinder()
        #Ligand
        l_rf.findRings2(lig_atoms, lig_atoms.bonds[0])
        #rf.rings is list of dictionaries, one per ring, with keys 'bonds' and 'atoms'
        if debug: print "LIG: len(l_rf.rings)=", len(l_rf.rings)
        if not len(l_rf.rings):
            if debug: print "no lig rings found by l_rf!"
            return
        acbs = self.aromatic_cycle_bond_selector
        #acbs = AromaticCycleBondSelector()
        lig_rings = []
        for r in l_rf.rings:
            ring_bnds = r['bonds']
            if use_all_cycles: 
                lig_rings.append(ring_bnds)
            else:
                arom_bnds = acbs.select(ring_bnds)
                if len(arom_bnds)>4:
                    lig_rings.append(arom_bnds)
        if debug: print "LIG: len(lig_arom_rings)=", len(lig_rings)
        self.results['lig_rings'] = lig_rings
        self.results['lig_ring_atoms'] = AtomSet()
        #only check for pi-cation if lig_rings exist
        if len(lig_rings):
            macro_cations = self.results['macro_cations'] = self.getCations(macro_atoms)
            macro_cations = macro_cations.get(lambda x: x.element!='H')
            lig_ring_atoms = AtomSet()
            u = {}
            for r in lig_rings:
                for a in BondSet(r).getAtoms():
                    u[a] = 1
            if len(u): 
                lig_ring_atoms = AtomSet(u.keys())
                lig_ring_atoms.sort()
                self.results['lig_ring_atoms'] = lig_ring_atoms
            if len(macro_cations):
                if debug: print "check distances from lig_rings to macro_cations here"
                #macro cations->lig rings
                pairDict2 = self.distanceSelector.select(lig_ring_atoms,macro_cations)
                z = {}
                for key,v in pairDict2.items():
                    val = v.tolist()[0]
                    if val in macro_cations:
                        z[val] = [key]
                if len(z):
                    self.results['pi_cation'] = (z.items())
                else:
                    self.results['pi_cation'] = []
        #check the distance between the rings and the macro_cations
        self.results['lig_cations'] = self.getCations(lig_atoms)
        lig_cations = self.results['lig_cations'] 
        #remove hydrogens
        lig_cations = lig_cations.get(lambda x: x.element!='H')
        #Macromolecule
        m_rf = RingFinder()
        m_rf.findRings2(macro_res.atoms, macro_res.atoms.bonds[0])
        #rf.rings is list of dictionaries, one per ring, with keys 'bonds' and 'atoms'
        if debug: print "MACRO: len(m_rf.rings)=", len(m_rf.rings)
        if not len(m_rf.rings):
            if debug: print "no macro rings found by m_rf!"
            return
        macro_rings = []
        for r in m_rf.rings:
            ring_bnds = r['bonds']
            if use_all_cycles: 
                macro_rings.append(ring_bnds)
            else:
                arom_bnds = acbs.select(ring_bnds)
                if len(arom_bnds)>4:
                    macro_rings.append(arom_bnds)
        if debug: print "len(macro_arom_rings)=", len(macro_rings)
        self.results['macro_rings'] = macro_rings
        self.results['macro_ring_atoms'] = AtomSet()
        #only check for pi-cation if macro_rings exist
        if len(macro_rings):
            macro_ring_atoms = AtomSet()
            u = {}
            for r in macro_rings:
                for a in BondSet(r).getAtoms(): #new method of bondSets
                    u[a] = 1
            if len(u):
                macro_ring_atoms = AtomSet(u.keys())
                macro_ring_atoms.sort()
                self.results['macro_ring_atoms'] = macro_ring_atoms
            if len(lig_cations):
                if debug: print "check distances from macro_rings to lig_cations here"
                pairDict3 = self.distanceSelector.select(macro_ring_atoms,lig_cations)
                z = {}
                for x in pairDict3.items():
                    #lig cations->macro rings
                    z.setdefault(x[1].tolist()[0], []).append(x[0])
                if len(z):
                    self.results['cation_pi'] = (z.items())
                else:
                    self.results['cation_pi'] = []
                #macro_pi_atoms = AtomSet(pairDict3.keys())
                #l_cations = AtomSet()
                #for v in pairDict3.values():
                #    for x in v:
                #        l_cations.append(x)
                #self.results['cation_pi'] = pairDict3.items()
                #self.results['cation_pi'] = (l_cations, macro_pi_atoms)
        #check for intermol distance   <  6 Angstrom (J.ComputChem 29:275-279, 2009)
        #compare each lig_ring vs each macro_ring
        for lig_ring_bnds in lig_rings:
            lig_atoms = acbs.getAtoms(lig_ring_bnds)
            lig_atoms.sort()
            if debug: print "len(lig_atoms)=", len(lig_atoms)
            #---------------------------------
            # compute the normal to lig ring
            #---------------------------------
            a1 = Numeric.array(lig_atoms[0].coords)
            a2 = Numeric.array(lig_atoms[2].coords)
            a3 = Numeric.array(lig_atoms[4].coords)
            if debug: print "a1,a2, a3=", a1.tolist(), a2.tolist(), a3.tolist()
            for macro_ring_bnds in macro_rings:
                macro_atoms = acbs.getAtoms(macro_ring_bnds)
                macro_atoms.sort()
                if debug: print "len(macro_atoms)=", len(macro_atoms)
                pD_dist = self.distanceSelectorWithCutoff.select(macro_ring_atoms, lig_atoms, cutoff=self.dist_cutoff)
                if not len(pD_dist[0]):
                    if debug: 
                        print "skipping ligand ring ", lig_rings.index(lig_ring_bnds), " vs ",
                        print "macro ring", macro_rings.index(macro_ring_bnds)
                    continue
                #---------------------------------
                # compute the normal to macro ring
                #---------------------------------
                b1 = Numeric.array(macro_atoms[0].coords)
                b2 = Numeric.array(macro_atoms[2].coords)
                b3 = Numeric.array(macro_atoms[4].coords)
                if debug: print "b1,b2, b3=", b1.tolist(), b2.tolist(), b3.tolist()
                # check for stacking 
                a2_1 = a2-a1
                a3_1 = a3-a1
                b2_1 = b2-b1
                b3_1 = b3-b1
                if debug: print "a2_1 = ", a2-a1
                if debug: print "a3_1 = ", a3-a1
                if debug: print "b2_1 = ", b2-b1
                if debug: print "b3_1 = ", b3-b1
                n1 = crossProduct(a3_1,a2_1) #to get the normal for the first ring
                n2 = crossProduct(b3_1,b2_1) #to get the normal for the second ring
                if debug: print "n1=", n1
                if debug: print "n2=", n2
                n1 = Numeric.array(n1)
                n2 = Numeric.array(n2)
                n1_dot_n2 = Numeric.dot(n1,n2)
                if debug: print "n1_dot_n2", Numeric.dot(n1,n2)
                if abs(n1_dot_n2) >= 1*tolerance: 
                    if debug: print "The rings are stacked vertically" 
                    new_result = (acbs.getAtoms(lig_ring_bnds), acbs.getAtoms(macro_ring_bnds))
                    self.results['pi_pi'].append(new_result)
                if abs(n1_dot_n2)  < = 0.01*tolerance: 
                    if debug: print "The rings are stacked perpendicularly" 
                    new_result = (acbs.getAtoms(lig_ring_bnds), acbs.getAtoms(macro_ring_bnds))
                    self.results['t_shaped'].append(new_result)


    def get_pi_pi(self, print_ctr=1, comment="USER AD> "):

0 Source : MoleculePreparation.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def findNearest(self, atom, bonded_atoms):
        lenK = len(bonded_atoms)
        lenC = 1
        nonbonded_atoms = AtomSet([atom])
        c = Numeric.array(nonbonded_atoms.coords, 'f')
        k = Numeric.array(bonded_atoms.coords, 'f')
        bigK = Numeric.resize(k, (lenK, lenK, 3))
        c.shape = (1, 1, 3)
        bigM = bigK[:1]
        d = bigM - c
        dSQ = d*d
        dSQMAT = Numeric.sum(dSQ, 2)
        mm = dSQMAT[0][0]
        mindex = 0
        for i in range(lenK):
            if dSQMAT[0][i]  <  mm:
                mm = dSQMAT[0][i]
                mindex = i
        #print "found closest atom %d at dist %f" %( mindex, mm)
        return bonded_atoms[mindex]



class ReceptorPreparation(AutoDockMoleculePreparation):

0 Source : pixelMap2D.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def __init__(self, results, master=None, mini=None, maxi=None, 
                    cmap=None, cmap_name='cmap', ramp=None, npixels=10):
        assert isinstance(results, type(Numeric.array(range(4))))
        assert len(results.shape)==2
        # a copy of the input array is used
        self.results = Numeric.array(results[:])
        self.results = results
        self.master = master
        #for a Numeric array,
        self.x_number = results.shape[0]   #number of rows 
        self.y_number = results.shape[1]   #number of columns
        self.results = results
        self.npixels = npixels
        if mini is None:
            mini=min(results.ravel())
        else:
            for x in xrange(self.x_number):
                for y in xrange(self.y_number):
                    if self.results[x][y]  <  mini:
                        self.results[x][y]=mini
        self.mini = mini
        if maxi is None:
            maxi=max(results.ravel())
        else:
            for x in xrange(self.x_number):
                for y in xrange(self.y_number):
                    if self.results[x][y]>maxi:
                        self.results[x][y]=maxi
        self.maxi = maxi
        self.cmap = cmap 
        if cmap is None:
            if ramp is None:
                ramp = RedWhiteRamp()
            self.cmap = ColorMap(cmap_name, mini=mini, maxi=maxi, ramp=ramp)

    def show_image(self):

0 Source : prepare_covalent_flexres.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

def setRelativeTorsion(atom1, atom2, angle): #mov_atoms=None):
    #rat1, rat2, ??30degrees??
    mol = atom1.top
    if mov_atoms is None:
        mov_atoms = mol.subTree(atom1, atom2, mol.allAtoms)
    assert len(mov_atoms)
    mov_coords = Numeric.array(mov_atoms.coords)
    lenCoords = len(mov_coords)
    x = Numeric.array(atom1.coords)
    y = Numeric.array(atom2.coords)
    rot = (angle * 3.14159/180.)%(2 * Numeric.pi)
    matrix = rotax(x, y, rot)
    _ones = Numeric.ones(lenCoords, 'f')
    _ones.shape = (lenCoords,1)
    mov_coords = Numeric.concatenate((mov_coords, _ones),1)
    newcoords = Numeric.dot(mov_coords, matrix)
    nc = newcoords[:,:3].astype('f')
    for i in range(lenCoords):
        at = mov_atoms[i]
        at._coords[at.conformation] = nc[i].tolist()



if __name__ == '__main__':

0 Source : graphtool.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def caluculate_ramp(self):
        """ 
        """
        dramp=[] 
        mypoints=[]
        mynewpoints=[]
        self.oldpoints.sort()
        calcpoints=[]
        #if self.continuous :
        if hasattr(self,"curx"):
                if (self.curx,self.cury) not in self.oldpoints and (self.curx,self.cury) not in [self.startpoint,self.endpoint]:
                    calcpoints.append((self.curx,self.cury))
        if len(self.oldpoints)!=0:
            for o in self.oldpoints:
                if o not in calcpoints:
                    calcpoints.append(o)
        if self.startpoint not in calcpoints:
                calcpoints.append(self.startpoint)
        if self.endpoint not in calcpoints:
                calcpoints.append(self.endpoint)
        
        calcpoints.sort()    
        length=len(calcpoints)
        for l in range(length):
            if l+1  <  =length-1:
                mypoints=[calcpoints[l],calcpoints[l+1]]
                if calcpoints[l] not in mynewpoints:
                    mynewpoints.append( calcpoints[l])   
                
                (x1,y1)=calcpoints[l]
                (x2,y2)=calcpoints[l+1]
                if x1>x2:
                    dcx=x1-x2
                    px=x1-1
                else:
                    dcx=x2-x1
                    px=x1+1
                if y1>y2:
                    dcy=y1-y2
                    if dcx>=1:
                        py=y1-float(dcy)/float(dcx)
                    else:
                        py=y1
                else:   
                    dcy=y2-y1
                    if dcx>=1:
                        py=y1+float(dcy)/float(dcx)
                    else:
                        py=y2
                mynewpoints.append( (px,int(round(py))))
                for dc in range(dcx-1):
                    
                    if x1>x2:
                        px=px-1
                    else:
                        px=px+1
                    if y1>y2:
                        if dcx>=1:
                            py=py-float(dcy)/float(dcx)
                        else:
                            py=y1
                    else:
                        if dcx>=1:
                            py=py+float(dcy)/float(dcx)
                        else:
                            py=y2
                    mynewpoints.append( (px,int(round(py))))
        ramp=[]
        for r in mynewpoints:
            #scale
            ra=float(275-r[1])
            if ra>=256:
                ra=255.0
            ramp.append(ra)
            dramp=Numeric.array(ramp,'f')
        if len(dramp)!=0:
            return   dramp     
        else:
            dramp=Numeric.arange(0,256,1,'f')
            return   dramp
        
    def get(self):

0 Source : tablemaker.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def load_file(self, file):
        from string import split, atoi
        of = open(file, 'r')
        line = split(of.readline())
        warning = "Warning: wrong file format. Could not read file %s" %(file,)
        if len(line):
            if line[0] != "Transfer":
                of.close()
                if self.load_file_old(file):
                    return
                else:
                    print warning
                return
        else:
            of.close()
            print warning
            return
        ymaxval = 0
        while(1):
            line = of.readline()
            line = split(line)
            if len(line):
                if line[0] == "End": break
                else:
                    if line[0] == "NumIntervals":
                        nintervals = atoi(line[1])
                    elif line[0] == "Intervals":
                        intervals_str= line[1:]
                    elif line[0] == "DataSizes":
                        sizes_str = line[1:]
                    elif line[0] == "Maxalpha":
                        ymaxval = atoi(line[1])
        
        intervals = []
        sizes = []
        for n in range(nintervals):
            intervals.append( (atoi(intervals_str[n*2]),
                                    atoi(intervals_str[n*2+1]) ))
            sizes.append( (atoi(sizes_str[n*3]),
                           atoi(sizes_str[n*3+1]),
                           atoi(sizes_str[n*3+2])) )
        #print "nintervals: ", nintervals
        #print "intervals: ", intervals
        #print "sizes: ", sizes
        
        data = []
        xmaxval = intervals[nintervals-1][1]
        if xmaxval != self.xmaxval:
            if self.viewer.hasGui:
                text = "WARNING: number of LUT entries in\n%s\n is %d,\n current number of LUT entries is %d.\nLoad new LUT?" %(file,xmaxval+1,self.xmaxval+1)
                dialog = Pmw.MessageDialog(self.master,
                                           buttons=('OK','Cancel'),
                                           defaultbutton='OK',
                                           title='Load New LUT',
                                           message_text=text)
                result=dialog.activate()
                if result=='Cancel':
                    of.close()
                    return
                else:
                    self.xmaxval = xmaxval
            else:
                print "WARNING: number of LUT entries in %s is %d, current number of LUT entries is %d." % (file, xmaxval+1, self.xmaxval+1)

        shapes = []
        values = []
        alphas = []
        colors = []
        from struct import unpack, calcsize
        for n in range(nintervals):
            fmt_shapes = ">%di"%sizes[n][0]
            fmt_values = ">%di"%sizes[n][1]
            fmt_colors = ">%df"%sizes[n][2]
            l_shapes = of.read(calcsize(fmt_shapes))
            #values and alphas have the same format
            l_values= of.read(calcsize(fmt_values))
            l_alphas = of.read(calcsize(fmt_values))
            l_colors = of.read(calcsize(fmt_colors))
            shapes.append(list(unpack(fmt_shapes, l_shapes)))
            values.append(unpack(fmt_values, l_values))
            alphas.append(unpack(fmt_values, l_alphas))
            colors.append(unpack(fmt_colors, l_colors))
        #print 'shapes:', shapes    
        #print 'values: ', values
        #print 'alphas: ', alphas
        
        of.close()
        d = 1
        if ymaxval:
##              d = (ymaxval*1.0)/self.ymaxval
            self.ymaxval = ymaxval
        #print "ymaxval: ", ymaxval, "self.ymaxval: ", self.ymaxval
        self.xmaxval = xmaxval
        for canvas in self.canvas_list:
            canvas.destroy()
        self.canvas_list = []
        self.lut_list = []
        self.intervals_list = intervals
        i = 0
        for interval in intervals:
##              print 'in load_file: interval =', interval
            lut = LUT(self.f1, xminval=interval[0],
                      xmaxval=interval[1], ymaxval = self.ymaxval,
                      grid_row=i,
                      num_of_entries=xmaxval+1, initdraw = 0)
            lut.canvas.bind('  <  Button-1>', self.selected)
            self.lut_list.append(lut)
            self.canvas_list.append(lut.canvas)
            if d != 1 :
                lut.calculate_points(values[i],
                                     map(lambda x: x/d, alphas[i]))
            else:
                lut.calculate_points(values[i], alphas[i])
            lut.shapes = shapes[i]
            colors_size = (len(colors[i])/3, 3)
            #print "colors_size: ", len(colors[i]), colors_size
            lut.color_arr = Numeric.reshape(Numeric.array(colors[i], 'f'),
                                            colors_size)
            lut.calculate_alphas()
            lut.redraw()
            lut.setCallbacks(self.lutcallbacks)
            lut.callbacks['setalpha']([interval[0], lut.alpha_arr])
            lut.callbacks['setcolor']([interval[0], lut.color_arr])
            i = i + 1
        self.lut_list[0].canvas.itemconfigure('outline', outline='blue')
        self.with_focus = self.lut_list[0]
        if len(intervals)>1:
            self.editBtn.menu.entryconfigure("Merge function", state='normal')
 
    def saveData(self):

0 Source : tablemaker.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def mouse2Down(self, event):
        
        c= self.canvas
        points = self.points
        self.lastx = c.canvasx(event.x)
        self.lasty = c.canvasy(event.y)
        tag = c.gettags(Tkinter.CURRENT)[1]
        curr_ind = int(tag[3:])
        shapes = self.shapes
        
        # find all points of selected shape & store them in select_shape
        i=0
        for shape in shapes:
            if curr_ind   <  = shape: break
            i=i+1
        l_shape = shapes[i-1]
        r_shape = shapes[i+1]
        if (shape-l_shape) > 1:
            select_shape = range(l_shape,shape+1)
        elif (r_shape-shape) >1:
            select_shape = range(shape, r_shape+1)
        # find coords of adjoining points of the shapes next to selected one
        next_l = select_shape[0]-1
        next_r = select_shape[-1]+1
        self.next_l = points[next_l][0]
        self.next_r = points[next_r][0]
        first_point = select_shape[0]
        
        # find distance between event.x and first and last points of shape
        rad = self.dotrad
        self.diffr = points[select_shape[-1]][0]+rad-self.lastx
        self.diffl = self.lastx-(points[first_point][0]-rad)
        self.firstx = self.lastx
                
        # calculate alphas, colors
        first_scal = self.values[select_shape[0]]
        last_scal = self.values[select_shape[-1]]

        # get alphas(colors) for every entry(scalar) in LUT in interval between
        # first and last points of the selected shape
        xminval = self.xminval
        if not(self.last_event == 'ButtonRelease-2'\
           and select_shape == self.select_shape):
            #list of alphas of the shape
            self.alpha_list = list(self.alpha_arr[first_scal-xminval:
                                                 last_scal-xminval+1])
            #color arrays of the shape
##              self.rgb = (self.color_arr[first_scal-xminval:
##                                         last_scal+1-xminval]*1).astype('f')
            self.rgb = Numeric.array(self.color_arr[first_scal-xminval:
                                       last_scal+1-xminval])
            
                
        # memorize initial value(scalar) of the first point 
        self.old_valx1 = first_scal
        #c.itemconfig('selected', outline='')
        c.itemconfig('selected', outline=UNSELECTED_COLOR)
        ##  c.itemconfig('selected', fill=UNSELECTED_COLOR,
##                       outline=UNSELECTED_COLOR)
        c.dtag('selected')
        c.addtag_withtag('selected', Tkinter.CURRENT)
        c.itemconfig('selected', outline=SELECTED_COLOR)
        ##  c.itemconfig('selected', fill=SELECTED_COLOR, outline=SELECTED_COLOR)
        # get color of current poit
        curr_scal = self.values[curr_ind]-xminval
        curr_color = list(self.color_arr[curr_scal])
        curr_hsv = ToHSV(curr_color)
        #print "curr_hsv in mouse2Down:", curr_hsv
        self.select_shape = select_shape
        self.counter = 0
        self.curr_ind = curr_ind
        self.last_event = 'Button-2'
        
        #check if there is an Iso val in the interval
        self.isoval_inrange = []
        if len(self.isoVals):
            for iso_val in self.isoVals:
                v = iso_val['val']
                if v >= self.values[next_l] and v  < = self.values[next_r]:
                    self.isoval_inrange.append(iso_val)
                    
        self.callbacks['entries'](val_x1=first_scal,
                            val_x2=first_scal+len(self.alpha_list)-1,
                            val_y = int(self.alpha_arr[curr_scal]),
                            val_r=round(curr_color[0],2),
                            val_g=round(curr_color[1],2),
                            val_b=round(curr_color[2],2))
        self.callbacks['rgbmap'](curr_hsv)

    def mouse2Move(self, event):

0 Source : thumbwheel.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def createCanvas(self, master, wheelPad=6):
        bw = self.borderWidth = wheelPad # distance between wheel and raise
        
        cd={'width':self.width+bw, 'height':self.height+bw, 'relief':'raised',
                'borderwidth':3}
        
        for k, w in self.canvasCfg.items():
            cd[k] = w

        self.canvas = Tkinter.Canvas(self, cd)
        cbdw = int(self.canvas.cget('borderwidth'))
        bd = self.borderWidth + cbdw + 1 # +1 for pixel0 that is not drawn

        height = self.height-bw
        width = self.width-bw
        cp = self.canvas.create_polygon
	self.outline1 = cp( bd, bd, bd, height+cbdw, width+cbdw, height+cbdw,
                            width+cbdw, bd, bd, bd,
                            width=1, outline='gray60', fill='gray85')

        ul = bd+1 # upper left pixel
        l = (width+cbdw-1) - (bd+1) # length of the inner box
        cl25 = 2.*l/25.
        cl = self.canvas.create_line
	self.outline2 = cl( ul+int(cl25), ul, ul, ul, ul,
                            height+cbdw-1, ul+int(cl25),
                            height+cbdw-1,
                            width=1, fill='gray20')
 	self.outline3 = cl( ul+int(cl25), ul, ul+int(3*cl25), ul,
                            width=1, fill='gray60')
 	self.outline4 = cl( ul+int(cl25), height+cbdw-1,
                            ul+int(3*cl25), height+cbdw-1,
                            width=1, fill='gray60')
 	self.outline5 = cl( ul+int(5*cl25), ul, ul+int(7.5*cl25), ul,
                            width=1, fill='white')
 	self.outline4 = cl(  ul+int(5*cl25), height+cbdw-1, ul+int(7.5*cl25),
                            height+cbdw-1,
                            width=1, fill='white')
 	self.outline6 = cl( ul+int(9.5*cl25), ul, ul+int(11.5*cl25), ul,
                            width=1, fill='gray60')
 	self.outline7 = cl( ul+int(9.5*cl25), height+cbdw-1,
                            ul+int(11.5*cl25), height+cbdw-1,
                            width=1, fill='gray60')

        re = ul+l
	self.outline8 = cl( ul+int(11.5*cl25), ul, re, ul, re,
                            height+cbdw-1, ul+int(11.5*cl25),
                            height+cbdw-1,
                            width=1, fill='gray20')

        # corners of the box where the lines have to be drawn
        self.innerbox = (ul+1, ul+1, re-1, height+cbdw-1)

        self.circlePtsAngles = []
        inc = 2*math.pi/float(self.nblines)
        for i in range(self.nblines):
            self.circlePtsAngles.append( i*inc )
        self.circlePtsAngles = Numeric.array(self.circlePtsAngles, 'f')
        self.linesIds = []
        self.shLinesIds = []
        # this table should depend on the number of lines
        # currently it is of length 15 (self.nblines/2)
        # It should be resized automatically to self.nblines/2
        self.shadowLinesOptions = [
            ( 0, 'black', 1), # offset, color, width
            ( 2, 'gray30', 1),
            ( 2, 'gray30', 1),
            ( 0, 'gray30', 1),
            (-1, 'white', 1),
            (-1, 'white', 1),
            (-1, 'white', 2),
            (-1, 'white', 2),
            (-1, 'white', 2),
            (-1, 'white', 2),
            (-1, 'white', 1),
            (-1, 'white', 1),
            ( 0, 'gray30', 1),
            (-2, 'gray30', 1),
            (-2, 'gray30', 1),
            ( 0, 'black', 1), # offset, color, width
            ( 0, 'black', 1), # offset, color, width
            ]

        for i in range(self.nblines):
            self.linesIds.append(cl(0,0,0,0,width=1, fill='black'))
            self.shLinesIds.append(cl(0,0,0,0))
        
        wlabCfg = {'padx':0,'pady':0}
        wlabCfg.update(self.wheelLabCfg)
        self.valueLabel = apply( Tkinter.Label, (self.master,), wlabCfg)

        self.drawLines()
	self.canvas.pack(side=Tkinter.LEFT)
        self.toggleWidgetLabel(self.showLabel)

        
    def drawLines(self):

0 Source : vector3DGUI.py
with GNU General Public License v3.0
from Valdes-Tresanco-MS

    def __init__(self, master=None, name='vector', size=200, continuous = 1,
                 vector=[0.0, 0.0, 1.0], mode='XY', precision=5,
                 lockContinuous=0,  lockPrecision=0, lockMode=0,
                 callback=None, labelSide='top'):
        
	KeyboardModifierMonitor.__init__(self)

        self.callback = callback # user specified callback
        self.name=name             # title inside canvas
        self.labelSide=labelSide   # where title gets packed
	self.mode=mode             # axe mode: can be 'XY', 'X', 'Y' or 'Z'
        self.precision=precision   # floating number digits
        self.continuous=continuous # can be 1 or 0
        self.vector=vector         # initial vector value
        self.size=size             # size of vector widget

        self.lockContinuous = lockContinuous  # set to 1 to lock menus in
                                              # option panel
        self.lockPrecision = lockPrecision
        self.lockMode = lockMode

        self.r = self.size/2
        self.r2 = self.r*self.r

        self.drawShadowX = 0
        self.drawShadowY = 1
        self.drawShadowZ = 0
	self.fillShadowPlanes = 1

	Tkinter.Frame.__init__(self, master)
        Tkinter.Pack.config(self)

        self.callbacks = CallbackManager() # object to manage callback
                                        # functions. They get called with the
                                        # current value as an argument
        self.zeros = Numeric.array( (0,0,0), 's')
        self.viewingMatInv = Numeric.array(
            [[  0.96770716, -0.03229283, -0.25      ,  0.        ],
             [  0.03229283, -0.96770716,  0.25      ,  0.        ],
             [  0.25      ,  0.25      ,  0.93541437,  0.        ],
             [  0.        ,  0.        ,  0.        ,  1.        ]],'f')
        self.viewingMat = Numeric.transpose(self.viewingMatInv)
        self.createCanvas(master, size)
        self.createEntries(self.frame)
	Tkinter.Widget.bind(self.canvas, "  <  ButtonPress-1>", self.mouseDown)
	Tkinter.Widget.bind(self.canvas, " < ButtonRelease-1>", self.mouseUp)
	Tkinter.Widget.bind(self.canvas, " < B1-Motion>", self.mouseMove)

        self.setEntries()

        self.opPanel = VectorOptionsPanel(master = self,
                                          title="Vector GUI Options")
        Tkinter.Widget.bind(self.canvas, " < Button-3>", self.toggleOptPanel)

        if self.callback:
            self.callbacks.AddCallback(self.callback)


    def toggleOptPanel(self, event=None):

See More Examples