예제 #1
0
def restoreMidasBase():
    formattedPositions = {
        'session-start':
        (1.155351159691909, 8.86882709175692,
         (1.3395405316555724, 3.9505837500000003, 8.726595046431203),
         (16.370238401985695, 1.165040645195333), 8.726595046431203, {
             (2, 0):
             ((-6.879216832661181, 1.2434449094635127, 13.102330090486209),
              (-0.7791729689523519, 0.43582107891998634, -0.450499136095727,
               109.18718989286837)),
             (1, 0):
             ((-6.879216832661183, 1.2434449094635125, 13.10233009048621),
              (-0.7791729689523519, 0.43582107891998634, -0.45049913609572706,
               109.18718989286837)),
             (0, 0):
             ((-6.879216832661183, 1.2434449094635125, 13.10233009048621),
              (-0.7791729689523519, 0.43582107891998634, -0.45049913609572706,
               109.18718989286837))
         }, {
             (0, 0, 'Molecule'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False, 5.0)
         }, 4, (1.3892258043886745, 3.93424088720653,
                8.767639523590514), False, 18.84968453493425)
    }
    import Midas
    Midas.restoreMidasBase(formattedPositions)
예제 #2
0
def show_saxs_profile(molecules, selected_only, epath, expath, dialog=None):

    if len(molecules) <= 2:
        name = ', '.join([m.name for m in molecules])
    else:
        name = '%d models' % len(molecules)

    import tempfile, os
    fd, pdbpath = tempfile.mkstemp(suffix='.pdb')
    os.close(fd)
    import Midas
    Midas.write(molecules, molecules[0], pdbpath, selOnly=selected_only)

    if not epath:
        # Use web services if no executable is given
        if dialog is None:
            dialog = PlotDialog()
        ProfileOpalService(pdbpath, expath, name, dialog.figure)
    else:
        cmd = '%s %s %s' % (epath, pdbpath, expath)
        from chimera.replyobj import info, warning
        info('Executing command: %s\n' % cmd)
        status = os.system(cmd)
        if status != 0:
            warning('Error %d executing command "%s"' % (status, cmd))
            return dialog
        if expath:
            from os.path import basename
            ppath = pdbpath[:-4] + '_' + basename(expath)
            p = read_profile(ppath, 3)
        else:
            ppath = pdbpath + '.dat'
            p = read_profile(ppath, 2)
        plot_profile(p, name, dialog.figure)
    return dialog
예제 #3
0
    def render_callback(self, frame):
        try:
            self.molecule.deleteCoordSet(self.molecule.coordSets[frame])
        except:
            pass
        self.molecule.LoadFrame(frame + 1)
        Midas.match("#0:1-545", "#1:1-545")
        Midas.undisplay("#0")

        Midas.color("byatom", "#0")
        Midas.undisplay("#0.=H=")
        Midas.wait(1)
        t = time.time()

        pct_complete = self.frames_done / float(self.frames_total) * 100
        if self.frames_done:
            time_to_complete = (t - self.t0) / self.frames_done * (
                self.frames_total - self.frames_done)
        else:
            time_to_complete = 0

        self.f.write(
            "Rendered frame %d (%d of %d, %d-%d), %5.2f%% complete, %5.2f seconds remaining)\n"
            % (frame, self.frames_done, self.frames_total, start, stop,
               pct_complete, time_to_complete))
        self.f.flush()
        self.frames_done += 1
        return True
예제 #4
0
def show_saxs_profile(molecules, selected_only, epath, expath, dialog = None):

  if len(molecules) <= 2:
    name = ', '.join([m.name for m in molecules])
  else:
    name = '%d models' % len(molecules)

  import tempfile, os
  fd, pdbpath = tempfile.mkstemp(suffix = '.pdb')
  os.close(fd)
  import Midas
  Midas.write(molecules, molecules[0], pdbpath, selOnly = selected_only)

  if not epath:
    # Use web services if no executable is given
    if dialog is None:
      dialog = PlotDialog()
    ProfileOpalService(pdbpath, expath, name, dialog.figure) 
  else:
    cmd = '%s %s %s' % (epath, pdbpath, expath)
    from chimera.replyobj import info, warning
    info('Executing command: %s\n' % cmd)
    status = os.system(cmd)
    if status != 0:
      warning('Error %d executing command "%s"' % (status, cmd))
      return dialog
    if expath:
      from os.path import basename
      ppath = pdbpath[:-4] + '_' + basename(expath)
      p = read_profile(ppath, 3)
    else:
      ppath = pdbpath + '.dat'
      p = read_profile(ppath, 2)
    plot_profile(p, name, dialog.figure)
  return dialog
예제 #5
0
    def pdbSelect(self):
        # Identify selected pbid
        sels = self.pdbListBox.getcurselection()
        if not sels:
            return
        pdbid = sels[0]

        # Set pdbid
        self.pdbid = pdbid

        # clean up previous pdbid selection
        self.cleanupPdbSelect()

        # Open Molecule if it isn't already open
        if myvrml.getModelNo(pdbid.lower()) == None:
            self.mol = myvrml.openMolecule(pdbid)
            # highlight hetatms
            Midas.represent("sphere", "#%d:.het" % self.mol.id)
            Midas.represent("sphere", "#%d:ca" % self.mol.id)

        # Get sites for the pdbid
        self.sites = self.sitefile.getByPdbid(pdbid)

        # Update listbox
        siteStrings = [PrettySiteString(s) for s in self.sites]
        self.siteListBox.setlist(siteStrings)
        
        # Select all sites
        self.siteListBox._listbox.select_set(0,'end')
        self.siteSelect()
예제 #6
0
def restoreMidasBase():
    formattedPositions = {
        'session-start':
        (1.0, 6.8744100148427, (46.179, 14.47249997139, 2.9510000367165),
         (15.820337462141, -12.771337686254), 2.9510000367165, {
             (0, 0): ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0)),
             (102, 0): ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0)),
             (2, 0): ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0)),
             (101, 0): ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0)),
             (1, 0): ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0)),
             (100, 0): ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0))
         }, {
             (2, 0, 'Molecule'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False, 5.0),
             (1, 0, 'Molecule'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False, 5.0),
             (0, 0, 'Molecule'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False, 5.0),
             (102, 0, 'Molecule'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False, 5.0),
             (101, 0, 'Molecule'): (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False,
                                    5.0),
             (100, 0, 'Molecule'): (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False,
                                    5.0)
         }, 4, (46.669999921321875, 9.811500097751617,
                1.5244998879432687), False, 17.567064639105)
    }
    import Midas
    Midas.restoreMidasBase(formattedPositions)
예제 #7
0
def showSurface(warnLarge=True):
	if warnLarge:
		numSurfaces = len(selMolecules())
		if numSurfaces > 20:
			import tkgui
			tkgui.SurfaceWarningDialog(numSurfaces,
				lambda : showSurface(warnLarge=False))
			return
	empty = selection.currentEmpty()
	atoms = selAtoms()
	for a in atoms:
		a.surfaceDisplay = True
	import Midas
	Midas.surfaceVisibilityByAtom(atoms)
	plist = selectedSurfacePieces(implied = True)
	if plist:
		pa, pb = surfacePieceAtomsAndBonds(plist)
		if pa:
			# Don't surface atoms that have non-MSMS surface.
			paset = set(pa)
			atoms = [a for a in atoms if a not in paset]
	for p in plist:
		p.display = True
		p.model.display = True
	from Midas import surfaceNew
	molcat = list(set([(a.molecule, a.surfaceCategory) for a in atoms]))
	if empty:
		# Only surface main category if nothing selected.
		molcat = [mc for mc in molcat if mc[1] == 'main']
	molcat.sort(lambda mc1,mc2: cmp(mc1[0].id, mc2[0].id))
	for mol, cat in molcat:
		surfaceNew(cat, models=[mol])
예제 #8
0
def showSurface(warnLarge=True):
    if warnLarge:
        numSurfaces = len(selMolecules())
        if numSurfaces > 20:
            import tkgui
            tkgui.SurfaceWarningDialog(numSurfaces,
                                       lambda: showSurface(warnLarge=False))
            return
    empty = selection.currentEmpty()
    atoms = selAtoms()
    for a in atoms:
        a.surfaceDisplay = True
    import Midas
    Midas.surfaceVisibilityByAtom(atoms)
    plist = selectedSurfacePieces(implied=True)
    if plist:
        pa, pb = surfacePieceAtomsAndBonds(plist)
        if pa:
            # Don't surface atoms that have non-MSMS surface.
            paset = set(pa)
            atoms = [a for a in atoms if a not in paset]
    for p in plist:
        p.display = True
        p.model.display = True
    from Midas import surfaceNew
    molcat = list(set([(a.molecule, a.surfaceCategory) for a in atoms]))
    if empty:
        # Only surface main category if nothing selected.
        molcat = [mc for mc in molcat if mc[1] == 'main']
    molcat.sort(lambda mc1, mc2: cmp(mc1[0].id, mc2[0].id))
    for mol, cat in molcat:
        surfaceNew(cat, models=[mol])
예제 #9
0
    def __init__(self, hitfile, master=None):
        Tkinter.Toplevel.__init__(self, master)

        self.hitfile = hitfile
        self.hitNodeList = HitNodeList(self.hitfile.hits)
        self.maxScore = 0
        self.models = []

        basename = os.path.basename(hitfile.filename)
        (pdbid, ext) = os.path.splitext(basename)
        self.pdbid = pdbid


        # Find MaxScore for slider
        if self.hitfile.hits:
            self.maxScore = max(self.hitfile.hits).score

        # Open Molecule if it isn't already open
        self.mol = None
        if myvrml.getModelNo(pdbid.lower()) == None:
            self.mol = myvrml.openMolecule(pdbid)
            # highlight hetatms
            Midas.represent("sphere", "#%d:.het" % self.mol.id)
            Midas.represent("sphere", "#%d:ca" % self.mol.id)

        self._buildGui()
예제 #10
0
def surfCmd(models, category):
	import Midas
	mols = filter(lambda m: isinstance(m, chimera.Molecule), models)
	Midas.surfaceNew(category, models=mols)
	for m in mols:
		for a in m.atoms:
			if a.surfaceCategory == category:
				a.surfaceDisplay = 1
예제 #11
0
def surfCmd(models, category):
    import Midas
    mols = filter(lambda m: isinstance(m, chimera.Molecule), models)
    Midas.surfaceNew(category, models=mols)
    for m in mols:
        for a in m.atoms:
            if a.surfaceCategory == category:
                a.surfaceDisplay = 1
예제 #12
0
    def _clearModelColor(self):
        # obtain modelNo
        modelNo = myvrml.getModelNo(self.pdbid.lower())
        if modelNo == None:
            return

        # Reset model color
        Midas.uncolor(None, "#%d" % modelNo)
        Midas.unrescolor(None, "#%d" % modelNo)
예제 #13
0
 def update_model_color(self):
     model_id = openModels.listIds()[-1][0]
     if not self.keep_selection:
         Midas.color('orange red', '#%d' % self.movie_id)
     else:
         Midas.color('forest green', '#%d' % model_id)
         Midas.color('byhet', '#%d' % model_id)
         Midas.color('forest green', '#%d' % self.movie_id)
     Midas.color('byhet', '#%d' % self.movie_id)
예제 #14
0
	def zoomModel(self, model):
		self.manipulateModel(model)
		sel = selection.ItemizedSelection()
		for m in self.refModels:
			if m.openState.active:
				sel.add(m.atoms)
		for m in self.altModels:
			if m.openState.active:
				sel.add(m.atoms)
		Midas.window(sel)
예제 #15
0
 def zoomModel(self, model):
     self.manipulateModel(model)
     sel = selection.ItemizedSelection()
     for m in self.refModels:
         if m.openState.active:
             sel.add(m.atoms)
     for m in self.altModels:
         if m.openState.active:
             sel.add(m.atoms)
     Midas.window(sel)
예제 #16
0
def restoreWindowSize((width, height)):
	import SimpleSession
	if SimpleSession.preexistingModels:
		return	# Leave window size as is.
	import Midas
	Midas.windowsize((width, height))
	def delay(arg1, arg2, arg3, width=width, height=height):
		repairView(width, height)
		from chimera.triggerSet import ONESHOT
		return ONESHOT
	chimera.triggers.addHandler('post-frame', delay, None)
예제 #17
0
def hideSurface():
	atoms = selAtoms()
	for a in atoms:
		a.surfaceDisplay = False
	import Midas
	Midas.surfaceVisibilityByAtom(atoms)
	plist = selectedSurfacePieces(excludeMSMS = True, implied = True)
	for p in plist:
		p.display = False
	# Undisplay models that have all pieces undisplayed.
	for s in set([p.model for p in plist]):
		if not [p for p in s.surfacePieces if p.display]:
			s.display = False
예제 #18
0
def hideSurface():
    atoms = selAtoms()
    for a in atoms:
        a.surfaceDisplay = False
    import Midas
    Midas.surfaceVisibilityByAtom(atoms)
    plist = selectedSurfacePieces(excludeMSMS=True, implied=True)
    for p in plist:
        p.display = False
    # Undisplay models that have all pieces undisplayed.
    for s in set([p.model for p in plist]):
        if not [p for p in s.surfacePieces if p.display]:
            s.display = False
예제 #19
0
 def html(*models):
     if models:
         for m in chimera.openModels.list():
             m.display = False
         chimera.selection.clearCurrent()
         for model in models:
             model.display = True
             chimera.selection.addCurrent(model)
             chimera.runCommand('focus sel')
     chimera.viewer.windowSize = 800, 600
     path = 'chimera_scene_export.html'
     Midas.export(filename=path, format='WebGL')
     return IFrame(path, *[x + 20 for x in chimera.viewer.windowSize])
예제 #20
0
 def save(okay, dialog, lfits=lfits):
     if okay:
         paths = dialog.getPaths()
         if paths:
             path = paths[0]
             import Midas
             if len(lfits) > 1 and path.find('%d') == -1:
                 base, suf = os.path.splitext(path)
                 path = base + '_fit%d' + suf
             for i, fit in enumerate(lfits):
                 p = path if len(lfits) == 1 else path % (i + 1)
                 fit.place_models(self.session)
                 Midas.write(fit.fit_molecules(),
                             relModel=fit.volume,
                             filename=p)
예제 #21
0
    def doMidasCommand(self, cmd):
        """ 'cmd' is the text of a Midas command
        This function will execute 'cmd'  using the Midas command line
        """

        from Midas import midas_text

        #code = None

        try:
            #code = Midas.midas_text.makeCommand(cmd)
            if midas_text.makeCommand(cmd):
                Midas.wait(1)
        except IOError, v:
            raise "Can't make command from %s" % cmd, v
예제 #22
0
    def doMidasCommand(self, cmd):
        """ 'cmd' is the text of a Midas command
        This function will execute 'cmd'  using the Midas command line
        """

        from Midas import midas_text
        
        #code = None

        try:
            #code = Midas.midas_text.makeCommand(cmd)
	    if midas_text.makeCommand(cmd):
		    Midas.wait(1)
        except IOError, v:
            raise "Can't make command from %s" % cmd, v
예제 #23
0
 def matchModel(self, model):
     n = self.matchVars[model].get()
     va, vd = self.modelVars[model]
     if n < 0:
         va.set(0)
         vd.set(0)
         self.activateModel(model, 0)
         self.displayModel(model, 0)
         return
     altOSL = '%s%s' % (model.oslIdent(), self.subSelection)
     ref = self.refModels[n]
     refOSL = '%s%s' % (ref.oslIdent(), self.subSelection)
     try:
         Midas.match(altOSL, refOSL)
     except Midas.MidasError, e:
         raise chimera.UserError(str(e))
예제 #24
0
def transpSurf(amount):
	if amount != -1:
		aopacity = opacity = min(1.0, 1 - amount)
	else:
		opacity = 1
		aopacity = -1
	atoms = selAtoms()
	import Midas
	surfatoms = Midas.atomMSMSModels(atoms)
	for s,atoms in surfatoms.items():
		adjustMSMSTransparency(s, atoms, opacity, aopacity)

	splist = selectedSurfacePieces(implied = True)
	from chimera import MSMSModel
	for p in splist:
		s = p.model
		if isinstance(s, MSMSModel) and s.molecule:
			adjustMSMSTransparency(s, s.atoms, opacity, aopacity)
		else:
			adjustSurfacePieceTransparency(p, opacity)

	if (len(atoms) > 0 and not selection.currentEmpty()
	    and len(surfatoms) == 0 and len(splist) == 0):
		from replyobj import warning
		warning('No surfaces shown for selected atoms.\n')
예제 #25
0
def colorAtomByElement(a, attrs=["color"], hetero=False):
	import Midas
	if hetero and a.element.number == chimera.elements.C.number:
		return
	c = Midas.elementColor(a.element)
	for attr in attrs:
		setattr(a, attr, c)
예제 #26
0
def colorAtomByElement(a, attrs=["color"], hetero=False):
    import Midas
    if hetero and a.element.number == chimera.elements.C.number:
        return
    c = Midas.elementColor(a.element)
    for attr in attrs:
        setattr(a, attr, c)
예제 #27
0
def transpSurf(amount):
    if amount != -1:
        aopacity = opacity = min(1.0, 1 - amount)
    else:
        opacity = 1
        aopacity = -1
    atoms = selAtoms()
    import Midas
    surfatoms = Midas.atomMSMSModels(atoms)
    for s, atoms in surfatoms.items():
        adjustMSMSTransparency(s, atoms, opacity, aopacity)

    splist = selectedSurfacePieces(implied=True)
    from chimera import MSMSModel
    for p in splist:
        s = p.model
        if isinstance(s, MSMSModel) and s.molecule:
            adjustMSMSTransparency(s, s.atoms, opacity, aopacity)
        else:
            adjustSurfacePieceTransparency(p, opacity)

    if (len(atoms) > 0 and not selection.currentEmpty() and len(surfatoms) == 0
            and len(splist) == 0):
        from replyobj import warning
        warning('No surfaces shown for selected atoms.\n')
예제 #28
0
	def matchModel(self, model):
		n = self.matchVars[model].get()
		va, vd = self.modelVars[model]
		if n < 0:
			va.set(0)
			vd.set(0)
			self.activateModel(model, 0)
			self.displayModel(model, 0)
			return
		altOSL = '%s%s' % (model.oslIdent(), self.subSelection)
		ref = self.refModels[n]
		refOSL = '%s%s' % (ref.oslIdent(), self.subSelection)
		try:
			Midas.match(altOSL, refOSL)
		except Midas.MidasError, e:
			raise chimera.UserError(str(e))
예제 #29
0
    def __init__(self, pdbid, motifs, master=None):
        Tkinter.Toplevel.__init__(self, master)

        self.pdbid = pdbid
        self.motifs = motifs
        self.models = []
        self.motifs.sort()

        # Open Molecule if it isn't already open
        self.mol = None
        if myvrml.getModelNo(pdbid.lower()) == None:
            self.mol = myvrml.openMolecule(pdbid)
            # highlight hetatms
            Midas.represent("sphere", "#%d:.het" % self.mol.id)
            Midas.represent("sphere", "#%d:ca" % self.mol.id)

        self._displayGui()
예제 #30
0
	def NDBColors(self):
		from chimera import selection
		if selection.currentEmpty():
			import Midas
			residues = Midas._selectedResidues('#')
		else:
			residues = selection.currentResidues()
		NA.NDBColors(residues)
예제 #31
0
def NDBColors(residues):
	import Midas
	color_names = set(std['NDB color'] for std in standard_bases.values())
	colors = {}
	for n in color_names:
		colors[n] = []
	for r in residues:
		try:
			info = standard_bases[nucleic3to1[r.type]]
		except KeyError:
			continue
		color = info['NDB color']
		colors[color].append(r)
	for color, residues in colors.items():
		if residues:
			Midas.color(color, residues)
			Midas.ribcolor(color, residues)
예제 #32
0
def oneTransparentLayer(ol):
    slist = set([p.model for p in selectedSurfacePieces(implied=True)])
    for s in slist:
        s.oneTransparentLayer = ol
    # MSMS surfaces with just atoms selected.
    import Midas
    surfatoms = Midas.atomMSMSModels(selAtoms())
    for s, atoms in surfatoms.items():
        s.oneTransparentLayer = ol
예제 #33
0
def oneTransparentLayer(ol):
	slist = set([p.model for p in selectedSurfacePieces(implied = True)])
	for s in slist:
		s.oneTransparentLayer = ol
	# MSMS surfaces with just atoms selected.
	import Midas
	surfatoms = Midas.atomMSMSModels(selAtoms())
	for s,atoms in surfatoms.items():
		s.oneTransparentLayer = ol
예제 #34
0
def atoms_surfnet(osl,
                  useMesh=True,
                  interval=1.0,
                  cutoff=10,
                  density='Gaussian',
                  color=None):
    try:
        atomList = Midas._selectedAtoms(osl)
    except (Midas.MidasError, chimera.oslParser.OSLSyntaxError), e:
        return str(e)
예제 #35
0
def restoreMidasBase():
    formattedPositions = {
        'session-start':
        (0.51656690745981, 212.3515733945, (0.42143249511719, -0.0260009765625,
                                            -104.88691711426),
         (430.69914501186, -402.44959815756), -104.88691711426, {
             (3, 0):
             ((85.74991093647263, -19.130254540518578, 15.953759428724865),
              (-0.5611631172296855, 0.5113469753074245, 0.650861142414425,
               111.83901581399124)),
             (2, 0):
             ((85.74991093647263, -19.130254540518578, 15.953759428724865),
              (-0.5611631172296855, 0.5113469753074245, 0.650861142414425,
               111.83901581399124)),
             (1, 0):
             ((85.74991093647263, -19.130254540518578, 15.953759428724865),
              (-0.5611631172296855, 0.5113469753074245, 0.650861142414425,
               111.83901581399124)),
             (0, 0):
             ((85.74991093647263, -19.130254540518578, 15.953759428724865),
              (-0.5611631172296855, 0.5113469753074245, 0.650861142414425,
               111.83901581399124)),
             (4, 0): ((85.74991093647263, -19.130254540518578,
                       15.953759428724865),
                      (-0.5611631172296855, 0.5113469753074245,
                       0.650861142414425, 111.83901581399124))
         }, {
             (1, 0, 'Volume'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, False, 5.0),
             (3, 0, 'Volume'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, False, 5.0),
             (0, 0, 'Volume'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, False, 5.0),
             (2, 0, 'Volume'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, False, 5.0),
             (4, 0, 'Volume'): (False, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, False,
                                5.0)
         }, 4, (86.38818617492556, -32.636260471782066,
                16.781572916543098), False, 24.739146122928)
    }
    import Midas
    Midas.restoreMidasBase(formattedPositions)
예제 #36
0
def interface_surfnet(receptorOSL,
                      ligandsOSL,
                      useMesh=True,
                      interval=1.0,
                      cutoff=10,
                      density='Gaussian',
                      color=None):
    try:
        receptorAtomList = Midas._selectedAtoms(receptorOSL)
    except (Midas.MidasError, chimera.oslParser.OSLSyntaxError), e:
        return str(e)
예제 #37
0
def restoreMidasBase():
    formattedPositions = {
        'session-start':
        (0.76683262201217, 6.8744100148427, (50.727180703031, 9.8739736787576,
                                             4.2693911011513),
         (16.96991371182, -9.3554221033169), 2.9510000367165, {
             (0, 0): ((68.201573465377, -15.759669552015, 43.458120084532),
                      (-0.46643889786615833, 0.31419420626180883,
                       0.8268716679805371, 117.23875474475)),
             (102, 0): ((68.201573465377, -15.759669552015, 43.458120084532),
                        (-0.46643889786615833, 0.31419420626180883,
                         0.8268716679805371, 117.23875474475)),
             (2, 0): ((68.201573465377, -15.759669552015, 43.458120084532),
                      (-0.46643889786615833, 0.31419420626180883,
                       0.8268716679805371, 117.23875474475)),
             (101, 0): ((68.201573465377, -15.759669552015, 43.458120084532),
                        (-0.46643889786615833, 0.31419420626180883,
                         0.8268716679805371, 117.23875474475)),
             (1, 0): ((68.201573465377, -15.759669552015, 43.458120084532),
                      (-0.46643889786615833, 0.31419420626180883,
                       0.8268716679805371, 117.23875474475)),
             (100, 0): ((68.201573465377, -15.759669552015, 43.458120084532),
                        (-0.46643889786615833, 0.31419420626180883,
                         0.8268716679805371, 117.23875474475))
         }, {
             (2, 0, 'Molecule'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False, 5.0),
             (1, 0, 'Molecule'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False, 5.0),
             (0, 0, 'Molecule'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False, 5.0),
             (102, 0, 'Molecule'):
             (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False, 5.0),
             (101, 0, 'Molecule'): (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False,
                                    5.0),
             (100, 0, 'Molecule'): (False, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False,
                                    5.0)
         }, 0, (54.1234, 9.16877, 4.26939), False, 17.567064639105)
    }
    import Midas
    Midas.restoreMidasBase(formattedPositions)
    def do_molBenchmark(self, style):

        self.set_standard_window_size()

        import Midas
        Midas.window('#')
        show_main_chimera_window()
        draw_scene()

        # Use glFinish instead of swapping buffers to avoid maxing out
        # at the screen's refresh rate
        times = []
        for i in range(5):
            with benchmarking(chimera.viewer):
                t = calls_per_second(draw_scene, self.averaging_interval)
            times.append(t)
            if self.halt_requested():
                raise HaltRequest(style)
        mean = sum(times) / 5.0

        return mean
예제 #39
0
    def __init__(self, m, grepPath):

        #    Generate a temporary file name for PDB file.
        #    We use Chimera's 'osTemporaryFile' function
        #    because it automatically deletes the file when
        #    Chimera exits.
        import OpenSave
        self.pdbFile = OpenSave.osTemporaryFile(suffix=".pdb", prefix="rg")
        self.outFile = OpenSave.osTemporaryFile(suffix=".out", prefix="rg")

        #    Write molecule in to temporary file in PDB format.
        self.molecule = m
        import Midas
        Midas.write([m], None, self.pdbFile)

        #    Set up a task instance for showing user our status.
        from chimera import tasks
        self.task = tasks.Task("atom count for %s" % m.name, self.cancelCB)

        #    Start by counting the ATOM records first.
        self.countAtoms()
    def __init__(self, m, grepPath):

	#    Generate a temporary file name for PDB file.
	#    We use Chimera's 'osTemporaryFile' function
	#    because it automatically deletes the file when
	#    Chimera exits.
	import OpenSave
	self.pdbFile = OpenSave.osTemporaryFile(suffix=".pdb", prefix="rg")
	self.outFile = OpenSave.osTemporaryFile(suffix=".out", prefix="rg")

	#    Write molecule in to temporary file in PDB format.
	self.molecule = m
	import Midas
	Midas.write([m], None, self.pdbFile)

	#    Set up a task instance for showing user our status.
	from chimera import tasks
	self.task = tasks.Task("atom count for %s" % m.name, self.cancelCB)

	#    Start by counting the ATOM records first.
	self.countAtoms()
예제 #41
0
  def do_molBenchmark(self, style):

	self.set_standard_window_size()

	import Midas
	Midas.window('#')
	show_main_chimera_window()
	draw_scene()

	# Use glFinish instead of swapping buffers to avoid maxing out
	# at the screen's refresh rate
	times = []
	for i in range(5):
		with benchmarking(chimera.viewer):
			t = calls_per_second(draw_scene, self.averaging_interval)
		times.append(t)
		if self.halt_requested():
			raise HaltRequest(style)
	mean = sum(times) / 5.0

	return mean
예제 #42
0
def sidechain(side, glycosidic=default.GLYCOSIDIC, orient=default.ORIENT,
		thickness=default.THICKNESS, hide=default.HIDE,
		shape=default.SHAPE, style=default.STYLE, radius=default.RADIUS,
		stubs=default.STUBS, ignore=default.IGNORE,
		useexisting=default.USE_EXISTING, sel='sel'):
	if isinstance(sel, basestring):
		sel = Midas.evalSpec(sel)
		residues = sel.residues()
		molecules = [g for g in sel.graphs()
					if isinstance(g, chimera.Molecule)]
	elif isinstance(sel, (list, tuple, set)):
		residues = sel
		molecules = set([r.molecule for r in residues])
	else:
		residues = sel.residues()
		molecules = [g for g in sel.graphs()
					if isinstance(g, chimera.Molecule)]
	residues = [r for r in residues
				if r.ribbonResidueClass.isNucleic()]
	if side == 'atoms':
		for r in residues:
			r.fillDisplay = False
		NA.set_normal(molecules, residues)
	elif side == 'fill/fill':
		for r in residues:
			r.fillDisplay = True
		if orient:
			NA.set_orient(molecules, residues)
		else:
			NA.set_normal(molecules, residues)
	elif side in ('fill/slab', 'tube/slab'):
		if side.startswith('fill'):
			for r in residues:
				r.fillDisplay = True
			showGly = True
		else:
			showGly = glycosidic
		if showGly:
			info = NA.findStyle(style)
			showGly = info[NA.ANCHOR] != NA.SUGAR
		NA.set_slab(side, molecules, residues, style=style,
			thickness=thickness, orient=orient,
			shape=shape, showGly=showGly, hide=hide)
	elif side == 'ladder':
		from FindHBond import recDistSlop, recAngleSlop
		NA.set_ladder(molecules, residues,
			rungRadius=radius,
			showStubs=stubs,
			skipNonBaseHBonds=ignore,
			useExisting=useexisting,
			distSlop=recDistSlop, angleSlop=recAngleSlop)
예제 #43
0
def fctMidas(p1, p2):
    xp, yp, zp = mc.player.getTilePos()
    if p1 == True:
        s = 15

    if p1 == False:
        s = 5

    if p2 == True:
        idb = 57

    if p2 == False:
        idb = 41

    Midas.Midascube(xp, yp, zp, s, idb)
    os('omxplayer -o local Desktop/minecraft/Magic_Wand/songs/Midas.mp3')
예제 #44
0
    def _displayMotif(self, motif):
        # obtain modelNo
        modelNo = myvrml.getModelNo(motif.pdbid.lower())
        if modelNo == None:
            print "No Model"
            return

        group = myvrml.GroupNode()

        # obtain chain residue numbers
        chainRes = []
        mol = chimera.openModels.list(id=modelNo)[0]
        residues = mol.residues
        residues.sort(lambda a, b: cmp(a.id.position, b.id.position))
        for res in residues:
            if res.id.chainId.strip() == motif.chainid:
                chainRes.append(res)

        # Hilight motif
        motifSel = "#%d:%d-%d.%s" % (
            modelNo, chainRes[motif.start].id.position,
            chainRes[motif.end - 1].id.position, motif.chainid)
        if gVerbose:
            print "MOTIFSEL:", motifSel
            print "START RES:", chainRes[motif.start].type,
            print "STOP RES:", chainRes[motif.end - 1].type
        Midas.color("red", motifSel)
        Midas.rescolor("red", motifSel)

        if gHaveCore:
            # Hilight coreMotif
            coreMotifSel = "#%d:%d-%d.%s" % (
                modelNo, chainRes[motif.coreStart].id.position,
                chainRes[motif.coreEnd - 1].id.position, motif.chainid)
            print "CORESEL:", coreMotifSel
            Midas.color("yellow", coreMotifSel)

        print motif

        return group
예제 #45
0
	def Apply(self):
		from chimera import dialogs

		selOnly = self.selOnlyVar.get()

		paths = self.getPaths()
		if not paths:
			replyobj.error('No save location chosen.\n')
			return
		path = paths[0]
		models = self.modelList.getvalue()
		if not models:
			replyobj.error("No models chosen to save.\n")
			return
		if len(openModels.listIds()) > 1:
			if self.saveRelativeVar.get():
				relModel = self.relModelMenu.getvalue()
			else:
				relModel = None
		else:
			if self.saveUntransformedVar.get():
				relModel = models[0]
			else:
				relModel = None
		if self.haveTraj and self.frameSave.getvalue() == "all frames":
			allFrames=True
		else:
			allFrames=False
			
		import Midas
		if len(models) < 2:
			replyobj.status("Writing %s to %s\n" %
							(models[0].name, path))
			Midas.write(models, relModel, path,
					allFrames=allFrames,
					dispOnly=self.dispOnlyVar.get(),
					selOnly=selOnly)
			replyobj.status("Wrote %s to %s\n" %
							(models[0].name, path))
			return

		saveOpt = self.multiSaveMenu.getvalue()
		for key, value in self.labelMap.items():
			if saveOpt == value:
				break
		self.prefs["multiSavePDB"] = key

		# write multiple models to multiple files
		if key == "multiple":
			if path.endswith(".pdb"):
				start, end = path[:-4], ".pdb"
			else:
				start, end = path, ""
			for m in models:
				modelPath = start + m.oslIdent()[1:] + end
				replyobj.status("Writing %s (%s) to %s\n" %
					(m.name, m.oslIdent(), modelPath))
				Midas.write(m, relModel, modelPath,
					allFrames=allFrames,
					dispOnly=self.dispOnlyVar.get(),
					selOnly=selOnly)
				replyobj.status("Wrote %s (%s) to %s\n" %
					(m.name, m.oslIdent(), modelPath))
			return

		# write multiple models to single file
		replyobj.status("Writing multiple models to %s\n" % path)
		Midas.write(models, relModel, path, allFrames=allFrames,
					dispOnly=self.dispOnlyVar.get(),
					selOnly=selOnly)
		replyobj.status("Wrote multiple models to %s\n" % path)
예제 #46
0
def restoreWindowSize((width, height)):
	import SimpleSession
	if SimpleSession.preexistingModels:
		return	# Leave window size as is.
	import Midas
	Midas.windowsize((width, height))
예제 #47
0
def restoreMidasBase():
	formattedPositions = {}
	import Midas
	Midas.restoreMidasBase(formattedPositions)
예제 #48
0
def ndbcolor(sel='sel'):
	residues = Midas._selectedResidues(sel)
	NA.NDBColors(residues)
예제 #49
0
def match(chainPairing, matchItems, matrix, alg, gapOpen, gapExtend,
		iterate=None, showAlignment=False, align=align, **alignKw):
	"""Superimpose structures based on sequence alignment

	   'chainPairing' is the method of pairing chains to match:
	   
	   CP_SPECIFIC_SPECIFIC --
	   Each reference chain is paired with a specified match chain
	   
	   CP_SPECIFIC_BEST --
	   Single reference chain is paired with best seq-aligning
	   chain from one or more molecules

	   CP_BEST --
	   Best seq-aligning pair of chains from reference molecule and
	   match molecule(s) is used
	"""
	ksdsspCache = set()
	alg = alg.lower()
	if alg == "nw" or alg.startswith("needle"):
		alg = "nw"
		algName = "Needleman-Wunsch"
	elif alg =="sw" or alg.startswith("smith"):
		alg = "sw"
		algName = "Smith-Waterman"
	else:
		raise ValueError("Unknown sequence alignment algorithm: %s"
									% alg)
	pairings = {}
	smallMolErrMsg = "Reference and/or match model contains no nucleic or"\
		" amino acid chains.\nUse the command-line 'match' command" \
		" to superimpose small molecules/ligands."
	if chainPairing == CP_SPECIFIC_SPECIFIC:
		# specific chain(s) in each

		# various sanity checks
		#
		# (1) can't have same chain matched to multiple refs
		# (2) reference molecule can't be a match molecule
		matchChains = {}
		matchMols = {}
		refMols = {}
		for ref, match in matchItems:
			if not matrixCompatible(ref, matrix):
				raise UserError("Reference chain (%s) not"
					" compatible with %s similarity"
					" matrix" % (ref.fullName(), matrix))
			if not matrixCompatible(match, matrix):
				raise UserError("Match chain (%s) not"
					" compatible with %s similarity"
					" matrix" % (match.fullName(), matrix))
			if match in matchChains:
				raise UserError("Cannot match the same chain"
					" to multiple reference chains")
			matchChains[match] = ref
			if match.molecule in refMols \
			or ref.molecule in matchMols \
			or match.molecule == ref.molecule:
				raise UserError("Cannot have same molecule"
					" model provide both reference and"
					" match chains")
			matchMols[match.molecule] = ref
			refMols[ref.molecule] = match

		if not matchChains:
			raise UserError("Must select at least one reference"
								" chain.\n")

		for match, ref in matchChains.items():
			score, s1, s2 = align(ref, match, matrix, alg,
						gapOpen, gapExtend,
						ksdsspCache, **alignKw)
			pairings.setdefault(s2.molecule, []).append(
							(score, s1, s2))

	elif chainPairing == CP_SPECIFIC_BEST:
		# specific chain in reference;
		# best seq-aligning chain in match model(s)
		ref, matches = matchItems
		if not ref or not matches:
			raise UserError("Must select at least one reference"
							" and match item.\n")
		if not matrixCompatible(ref, matrix):
			raise UserError("Reference chain (%s) not compatible"
						" with %s similarity matrix"
						% (ref.fullName(), matrix))
		for match in matches:
			bestScore = None
			seqs = [s for s in match.sequences()
						if matrixCompatible(s, matrix)]
			if not seqs and match.sequences():
				raise UserError("No chains in match structure"
					" %s compatible with %s similarity"
					" matrix" % (match, matrix))
			for seq in seqs:
				score, s1, s2 = align(ref, seq, matrix, alg,
						gapOpen, gapExtend,
						ksdsspCache, **alignKw)
				if bestScore is None or score > bestScore:
					bestScore = score
					pairing = (score, s1, s2)
			if bestScore is None:
				raise LimitationError(smallMolErrMsg)
			pairings[match]= [pairing]

	elif chainPairing == CP_BEST:
		# best seq-aligning pair of chains between
		# reference and match structure(s)
		ref, matches = matchItems
		if not ref or not matches:
			raise UserError("Must select at least one reference"
				" and match item in different models.\n")
		rseqs = [s for s in ref.sequences()
					if matrixCompatible(s, matrix)]
		if not rseqs and ref.sequences():
			raise UserError("No chains in reference structure"
				" %s compatible with %s similarity"
				" matrix" % (ref, matrix))
		for match in matches:
			bestScore = None
			mseqs = [s for s in match.sequences()
						if matrixCompatible(s, matrix)]
			if not mseqs and match.sequences():
				raise UserError("No chains in match structure"
					" %s compatible with %s similarity"
					" matrix" % (match, matrix))
			for mseq in mseqs:
				for rseq in rseqs:
					score, s1, s2 = align(rseq, mseq,
						matrix, alg, gapOpen, gapExtend,
						ksdsspCache, **alignKw)
					if bestScore is None \
					or score > bestScore:
						bestScore = score
						pairing = (score,s1,s2)
			if bestScore is None:
				raise LimitationError(smallMolErrMsg)
			pairings[match]= [pairing]
	else:
		raise ValueError("No such chain-pairing method")

	from chimera.misc import principalAtom
	retVals = []
	for matchMol, pairs in pairings.items():
		refAtoms = []
		matchAtoms = []
		regionInfo = {}
		for score, s1, s2 in pairs:
			try:
				ssMatrix = alignKw['ssMatrix']
			except KeyError:
				ssMatrix = defaultSSMatrix
			try:
				ssFraction = alignKw['ssFraction']
			except KeyError:
				ssFraction = defaults[SS_MIXTURE]

			replyobj.status("match %s (%s) with %s (%s),"
				" score = %g\n" % (
				s1.name, s1.molecule.oslIdent(), s2.name,
				s2.molecule.oslIdent(), score), log=1)
			replyobj.info("with these parameters:\n"
				"\tchain pairing: %s\n\t%s using %s\n"
				% (chainPairing, algName, matrix))

			if ssFraction is None or ssFraction is False:
				replyobj.info("\tno secondary structure"
							" guidance used\n")
				replyobj.info("\tgap open %g, extend %g\n" % (
							gapOpen, gapExtend))
			else:
				if 'gapOpenHelix' in alignKw:
					gh = alignKw['gapOpenHelix']
				else:
					gh = defaults[HELIX_OPEN]
				if 'gapOpenStrand' in alignKw:
					gs = alignKw['gapOpenStrand']
				else:
					gs = defaults[STRAND_OPEN]
				if 'gapOpenOther' in alignKw:
					go = alignKw['gapOpenOther']
				else:
					go = defaults[OTHER_OPEN]
				replyobj.info("\tss fraction: %g\n"
					"\tgap open (HH/SS/other) %g/%g/%g, "
					"extend %g\n"
					"\tss matrix: " % (ssFraction, gh, gs,
					go, gapExtend))
				for ss1, ss2 in ssMatrix.keys():
					if ss2 < ss1:
						continue
					replyobj.info(" (%s, %s): %g" % (ss1,
						ss2, ssMatrix[(ss1, ss2)]))
				replyobj.info("\n")
			if iterate is None:
				replyobj.info("\tno iteration\n")
			else:
				replyobj.info("\titeration cutoff: %g\n"
								% iterate)
			if showAlignment:
				from MultAlignViewer.MAViewer import MAViewer
				mav = MAViewer([s1,s2], autoAssociate=None)
				mav.autoAssociate = True
				mav.hideHeaders(mav.headers(shownOnly=True))
				mav.showHeaders([h for h in mav.headers()
							if h.name == "RMSD"])
			for i in range(len(s1)):
				if s1[i] == "." or s2[i] == ".":
					continue
				refRes = s1.residues[s1.gapped2ungapped(i)]
				matchRes = s2.residues[s2.gapped2ungapped(i)]
				if not refRes:
					continue
				refAtom = principalAtom(refRes)
				if not refAtom:
					continue
				if not matchRes:
					continue
				matchAtom = principalAtom(matchRes)
				if not matchAtom:
					continue
				if refAtom.name != matchAtom.name:
					# nucleic P-only trace vs. full nucleic
					if refAtom.name != "P":
						try:
							refAtom = refAtom.residue.atomsMap["P"][0]
						except KeyError:
							continue
					else:
						try:
							matchAtom = matchAtom.residue.atomsMap["P"][0]
						except KeyError:
							continue
				refAtoms.append(refAtom)
				matchAtoms.append(matchAtom)
				if showAlignment and iterate is not None:
					regionInfo[refAtom] = (mav, i)
		import Midas
		if len(matchAtoms) < 3:
			replyobj.error("Fewer than 3 residues aligned; cannot"
				" match %s with %s\n" % (s1.name, s2.name))
			continue
		try:
			retVals.append(Midas.match(matchAtoms, refAtoms,
						iterate=iterate, minPoints=3))
		except Midas.TooFewAtomsError:
			replyobj.error("Iteration produces fewer than 3"
				" residues aligned.\nCannot match %s with %s"
				" satisfying iteration threshold.\n"
				% (s1.name, s2.name))
			continue
		replyobj.info("\n") # separate matches with whitespace
		if regionInfo:
			byMav = {}
			for ra in retVals[-1][1]:
				mav, index = regionInfo[ra]
				byMav.setdefault(mav, []).append(index)
			for mav, indices in byMav.items():
				indices.sort()
				from MultAlignViewer.MAViewer import \
							MATCHED_REGION_INFO
				name, fill, outline = MATCHED_REGION_INFO
				mav.newRegion(name=name, columns=indices,
						fill=fill, outline=outline)
				mav.status("Residues used in final fit"
						" iteration are highlighted")
	return retVals
예제 #50
0
    def check_space_navigator(self, trigger_name, d1, d2):

        e = self.device.last_event()
        if e is None:
            return
        rot, trans, buttons = e

        from math import sqrt, pow
        from chimera import Vector, Xform, viewer

        # Rotation
        rx, ry, rz = rot         # 10 bits, signed, +/-512
        rmag = sqrt(rx*rx + ry*ry + rz*rz)

        # Translation
        tx, ty, tz = trans       # 10 bits, signed, +/-512
        if self.zoom and not self.fly_mode:
            zm = tz
            tz = 0
        else:
            zm = 0
        tmag = sqrt(tx*tx + ty*ty + tz*tz)
        zmag = abs(zm)
        
        if self.dominant:
            if tmag < rmag or tmag < zmag:
                tmag = 0
            if rmag < tmag or rmag < zmag:
                rmag = 0
            if zmag < tmag or zmag < rmag:
                zmag = 0
            if self.fly_mode:
                rt = 50
                if abs(ry) > abs(rx)+rt and abs(ry) > abs(rz)+rt: rx = rz = 0
                else: ry = 0
                rmag = sqrt(rx*rx + ry*ry + rz*rz)

        if rmag > 0:
            axis = Vector(rx/rmag, ry/rmag, rz/rmag)
            if self.fly_mode: f = 3
            else: f = 30
            angle = self.speed*(f*rmag/512)
            xf = Xform.rotation(axis, angle)
            self.apply_transform(xf)

        if tmag > 0:
            axis = Vector(tx/tmag, ty/tmag, tz/tmag)
            shift = axis * 0.15 * self.speed * viewer.viewSize * tmag/512
            xf = Xform.translation(shift)
            self.apply_transform(xf)

        if zmag != 0:
            f = pow(1.1, self.speed*float(zm)/512)
            import Midas
            Midas.updateZoomDepth(viewer)
            try:
                viewer.scaleFactor *= f
            except ValueError:
                import chimera
		raise chimera.LimitationError("refocus to continue scaling")

        if 'N1' in buttons or 31 in buttons:
            self.view_all()

        if 'N2' in buttons:
            self.toggle_dominant_mode()