Exemplo n.º 1
0
	def _selResidues(self, residues):
		from chimera.selection import ItemizedSelection
		from chimera.tkgui import selectionOperation
		sel = ItemizedSelection()
		sel.add(residues)
		sel.addImplied(vertices=0)
		selectionOperation(sel)
Exemplo n.º 2
0
	def _mouseUpCB(self, event):
		canvas = self.seqCanvas.mainCanvas
		if not self._dragRegion:
			# maybe a region pick
			region = self._region(event)
			if region:
				self._toggleCurrent(region)
			else:
				# maybe a column pick
				col = self._columnPick(event)
				if col is not None:
					residues = self._residuesInBlock((
						self.seqCanvas.seqs[0],
						self.seqCanvas.seqs[-1],
						col, col))
					sel = ItemizedSelection()
					sel.add(residues)
					selectionOperation(sel)
		else:
			self._selectOnStructures()
			self._prevDrag = self._dragRegion
			self.seqCanvas.mav.status(
				"Shift-drag to add to region; "
				"control-drag to add new region\n"
				"Tools->Region Browser to change colors; "
				"control left/right arrow to realign region",
				blankAfter=120)
		self._startX, self._startY = None, None
		if self._afterID:
			canvas.after_cancel(self._afterID)
			self._afterID = None
		self._dragRegion = None
		self._clearDrag()
Exemplo n.º 3
0
	def _selectOnStructures(self, region=None):
		# highlight on chimera structures
		from chimera import getSelMode
		self._selChangeFromSelf = getSelMode() == "replace"
		sel = ItemizedSelection()
		sel.add(self.regionResidues(region))
		sel.addImplied(vertices=False)
		selectionOperation(sel)
		self._selChangeFromSelf = False
Exemplo n.º 4
0
    def _instantiateAxis(self, number, name, color, radius, sourceModel, atoms,
                         center, vec, extents):
        axis = Axis(number, name, color, radius, sourceModel, center, vec,
                    extents)
        from chimera.selection import ItemizedSelection
        sel = ItemizedSelection(selChangedCB=lambda a=axis: self.removeAxes(
            [a], checkForChanges=False))
        sel.add(atoms)
        self.axisData[axis] = sel

        from Geometry import geomManager
        geomManager.addInterfaceItems([axis])
        return axis
	def _instantiatePlane(self, number, name, cmpVal, color, radius,
			thickness, sourceModel, atoms, chimeraPlane):
		plane = Plane(number, name, color, radius,
					thickness, sourceModel, chimeraPlane)
		from chimera.selection import ItemizedSelection
		sel = ItemizedSelection(selChangedCB=lambda pl=plane:
				self.removePlanes([pl], checkForChanges=False))
		sel.add(atoms)
		self.planeData[plane] = sel

		from Geometry import geomManager
		geomManager.addInterfaceItems([plane])
		return plane
Exemplo n.º 6
0
 def _writeParmchk(self, filename):
     # generate Mol2 input file for parmchk
     import WriteMol2
     from chimera.selection import ItemizedSelection
     from chimera import Bond
     rSet = set(self.needParmchk)
     for b in self.chimeraMolecule.bonds:
         if b.display == Bond.Never:
             continue
         a0, a1 = b.atoms
         r0 = a0.residue
         r1 = a1.residue
         if (r0 in self.needParmchk and r1 not in self.needParmchk):
             rSet.add(r1)
         elif (r0 not in self.needParmchk and r1 in self.needParmchk):
             rSet.add(r0)
     sel = ItemizedSelection()
     sel.add(rSet)
     WriteMol2.writeMol2(sel, filename, gaffType=True)
Exemplo n.º 7
0
def gatherAtoms(bySerial, label, f, dicts):
    for line in f:
        line = line.strip()
        if not line:
            continue
        # ignore altloc column...
        if line.startswith("HETATM"):
            # guarantee that atom serial number splits off...
            line = "ATOM  " + line[6:]
        fields = line[:16].strip().split() + line[17:].split()
        serial = int(fields[1])
        try:
            atom = bySerial[serial]
        except KeyError:
            raise ValueError("Non-existent serial number (%d) found"
                             " in %s file" % (serial, label))
        from chimera.misc import chimeraLabel
        if atom.name != fields[2] \
        and atom.name != fields[2].replace("*", "'"):
            raise ValueError(
                "Atom with serial number %d (%s) does"
                " not match name in %s file (%s)" %
                (serial, chimeraLabel(atom, showModel=False,
                                      modelName=False), label, fields[2]))
        if atom.residue.type != fields[3]:
            raise ValueError(
                "Atom with serial number %d (%s) does"
                " not match residue type in %s file (%s)" %
                (serial, chimeraLabel(atom, showModel=False,
                                      modelName=False), label, fields[3]))
        id = int(fields[-2])
        if id > len(dicts):
            raise ValueError(
                "%s ID (%d) in %s file greater than"
                " number of %ss (%d) in %s info file" %
                (label.capitalize(), id, label, label, len(dicts), label))
        dicts[id - 1].setdefault("atoms", []).append(atom)
    from chimera.selection import ItemizedSelection
    for d in dicts:
        sel = ItemizedSelection()
        sel.add(d.get("atoms", []))
        d["atoms"] = sel
Exemplo n.º 8
0
 def holdSteadyCB(self):
     """'hold steady' menu callback"""
     from chimera.actions import selAtoms
     from chimera.selection import ItemizedSelection
     atoms = selAtoms()
     if not atoms:
         replyobj.error("No atoms selected\n")
         return
     self.status("Holding %d atoms steady" % len(atoms))
     steadySel = ItemizedSelection(selChangedCB=self._steadySelCB)
     steadySel.add(atoms)
     identity = chimera.Xform.identity()
     curFrame = self.currentFrame.get()
     cs = self.model.activeCoordSet
     self.holdingSteady = (atoms, steadySel, cs, identity)
     self.transforms = {curFrame: (identity, identity)}
     self.actionsMenu.entryconfigure(self.stopHoldingLabel, state='normal')
     if self.volumeDialog:
         # clear "no atoms held steady" error
         self.volumeDialog.status("")
Exemplo n.º 9
0
	def _focusCB(self, event, pref=None):
		if pref == "residue":
			funcs = [self._residueCB, self._regionResiduesCB]
		else:
			funcs = [self._regionResiduesCB, self._residueCB]

		for func in funcs:
			residues = func(event)
			if residues is None: # no residue/region 
				continue
			if not residues: # region with no structure residues
				return
			break
		if residues is None:
			return
		from Midas import cofr, window
		from chimera.selection import ItemizedSelection
		sel = ItemizedSelection()
		sel.add(residues)
		window(sel)
		cofr(sel)
Exemplo n.º 10
0
	def holdSteadyCB(self):
		"""'hold steady' menu callback"""
		from chimera.actions import selAtoms
		from chimera.selection import ItemizedSelection
		atoms = selAtoms()
		if not atoms:
			replyobj.error("No atoms selected\n")
			return
		self.status("Holding %d atoms steady" % len(atoms))
		steadySel = ItemizedSelection(selChangedCB=self._steadySelCB)
		steadySel.add(atoms)
		identity = chimera.Xform.identity()
		curFrame = self.currentFrame.get()
		cs = self.model.activeCoordSet
		self.holdingSteady = (atoms, steadySel, cs, identity)
		self.transforms = { curFrame: (identity, identity) }
		self.actionsMenu.entryconfigure(self.stopHoldingLabel,
							state='normal')
		if self.volumeDialog:
			# clear "no atoms held steady" error
			self.volumeDialog.status("")
Exemplo n.º 11
0
	def _writeParmchk(self, filename):
		# generate Mol2 input file for parmchk
		import WriteMol2
		from chimera.selection import ItemizedSelection
		from chimera import Bond
		rSet = set(self.needParmchk)
		for b in self.chimeraMolecule.bonds:
			if b.display == Bond.Never:
				continue
			a0, a1 = b.atoms
			r0 = a0.residue
			r1 = a1.residue
			if (r0 in self.needParmchk
			and r1 not in self.needParmchk):
				rSet.add(r1)
			elif (r0 not in self.needParmchk
			and r1 in self.needParmchk):
				rSet.add(r0)
		sel = ItemizedSelection()
		sel.add(rSet)
		WriteMol2.writeMol2(sel, filename, gaffType=True)
Exemplo n.º 12
0
 def _selResidues(self, residues):
     from chimera.selection import ItemizedSelection
     from chimera.tkgui import selectionOperation
     sel = ItemizedSelection()
     sel.add(residues)
     sel.addImplied(vertices=0)
     selectionOperation(sel)
    def Apply(self):
        from operator import add
        from chimera.selection import ItemizedSelection, \
             OSLSelection, REPLACE
        sel = ItemizedSelection()
        chainOSL = ""
        for codeInfo, var in self._codeVars.items():
            model, code = codeInfo
            if var.get():
                chainOSL = chainOSL + model.oslIdent() \
                    + ":." + code
        if chainOSL:
            sel.merge(REPLACE, OSLSelection(chainOSL))

        for model, var, resList in self._physVars:
            if var.get():
                sel.add(resList)

        sel.addImplied(vertices=0)
        chimera.tkgui.selectionOperation(sel)
Exemplo n.º 14
0
	def Apply(self):
		from operator import add
		from chimera.selection import ItemizedSelection, \
							OSLSelection, REPLACE
		sel = ItemizedSelection()
		chainOSL = ""
		for codeInfo, var in self._codeVars.items():
			model, code = codeInfo
			if var.get():
				chainOSL = chainOSL + model.oslIdent() \
								+ ":." + code
		if chainOSL:
			sel.merge(REPLACE, OSLSelection(chainOSL))
		
		for model, var, resList in self._physVars:
			if var.get():
				sel.add(resList)
				
		sel.addImplied(vertices=0)
		chimera.tkgui.selectionOperation(sel)
Exemplo n.º 15
0
class DetectClashDialog(ModelessDialog):
	name = "detect clashes"
	title = "Find Clashes/Contacts"
	provideStatus = True
	statusPosition = "above"
	help = "ContributedSoftware/findclash/findclash.html"

	FREQ_APPLY = "when OK/Apply clicked"
	FREQ_MOTION = "after relative motions (until dialog closed)"
	FREQ_CONTINUOUS = "continuously (until dialog closed)"

	CHECK_SET = "second set of designated atoms"

	def fillInUI(self, parent):
		self._handlers = {}
		desigGroup = Pmw.Group(parent, tag_text="Atoms to Check", hull_padx=2)
		desigGroup.grid(row=0, sticky="ew")
		from chimera.tkgui import windowSystem
		Tkinter.Button(desigGroup.interior(), command=self._desigCB,
				text="Designate").grid(row=0, column=0, sticky='e')
		Tkinter.Label(desigGroup.interior(), text="currently selected"
			" atoms for checking").grid(row=0, column=1, sticky='w')
		self.desigStatus = Tkinter.Label(desigGroup.interior())
		from tkFont import Font
		font = Font(font=self.desigStatus.cget('font'))
		size = int(font.cget('size'))
		if size > 2:
			font.config(size=size-2)
		font.config(weight='normal')
		self.desigStatus.config(font=font)
		from chimera.selection import ItemizedSelection
		self.designated = ItemizedSelection(
					selChangedCB=self._updateDesigStatus)
		self.desigStatus.grid(row=1, column=0, columnspan=2)
		self.designated2 = ItemizedSelection(selChangedCB=self._locButtonCB)
		if windowSystem == 'aqua':
			pady = None
		else:
			pady = 0
		Tkinter.Button(desigGroup.interior(), command=self._desig2CB,
				pady=pady, text="Designate selection as second set"
				).grid(row=3, column=1)
		self.desig2Status = Tkinter.Label(desigGroup.interior())
		if size > 4:
			font2 = Font(font=font)
			font2.config(size=size-4)
		else:
			font2 = font
		self.desig2Status.config(font=font2)
		self.desig2Status.grid(row=4, column=1)
		self.checkLocButtons = Pmw.RadioSelect(desigGroup.interior(),
			pady=0, orient='vertical', buttontype='radiobutton',
			labelpos='w', label_text="Check designated\natoms"
			" against:", command=self._locButtonCB)
		self.checkLocButtons.grid(row=2, column=0, columnspan=2)
		self.checkLocButtons.add("themselves")
		self.checkLocButtons.add("all other atoms")
		self.checkLocButtons.add("other atoms in same model")
		self.checkLocButtons.add(self.CHECK_SET)
		self.checkLocButtons.invoke(1)

		defGroup = Pmw.Group(parent,
			tag_text="Clash/Contact Parameters", hull_padx=2)
		defGroup.grid(row=1, sticky='ew')
		self.clashDef = ClashDef(defGroup.interior(),
					command=self._checkContinuous,
					value=str(prefs[CLASH_THRESHOLD]))
		self.clashDef.grid(row=0, sticky='w')
		self.hbondAllow = HbondAllow(defGroup.interior(),
					command=self._checkContinuous,
					value=str(prefs[HBOND_ALLOWANCE]))
		self.hbondAllow.grid(row=1, sticky='w')
		defaultsFrame = Tkinter.Frame(defGroup.interior())
		defaultsFrame.grid(row=2)
		Tkinter.Label(defaultsFrame, text="Default").grid(
							row=0, column=0)
		Tkinter.Button(defaultsFrame, text="clash", pady=pady,
			command=self._clashDefaultsCB).grid(row=0, column=1)
		Tkinter.Label(defaultsFrame, text="/").grid(row=0, column=2)
		Tkinter.Button(defaultsFrame, text="contact", pady=pady,
			command=self._contactDefaultsCB).grid(row=0, column=3)
		Tkinter.Label(defaultsFrame, text="criteria").grid(
							row=0, column=4)
		bondsFrame = Tkinter.Frame(defGroup.interior())
		bondsFrame.grid(row=3, sticky='w')
		self.bondsApart = Pmw.OptionMenu(bondsFrame, labelpos='w',
			label_text="Ignore contacts of pairs",
			command=self._checkContinuous,
			initialitem=str(prefs[BOND_SEPARATION]),
			items=[str(i+2) for i in range(4)])
		self.bondsApart.grid(row=0, column=0)
		Tkinter.Label(bondsFrame, text="or fewer bonds apart").grid(
							row=0, column=1)
		self.ignoreIntraResVar = Tkinter.IntVar(parent)
		self.ignoreIntraResVar.set(prefs[IGNORE_INTRA_RES])
		Tkinter.Checkbutton(defGroup.interior(), text="Ignore intra-"
			"residue contacts", variable=self.ignoreIntraResVar,
			command=self._checkContinuous
			).grid(row=4)
			
		actionGroup = Pmw.Group(parent, tag_text=
				"Treatment of Clash/Contact Atoms", hull_padx=2)
		actionGroup.grid(row=2, sticky='ew')
		self.actionSelVar = Tkinter.IntVar(parent)
		self.actionSelVar.set(prefs[ACTION_SELECT])
		Tkinter.Checkbutton(actionGroup.interior(), text="Select",
			command=self._checkContinuous,
			variable=self.actionSelVar).grid(row=0, sticky='w')
		self.actionColorVar = Tkinter.IntVar(parent)
		self.actionColorVar.set(prefs[ACTION_COLOR])
		f = Tkinter.Frame(actionGroup.interior())
		f.grid(row=1, sticky='w')
		Tkinter.Checkbutton(f, text="Color",
			command=self._checkContinuous,
			variable=self.actionColorVar).grid(row=0, column=0)
		from CGLtk.color.ColorWell import ColorWell
		self.clashColorWell = ColorWell(f, noneOkay=True,
						callback=self._checkContinuous,
						color=prefs[CLASH_COLOR])
		self.clashColorWell.grid(row=0, column=1)
		Tkinter.Label(f, text=" (and color all other atoms").grid(row=0,
								column=2)
		self.nonclashColorWell = ColorWell(f, noneOkay=True,
						callback=self._checkContinuous,
						color=prefs[NONCLASH_COLOR])
		self.nonclashColorWell.grid(row=0, column=3)
		Tkinter.Label(f, text=")").grid(row=0, column=4)
		self.actionPBVar = Tkinter.IntVar(parent)
		self.actionPBVar.set(prefs[ACTION_PSEUDOBONDS])
		f = Tkinter.Frame(actionGroup.interior())
		f.grid(row=2, sticky='w')
		Tkinter.Checkbutton(f, text="Draw pseudobonds of color",
			command=self._checkContinuous,
			variable=self.actionPBVar).grid(row=0, column=0)
		from CGLtk.color.ColorWell import ColorWell
		self.pbColorWell = ColorWell(f, noneOkay=False,
						callback=self._checkContinuous,
						color=prefs[PB_COLOR])
		self.pbColorWell.grid(row=0, column=1)
		self.pbWidthEntry = Pmw.EntryField(f, labelpos='w',
			label_text=" and width", validate={'validator': 'real',
			'min': 0.01}, entry_width=4, entry_justify="center",
			command=self._checkContinuous,
			value=str(prefs[PB_WIDTH]))
		self.pbWidthEntry.grid(row=0, column=2)
		self.actionAttrVar = Tkinter.IntVar(parent)
		self.actionAttrVar.set(prefs[ACTION_ATTR])
		self.assignAttrButton = Tkinter.Checkbutton(
					actionGroup.interior(),
					text="Assign 'overlap' attribute",
					variable=self.actionAttrVar)
		self.assignAttrButton.grid(row=3, sticky='w')
		self.actionWriteInfoVar = Tkinter.IntVar(parent)
		self.actionWriteInfoVar.set(prefs[ACTION_WRITEINFO])
		self.writeInfoButton = Tkinter.Checkbutton(
			actionGroup.interior(), text="Write information to"
			" file", variable=self.actionWriteInfoVar)
		self.writeInfoButton.grid(row=4, sticky='w')
		self.actionLogInfoVar = Tkinter.IntVar(parent)
		self.actionLogInfoVar.set(prefs[ACTION_REPLYLOG])
		self.logInfoButton = Tkinter.Checkbutton(
			actionGroup.interior(), text="Write information to"
			" reply log", variable=self.actionLogInfoVar)
		self.logInfoButton.grid(row=5, sticky='w')

		freqGroup = Pmw.Group(parent, tag_text="Frequency of Checking",
								hull_padx=2)
		freqGroup.grid(row=3, sticky="ew")
		self.freqButtons = Pmw.RadioSelect(freqGroup.interior(),
			pady=0, orient='vertical', buttontype='radiobutton',
			labelpos='w', label_text= "Check...",
			command=self._freqChangeCB)
		self.freqButtons.grid(sticky='w')
		self.freqButtons.add(self.FREQ_APPLY)
		self.freqButtons.add(self.FREQ_MOTION)
		self.freqButtons.add(self.FREQ_CONTINUOUS)

		self.freqButtons.invoke(0)
		self._updateDesigStatus()

	def OK(self, *args):
		# use main status line if dialog closing
		from chimera.replyobj import status
		self.status = status
		ModelessDialog.OK(self, *args)

	def Apply(self, *args):
		# workaround: remove pseudobonds before recreating colors
		# so C++ layer doesn't end up with pointers to deleted
		# colors in obscure circumstances
		from DetectClash import nukeGroup
		nukeGroup()
		from chimera import UserError
		self.status("")
		checkAtoms = self.designated.atoms()
		if not checkAtoms:
			self.enter()
			raise UserError("No atoms designated for clash detection")
		self.clashDef['command'] = None
		self.clashDef.invoke()
		self.clashDef['command'] = self._checkContinuous
		if not self.clashDef.valid():
			self.enter()
			raise UserError("Invalid clash amount"
					" (in Clash/Contact Parameters)")
		prefs[CLASH_THRESHOLD] = float(self.clashDef.getvalue())
		self.hbondAllow['command'] = None
		self.hbondAllow.invoke()
		self.hbondAllow['command'] = self._checkContinuous
		if not self.hbondAllow.valid():
			self.enter()
			raise UserError("Invalid H-bond overlap amount"
					" (in Clash/Contact Parameters)")
		prefs[HBOND_ALLOWANCE] = float(self.hbondAllow.getvalue())
		prefs[BOND_SEPARATION] = int(self.bondsApart.getvalue())
		prefs[IGNORE_INTRA_RES] = self.ignoreIntraResVar.get()
		checkVal = self.checkLocButtons.getvalue()
		if checkVal == "themselves":
			test = "self"
		elif checkVal == "all other atoms":
			test = "others"
		elif checkVal == "other atoms in same model":
			test = "model"
		else:
			test = self.designated2.atoms()
			if not test:
				self.enter()
				raise UserError("No second-set atoms designated")
		actionAttr = prefs[ACTION_ATTR] = self.actionAttrVar.get()
		actionSelect = prefs[ACTION_SELECT] = self.actionSelVar.get()
		actionColor = prefs[ACTION_COLOR] = self.actionColorVar.get()
		actionPseudobonds = prefs[ACTION_PSEUDOBONDS] = \
							self.actionPBVar.get()
		actionWriteInfo = prefs[ACTION_WRITEINFO] = \
						self.actionWriteInfoVar.get()
		actionLogInfo = prefs[ACTION_REPLYLOG] = \
						self.actionLogInfoVar.get()
		if self.freqButtons.getvalue() != self.FREQ_APPLY:
			actionAttr = actionWriteInfo = actionLogInfo = False
		if not actionAttr and not actionSelect and not actionColor \
		and not actionPseudobonds and not actionWriteInfo \
		and not actionLogInfo:
			self.enter()
			raise UserError("No actions selected for clashes")
		self.status("Checking for clashes")
		clashColor = nonclashColor = None
		if actionColor:
			prefs[CLASH_COLOR] = self.clashColorWell.rgba
			prefs[NONCLASH_COLOR] = self.nonclashColorWell.rgba
			if prefs[CLASH_COLOR] == None:
				clashColor = None
			else:
				clashColor = chimera.MaterialColor(
							*prefs[CLASH_COLOR])
			if prefs[NONCLASH_COLOR] == None:
				nonclashColor = None
			else:
				nonclashColor = chimera.MaterialColor(
							*prefs[NONCLASH_COLOR])
		pbColor = None
		if actionPseudobonds:
			prefs[PB_COLOR] = self.pbColorWell.rgba
			pbColor = chimera.MaterialColor(*prefs[PB_COLOR])
			self.pbWidthEntry['command'] = None
			self.pbWidthEntry.invoke()
			self.pbWidthEntry['command'] = self._checkContinuous
			if not self.pbWidthEntry.valid():
				self.enter()
				raise UserError("Invalid pseudobond width "
					"(in Treatment of Clash/Contact Atoms)")
			prefs[PB_WIDTH] = float(self.pbWidthEntry.getvalue())

		from DetectClash import cmdDetectClash
		if actionWriteInfo:
			saveFile = "-"
		else:
			saveFile = None
		clashes = cmdDetectClash(checkAtoms, test=test,
			overlapCutoff=prefs[CLASH_THRESHOLD],
			hbondAllowance=prefs[HBOND_ALLOWANCE],
			bondSeparation=prefs[BOND_SEPARATION],
			ignoreIntraRes=prefs[IGNORE_INTRA_RES],
			setAttrs=actionAttr,
			selectClashes=actionSelect,
			colorClashes=actionColor,
			clashColor=clashColor, nonclashColor=nonclashColor,
			makePseudobonds=actionPseudobonds,
			pbColor=pbColor, lineWidth=prefs[PB_WIDTH],
			saveFile=saveFile, log=actionLogInfo,
			summary=self.status)
		if actionAttr:
			from ShowAttr import ShowAttrDialog
			from chimera import dialogs
			from DetectClash import attrName
			d = dialogs.display(ShowAttrDialog.name)
			d.configure(attrsOf="atoms", attrName=attrName,
								mode="Render")

	def Close(self):
		ModelessDialog.Close(self)
		if self.freqButtons.getvalue() != self.FREQ_APPLY:
			self.freqButtons.invoke(self.FREQ_APPLY)

	def _checkContinuous(self, *args):
		if self.freqButtons.getvalue() == self.FREQ_CONTINUOUS:
			self.Apply()

	def _clashDefaultsCB(self):
		from prefs import defaults
		self.hbondAllow.setvalue(str(defaults[HBOND_ALLOWANCE]))
		self.clashDef.setvalue(str(defaults[CLASH_THRESHOLD]))
		self._checkContinuous()

	def _clearHandlers(self):
		while self._handlers:
			trigName, handler = self._handlers.popitem()
			chimera.triggers.deleteHandler(trigName, handler)

	def _contactDefaultsCB(self):
		self.hbondAllow.setvalue("0.0")
		self.clashDef.setvalue("-0.4")
		self._checkContinuous()

	def _desigCB(self):
		self.designated.clear()
		self.designated.add(chimera.selection.currentAtoms())
		self._updateDesigStatus()

	def _desig2CB(self):
		self.designated2.clear()
		self.designated2.add(chimera.selection.currentAtoms())
		self._locButtonCB()
		self._updateDesig2Status()

	def _freqChangeCB(self, freqVal):
		self._clearHandlers()
		if freqVal == self.FREQ_APPLY:
			self.assignAttrButton.configure(state='normal')
			self.writeInfoButton.configure(state='normal')
			self.logInfoButton.configure(state='normal')
			return
		self.assignAttrButton.configure(state='disabled')
		self.writeInfoButton.configure(state='disabled')
		self.logInfoButton.configure(state='disabled')
		def modCoordSets(trigName, myData, changes):
			if changes.modified:
				self.Apply()
		self._handlers['CoordSet'] = chimera.triggers.addHandler(
						'CoordSet', modCoordSets, None)
		def justCoordSets(trigName, myData, changes):
			if 'activeCoordSet changed' in changes.reasons:
				self.Apply()
		self._handlers['Molecule'] = chimera.triggers.addHandler(
						'Molecule', justCoordSets, None)
		if freqVal == self.FREQ_MOTION:
			self._handlers[chimera.MOTION_STOP] = chimera.triggers\
					.addHandler(chimera.MOTION_STOP,
					self._motionCB, None)
		elif freqVal == self.FREQ_CONTINUOUS:
			def preCB(trigName, myData, changes):
				if 'transformation change' in changes.reasons:
					self._motionCB()
			self._handlers['OpenState'] = chimera.triggers\
					.addHandler('OpenState', preCB, None)
		self.Apply()

	def _locButtonCB(self, butName=None):
		checkSetBut = self.checkLocButtons.button(self.CHECK_SET)
		if self.checkLocButtons.getvalue() == self.CHECK_SET \
		and not self.designated2.atoms():
			checkSetBut.config(fg="red", activeforeground="red")
		else:
			checkSetBut.config(fg="black", activeforeground="black")
		self._updateDesig2Status()

	def _motionCB(self, *args):
		# if all molecule activities are the same (i.e. no possible
		# relative motion), do nothing
		activity = None
		for m in chimera.openModels.list(modelTypes=[chimera.Molecule]):
			if activity is None:
				activity = m.openState.active
			elif activity != m.openState.active:
				self.Apply()
				return

	def _updateDesigStatus(self):
		numAtoms = len(self.designated.atoms())
		if numAtoms:
			statusText = "%d atoms designated" % numAtoms
			color = 'blue'
		else:
			statusText = "No atoms designated"
			color = 'red'
			self.freqButtons.invoke(self.FREQ_APPLY)
		self.desigStatus.config(text=statusText, fg=color)
		self._checkContinuous()

	def _updateDesig2Status(self):
		numAtoms = len(self.designated2.atoms())
		checkSet = self.checkLocButtons.getvalue() == self.CHECK_SET
		color = 'black'
		if numAtoms:
			statusText = "Second set: %d atoms" % numAtoms
		else:
			statusText = "No second set"
			if checkSet:
				color = 'red'
				self.freqButtons.invoke(self.FREQ_APPLY)
		self.desig2Status.config(text=statusText, fg=color)
		if checkSet:
			self._checkContinuous()
Exemplo n.º 16
0
    def fillInUI(self, parent):
        # inter/intra-model; slop; colors; models; replace current;
        # label

        # for removing labels in subsequent passes...
        # (use a selection so I don't have to track model closures)
        self.labelSelection = ItemizedSelection()
        self.labelMap = {}

        self.callbacks = []

        row = 0
        cols = 3

        self.bondColorOption = ColorOption(parent,
                                           row,
                                           'H-bond color',
                                           prefs[BOND_COLOR],
                                           None,
                                           noneOkay=0)

        class HBLineWidthOption(LineWidthOption):
            name = "Line width"
            balloon = "Width of pseudobonds (in pixels)"
            default = prefs[LINE_WIDTH]

        self.lineWidth = HBLineWidthOption(parent,
                                           row + 1,
                                           None,
                                           None,
                                           None,
                                           width=4,
                                           sticky='w')

        self.findMode = Pmw.RadioSelect(parent,
                                        buttontype='radiobutton',
                                        labelpos='n',
                                        pady=0,
                                        orient='vertical',
                                        label_text='Find these bonds:',
                                        hull_borderwidth=2,
                                        hull_relief='ridge')
        self.findMode.add('inter-model')
        self.findMode.add('intra-model')
        self.findMode.add('both')
        self.findMode.invoke('both')
        self.findMode.grid(row=row, column=2, rowspan=2)
        row += 2

        self.relaxParams = RelaxParams(parent, prefs[RELAX_COLOR])
        self.relaxParams.grid(row=row, columnspan=cols, sticky='nsew', padx=2)
        row += 1

        self.restrictModels = Tkinter.IntVar(parent)
        self.restrictModels.set(0)
        self.modelFrame = Tkinter.Frame(parent)
        self.molTexts = ["Restrict to models...", "Restrict to models:"]
        self.restrictCheckBox = Tkinter.Checkbutton(
            self.modelFrame,
            variable=self.restrictModels,
            text=self.molTexts[0],
            command=self._restrictModelsCB)
        self.restrictCheckBox.grid(row=0, column=0)
        from chimera.widgets import MoleculeScrolledListBox
        self.molList = MoleculeScrolledListBox(self.modelFrame,
                                               listbox_selectmode="extended")
        self.modelFrame.rowconfigure(0, weight=1)
        self.modelFrame.grid(row=row, column=0, columnspan=cols, sticky="nsw")
        parent.rowconfigure(row, weight=1)
        row += 1

        self.inSelection = Tkinter.IntVar(parent)
        self.inSelection.set(0)
        f = Tkinter.Frame(parent)
        f.grid(row=row, column=0, columnspan=cols, sticky="w")
        Tkinter.Checkbutton(f,
                            variable=self.inSelection,
                            text="Only find H-bonds with",
                            command=self._useSelChange).grid(row=0,
                                                             column=0,
                                                             sticky="e")
        self.selType = Pmw.OptionMenu(
            f,
            items=["at least one end", "exactly one end", "both ends"],
            initialitem=0,
            menubutton_state="disabled",
            labelpos="e",
            label_text="selected")
        self.selType.grid(row=0, column=1, sticky="w")
        row += 1

        self.revealEnds = Tkinter.IntVar(parent)
        self.revealEnds.set(0)
        Tkinter.Checkbutton(
            parent,
            variable=self.revealEnds,
            text="If endpoint atom hidden, show endpoint residue").grid(
                row=row, column=0, columnspan=cols, sticky="w")
        row += 1

        self.retainCurrent = Tkinter.IntVar(parent)
        self.retainCurrent.set(0)
        Tkinter.Checkbutton(parent,
                            variable=self.retainCurrent,
                            text="Retain currently displayed H-bonds").grid(
                                row=row, column=0, columnspan=cols, sticky="w")
        row += 1

        self.interSubmodel = Tkinter.IntVar(parent)
        self.interSubmodel.set(0)
        # comment out the below since there seems to be no
        # situations where cross-submodel-same-model hbonds
        # are interesting.  If reading pdbrun files occurs, this
        # may change.
        #Tkinter.Checkbutton(parent, variable=self.interSubmodel,
        #	text="Find H-bonds between submodels\n"
        #	     "having same principal model number"
        #	).grid(row=row, column=0, columnspan=cols, sticky="w")
        #row += 1

        self.writeFile = Tkinter.IntVar(parent)
        self.writeFile.set(0)
        Tkinter.Checkbutton(parent,
                            variable=self.writeFile,
                            text="Write information to file").grid(
                                row=row, column=0, columnspan=cols, sticky="w")
        self.fileName = None
        row += 1

        self.writeLog = Tkinter.IntVar(parent)
        self.writeLog.set(0)
        Tkinter.Checkbutton(parent,
                            variable=self.writeLog,
                            text="Write information to reply log").grid(
                                row=row, column=0, columnspan=cols, sticky="w")
        row += 1
Exemplo n.º 17
0
	def _selCavityCB(self, tableSel):
		prefs[EXCLUDE_MOUTH] = self.excludeMouth.variable.get()
		from chimera.selection import ItemizedSelection, mergeCurrent, \
								EXTEND, REMOVE
		cavitySel = ItemizedSelection()
		for cavity in tableSel:
			cavitySel.merge(EXTEND, cavity.pocketInfo["atoms"])
			if prefs[EXCLUDE_MOUTH]:
				cavitySel.merge(REMOVE,
						cavity.mouthInfo["atoms"])
		cavitySel.addImplied()
		# might be no cavities selected...
		cav1 = self.cavities[0]
		someA = (cav1.mouthInfo["atoms"].atoms()
			or cav1.pocketInfo["atoms"].atoms())[0]
		if someA.__destroyed__:
			return
		mol = someA.molecule
		cavitySet = set(cavitySel.atoms())
		from chimera import selectionOperation
		doSelect = self.doSelect.variable.get()
		if doSelect != prefs[DO_SELECT]:
			#if not doSelect:
			#	mergeCurrent(REMOVE, cavitySel)
			prefs[DO_SELECT] = doSelect
		doColor = self.doColor.variable.get()
		if doColor != prefs[DO_COLOR]:
			if not doColor and hasattr(self, '_prevColors'):
				for a, c, sc in self._prevColors:
					if a.__destroyed__:
						continue
					a.color = c
					a.surfaceColor = sc
				delattr(self, '_prevColors')
			prefs[DO_COLOR] = doColor
		if doColor:
			prefs[POCKET_COLOR] = self.pocketColor.rgba
			prefs[NONPOCKET_COLOR] = self.nonpocketColor.rgba
		doSurface = self.doSurface.variable.get()
		if doSurface != prefs[DO_SURFACE]:
			if not doSurface:
				for a in cavitySet:
					a.surfaceDisplay = False
			prefs[DO_SURFACE] = doSurface
		doZoom = self.doZoom.variable.get()
		if doZoom != prefs[DO_ZOOM]:
			if not doZoom:
				from Midas import focus, uncofr
				focus([mol])
				uncofr()
			prefs[DO_ZOOM] = doZoom

		if doSelect:
			selectionOperation(cavitySel)
		if doColor:
			if prefs[POCKET_COLOR] == None:
				pocketColor = None
			else:
				pocketColor = chimera.MaterialColor(
							*prefs[POCKET_COLOR])
			if prefs[NONPOCKET_COLOR] == None:
				nonpocketColor = None
			else:
				nonpocketColor = chimera.MaterialColor(
							*prefs[NONPOCKET_COLOR])
			if not hasattr(self, '_prevColors'):
				self._prevColors = [(a, a.color, a.surfaceColor)
							for a in mol.atoms]
			for a in mol.atoms:
				if a in cavitySet:
					a.surfaceColor = a.color = pocketColor
				else:
					a.surfaceColor = a.color = nonpocketColor
		if doSurface:
			for a in mol.atoms:
				a.surfaceDisplay = a in cavitySet
			surfs = chimera.openModels.list(mol.id, mol.subid,
					modelTypes=[chimera.MSMSModel])
			catsurfs = [s for s in surfs if s.category == "main"]
			if not catsurfs:
				from Midas import surfaceNew
				surfaceNew("main", models=[mol])

		if doZoom and tableSel:
			from Midas import align, focus
			align(cavitySel, mol.atoms)
			focus(cavitySel)
Exemplo n.º 18
0
	def fillInUI(self, parent):
		self._handlers = {}
		desigGroup = Pmw.Group(parent, tag_text="Atoms to Check", hull_padx=2)
		desigGroup.grid(row=0, sticky="ew")
		from chimera.tkgui import windowSystem
		Tkinter.Button(desigGroup.interior(), command=self._desigCB,
				text="Designate").grid(row=0, column=0, sticky='e')
		Tkinter.Label(desigGroup.interior(), text="currently selected"
			" atoms for checking").grid(row=0, column=1, sticky='w')
		self.desigStatus = Tkinter.Label(desigGroup.interior())
		from tkFont import Font
		font = Font(font=self.desigStatus.cget('font'))
		size = int(font.cget('size'))
		if size > 2:
			font.config(size=size-2)
		font.config(weight='normal')
		self.desigStatus.config(font=font)
		from chimera.selection import ItemizedSelection
		self.designated = ItemizedSelection(
					selChangedCB=self._updateDesigStatus)
		self.desigStatus.grid(row=1, column=0, columnspan=2)
		self.designated2 = ItemizedSelection(selChangedCB=self._locButtonCB)
		if windowSystem == 'aqua':
			pady = None
		else:
			pady = 0
		Tkinter.Button(desigGroup.interior(), command=self._desig2CB,
				pady=pady, text="Designate selection as second set"
				).grid(row=3, column=1)
		self.desig2Status = Tkinter.Label(desigGroup.interior())
		if size > 4:
			font2 = Font(font=font)
			font2.config(size=size-4)
		else:
			font2 = font
		self.desig2Status.config(font=font2)
		self.desig2Status.grid(row=4, column=1)
		self.checkLocButtons = Pmw.RadioSelect(desigGroup.interior(),
			pady=0, orient='vertical', buttontype='radiobutton',
			labelpos='w', label_text="Check designated\natoms"
			" against:", command=self._locButtonCB)
		self.checkLocButtons.grid(row=2, column=0, columnspan=2)
		self.checkLocButtons.add("themselves")
		self.checkLocButtons.add("all other atoms")
		self.checkLocButtons.add("other atoms in same model")
		self.checkLocButtons.add(self.CHECK_SET)
		self.checkLocButtons.invoke(1)

		defGroup = Pmw.Group(parent,
			tag_text="Clash/Contact Parameters", hull_padx=2)
		defGroup.grid(row=1, sticky='ew')
		self.clashDef = ClashDef(defGroup.interior(),
					command=self._checkContinuous,
					value=str(prefs[CLASH_THRESHOLD]))
		self.clashDef.grid(row=0, sticky='w')
		self.hbondAllow = HbondAllow(defGroup.interior(),
					command=self._checkContinuous,
					value=str(prefs[HBOND_ALLOWANCE]))
		self.hbondAllow.grid(row=1, sticky='w')
		defaultsFrame = Tkinter.Frame(defGroup.interior())
		defaultsFrame.grid(row=2)
		Tkinter.Label(defaultsFrame, text="Default").grid(
							row=0, column=0)
		Tkinter.Button(defaultsFrame, text="clash", pady=pady,
			command=self._clashDefaultsCB).grid(row=0, column=1)
		Tkinter.Label(defaultsFrame, text="/").grid(row=0, column=2)
		Tkinter.Button(defaultsFrame, text="contact", pady=pady,
			command=self._contactDefaultsCB).grid(row=0, column=3)
		Tkinter.Label(defaultsFrame, text="criteria").grid(
							row=0, column=4)
		bondsFrame = Tkinter.Frame(defGroup.interior())
		bondsFrame.grid(row=3, sticky='w')
		self.bondsApart = Pmw.OptionMenu(bondsFrame, labelpos='w',
			label_text="Ignore contacts of pairs",
			command=self._checkContinuous,
			initialitem=str(prefs[BOND_SEPARATION]),
			items=[str(i+2) for i in range(4)])
		self.bondsApart.grid(row=0, column=0)
		Tkinter.Label(bondsFrame, text="or fewer bonds apart").grid(
							row=0, column=1)
		self.ignoreIntraResVar = Tkinter.IntVar(parent)
		self.ignoreIntraResVar.set(prefs[IGNORE_INTRA_RES])
		Tkinter.Checkbutton(defGroup.interior(), text="Ignore intra-"
			"residue contacts", variable=self.ignoreIntraResVar,
			command=self._checkContinuous
			).grid(row=4)
			
		actionGroup = Pmw.Group(parent, tag_text=
				"Treatment of Clash/Contact Atoms", hull_padx=2)
		actionGroup.grid(row=2, sticky='ew')
		self.actionSelVar = Tkinter.IntVar(parent)
		self.actionSelVar.set(prefs[ACTION_SELECT])
		Tkinter.Checkbutton(actionGroup.interior(), text="Select",
			command=self._checkContinuous,
			variable=self.actionSelVar).grid(row=0, sticky='w')
		self.actionColorVar = Tkinter.IntVar(parent)
		self.actionColorVar.set(prefs[ACTION_COLOR])
		f = Tkinter.Frame(actionGroup.interior())
		f.grid(row=1, sticky='w')
		Tkinter.Checkbutton(f, text="Color",
			command=self._checkContinuous,
			variable=self.actionColorVar).grid(row=0, column=0)
		from CGLtk.color.ColorWell import ColorWell
		self.clashColorWell = ColorWell(f, noneOkay=True,
						callback=self._checkContinuous,
						color=prefs[CLASH_COLOR])
		self.clashColorWell.grid(row=0, column=1)
		Tkinter.Label(f, text=" (and color all other atoms").grid(row=0,
								column=2)
		self.nonclashColorWell = ColorWell(f, noneOkay=True,
						callback=self._checkContinuous,
						color=prefs[NONCLASH_COLOR])
		self.nonclashColorWell.grid(row=0, column=3)
		Tkinter.Label(f, text=")").grid(row=0, column=4)
		self.actionPBVar = Tkinter.IntVar(parent)
		self.actionPBVar.set(prefs[ACTION_PSEUDOBONDS])
		f = Tkinter.Frame(actionGroup.interior())
		f.grid(row=2, sticky='w')
		Tkinter.Checkbutton(f, text="Draw pseudobonds of color",
			command=self._checkContinuous,
			variable=self.actionPBVar).grid(row=0, column=0)
		from CGLtk.color.ColorWell import ColorWell
		self.pbColorWell = ColorWell(f, noneOkay=False,
						callback=self._checkContinuous,
						color=prefs[PB_COLOR])
		self.pbColorWell.grid(row=0, column=1)
		self.pbWidthEntry = Pmw.EntryField(f, labelpos='w',
			label_text=" and width", validate={'validator': 'real',
			'min': 0.01}, entry_width=4, entry_justify="center",
			command=self._checkContinuous,
			value=str(prefs[PB_WIDTH]))
		self.pbWidthEntry.grid(row=0, column=2)
		self.actionAttrVar = Tkinter.IntVar(parent)
		self.actionAttrVar.set(prefs[ACTION_ATTR])
		self.assignAttrButton = Tkinter.Checkbutton(
					actionGroup.interior(),
					text="Assign 'overlap' attribute",
					variable=self.actionAttrVar)
		self.assignAttrButton.grid(row=3, sticky='w')
		self.actionWriteInfoVar = Tkinter.IntVar(parent)
		self.actionWriteInfoVar.set(prefs[ACTION_WRITEINFO])
		self.writeInfoButton = Tkinter.Checkbutton(
			actionGroup.interior(), text="Write information to"
			" file", variable=self.actionWriteInfoVar)
		self.writeInfoButton.grid(row=4, sticky='w')
		self.actionLogInfoVar = Tkinter.IntVar(parent)
		self.actionLogInfoVar.set(prefs[ACTION_REPLYLOG])
		self.logInfoButton = Tkinter.Checkbutton(
			actionGroup.interior(), text="Write information to"
			" reply log", variable=self.actionLogInfoVar)
		self.logInfoButton.grid(row=5, sticky='w')

		freqGroup = Pmw.Group(parent, tag_text="Frequency of Checking",
								hull_padx=2)
		freqGroup.grid(row=3, sticky="ew")
		self.freqButtons = Pmw.RadioSelect(freqGroup.interior(),
			pady=0, orient='vertical', buttontype='radiobutton',
			labelpos='w', label_text= "Check...",
			command=self._freqChangeCB)
		self.freqButtons.grid(sticky='w')
		self.freqButtons.add(self.FREQ_APPLY)
		self.freqButtons.add(self.FREQ_MOTION)
		self.freqButtons.add(self.FREQ_CONTINUOUS)

		self.freqButtons.invoke(0)
		self._updateDesigStatus()
Exemplo n.º 19
0
def writeMol2(models, fileName, status=None, anchor=None, relModel=None,
		hydNamingStyle="sybyl", multimodelHandling="individual",
		skip=None, resNum=True, gaffType=False, gaffFailError=None):
	"""Write a Mol2 file.

	   'models' are the models to write out into a file named 'fileName'.

	   'status', if not None, is a function that takes a string -- used
	   to report the progress of the write.
	   
	   'anchor' is a selection (i.e. instance of a subclass of
	   chimera.selection.Selection) containing atoms/bonds that should
	   be written out to the @SETS section of the file as the rigid
	   framework for flexible ligand docking.

	   'hydNamingStyle' controls whether hydrogen names should be
	   "Sybyl-like" (value: sybyl) or "PDB-like" (value: pdb)
	   -- e.g.  HG21 vs. 1HG2.

	   'multimodelHandling' controls whether multiple models will be
	   combined into a single @MOLECULE section (value: combined) or
	   each given its own section (value: individual).

	   'skip' is a list of atoms to not output

	   'resNum' controls whether residue sequence numbers are included
	   in the substructure name.  Since Sybyl Mol2 files include them,
	   this defaults to True.

	   If 'gaffType' is True, outout GAFF atom types instead of Sybyl
	   atom types.  'gaffFailError', if specified, is the type of error
	   to throw (e.g. UserError) if there is no gaffType attribute for
	   an atom, otherwise throw the standard AttributeError.
	"""

	# open the given file name for writing
	from OpenSave import osOpen
	f = osOpen(fileName, "w")

	sortFunc = serialSort = lambda a1, a2: cmp(a1.coordIndex, a2.coordIndex)

	if isinstance(models, chimera.Molecule):
		models = [models]
	elif isinstance(models, Selection):
		# create a fictitious jumbo model
		if isinstance(models, ItemizedSelection):
			sel = models
		else:
			sel = ItemizedSelection()
			sel.merge(models)
		sel.addImplied()
		class Jumbo:
			def __init__(self, sel):
				self.atoms = sel.atoms()
				self.residues = sel.residues()
				self.bonds = sel.bonds()
				self.name = "(selection)"
		models = [Jumbo(sel)]
		sortFunc = lambda a1, a2: cmp(a1.molecule.id, a2.molecule.id) \
			or cmp(a1.molecule.subid, a2.molecule.subid) \
			or serialSort(a1, a2)
		multimodelHandling = "individual"

	# transform...
	if relModel is None:
		xform = chimera.Xform.identity()
	else:
		xform = relModel.openState.xform
		xform.invert()

	# need to find amide moieties since Sybyl has an explicit amide type
	if status:
		status("Finding amides\n")
	from ChemGroup import findGroup
	amides = findGroup("amide", models)
	amideNs = dict.fromkeys([amide[2] for amide in amides])
	amideCNs = dict.fromkeys([amide[0] for amide in amides])
	amideCNs.update(amideNs)
	amideOs = dict.fromkeys([amide[1] for amide in amides])

	substructureNames = None
	if multimodelHandling == "combined":
		# create a fictitious jumbo model
		class Jumbo:
			def __init__(self, models):
				self.atoms = []
				self.residues = []
				self.bonds = []
				self.name = models[0].name + " (combined)"
				for m in models:
					self.atoms.extend(m.atoms)
					self.residues.extend(m.residues)
					self.bonds.extend(m.bonds)
				# if combining single-residue models,
				# can be more informative to use model name
				# instead of residue type for substructure
				if len(models) == len(self.residues):
					rtypes = [r.type for r in self.residues]
					if len(set(rtypes)) < len(rtypes):
						mnames = [m.name for m in models]
						if len(set(mnames)) == len(mnames):
							self.substructureNames = dict(
								zip(self.residues, mnames))
		models = [Jumbo(models)]
		if hasattr(models[-1], 'substructureNames'):
			substructureNames = models[-1].substructureNames
			delattr(models[-1], 'substructureNames')
		sortFunc = lambda a1, a2: cmp(a1.molecule.id, a2.molecule.id) \
			or cmp(a1.molecule.subid, a2.molecule.subid) \
			or serialSort(a1, a2)

	# write out models
	for mol in models:
		if hasattr(mol, 'mol2comments'):
			for m2c in mol.mol2comments:
				print>>f, m2c
		if hasattr(mol, 'solventInfo' ):
			print>>f, mol.solventInfo

		# molecule section header
		print>>f, "%s" % MOLECULE_HEADER

		# molecule name
		print>>f, "%s" % mol.name

		ATOM_LIST = mol.atoms
		BOND_LIST = mol.bonds
		if skip:
			skip = set(skip)
			ATOM_LIST = [a for a in ATOM_LIST if a not in skip]
			BOND_LIST = [b for b in BOND_LIST
					if b.atoms[0] not in skip
					and b.atoms[1] not in skip]
		RES_LIST  = mol.residues

		# Chimera has an unusual internal order for its atoms, so
		# sort them by input order
		if status:
			status("Putting atoms in input order")
		ATOM_LIST.sort(sortFunc)

		# if anchor is not None, then there will be two entries in
		# the @SETS section of the file...
		if anchor:
			sets = 2
		else:
			sets = 0
		# number of entries for various sections...
		print>>f, "%d %d %d 0 %d" % (len(ATOM_LIST), len(BOND_LIST),
							len(RES_LIST), sets)

		# type of molecule
		if hasattr(mol, "mol2type"):
			mtype = mol.mol2type
		else:
			mtype = "SMALL"
			from chimera.resCode import nucleic3to1, protein3to1
			for r in mol.residues:
				if r.type in protein3to1:
					mtype = "PROTEIN"
					break
				if r.type in nucleic3to1:
					mtype = "NUCLEIC_ACID"
					break
		print>>f, mtype

		# indicate type of charge information
		if hasattr(mol, 'chargeModel'):
			print>>f, mol.chargeModel
		else:
			print>>f, "NO_CHARGES"

		if hasattr(mol, 'mol2comment'):
			print>>f, "\n%s" % mol.mol2comment
		else:
			print>>f, "\n"


		if status:
			status("writing atoms\n")
		# atom section header
		print>>f, "%s" % ATOM_HEADER

		# make a dictionary of residue indices so that we can do
		# quick look ups
		resIndices = {}
		for i, r in enumerate(RES_LIST):
			resIndices[r] = i+1
		for i, atom in enumerate(ATOM_LIST):
			# atom ID, starting from 1
			print>>f, "%7d" % (i+1),

			# atom name, possibly rearranged if it's a hydrogen
			if hydNamingStyle == "sybyl" \
						and not atom.name[0].isalpha():
				atomName = atom.name[1:] + atom.name[0]
			else:
				atomName = atom.name
			print>>f, "%-8s" % atomName,

			# untransformed coordinate position
			coord = xform.apply(atom.xformCoord())
			print>>f, "%9.4f %9.4f %9.4f" % (
						coord.x, coord.y, coord.z),

			# atom type
			if gaffType:
				try:
					atomType = atom.gaffType
				except AttributeError:
					if not gaffFailError:
						raise
					raise gaffFailError("%s has no Amber/GAFF type assigned.\n"
						"Use the AddCharge tool to assign Amber/GAFF types."
						% atom)
			elif hasattr(atom, 'mol2type'):
				atomType = atom.mol2type
			elif atom in amideNs:
				atomType = "N.am"
			elif atom.residue.id.chainId == "water":
				if atom.element.name == "O":
					atomType = "O.t3p"
				else:
					atomType = "H.t3p"
			elif atom.element.name == "N" and len(
			[r for r in atom.minimumRings() if r.aromatic()]) > 0:
				atomType = "N.ar"
			elif atom.idatmType == "C2" and len([nb for nb in atom.neighbors
											if nb.idatmType == "Ng+"]) > 2:
				atomType = "C.cat"
			else:
				try:
					atomType = chimera2sybyl[atom.idatmType]
				except KeyError:
					chimera.replyobj.warning("Atom whose"
						" IDATM type has no equivalent"
						" Sybyl type: %s (type: %s)\n"
						% (atom.oslIdent(),
						atom.idatmType))
					atomType = str(atom.element)
			print>>f, "%-5s" % atomType,

			# residue-related info
			res = atom.residue

			# residue index
			print>>f, "%5d" % resIndices[res],

			# substructure identifier and charge
			if hasattr(atom, 'charge'):
				charge = atom.charge
			else:
				charge = 0.0
			if substructureNames:
				rname = substructureNames[res]
			elif resNum:
				rname = "%3s%-5d" % (res.type, res.id.position)
			else:
				rname = "%3s" % res.type
			print>>f, "%s %9.4f" % (rname, charge)


		if status:
			status("writing bonds\n")
		# bond section header
		print>>f, "%s" % BOND_HEADER


		# make an atom-index dictionary to speed lookups
		atomIndices = {}
		for i, a in enumerate(ATOM_LIST):
			atomIndices[a] = i+1
		for i, bond in enumerate(BOND_LIST):
			a1, a2 = bond.atoms

			# ID
			print>>f, "%6d" % (i+1),

			# atom IDs
			print>>f, "%4d %4d" % (
					atomIndices[a1], atomIndices[a2]),

			# bond order; give it our best shot...
			amideA1 = a1 in amideCNs
			amideA2 = a2 in amideCNs
			if amideA1 and amideA2:
				print>>f, "am"
				continue
			if amideA1 or amideA2:
				if a1 in amideOs or a2 in amideOs:
					print>>f, "2"
				else:
					print>>f, "1"
				continue
				
			aromatic = False
			for ring in bond.minimumRings():
				if ring.aromatic():
					aromatic = True
					break
			if aromatic:
				print>>f, "ar"
				continue

			try:
				geom1 = typeInfo[a1.idatmType].geometry
			except KeyError:
				print>>f, "1"
				continue
			try:
				geom2 = typeInfo[a2.idatmType].geometry
			except KeyError:
				print>>f, "1"
				continue
			if geom1 not in [2,3] or geom2 not in [2,3]:
				print>>f, "1"
				continue
			# if either endpoint atom is in an aromatic ring and
			# the bond isn't, it's a single bond...
			for endp in [a1, a2]:
				aromatic = False
				for ring in endp.minimumRings():
					if ring.aromatic():
						aromatic = True
						break
				if aromatic:
					break
			else:
				# neither endpoint in aromatic ring
				print>>f, "2"
				continue
			print>>f, "1"

		if status:
			status("writing residues")
		# residue section header
		print>>f, "%s" % SUBSTR_HEADER

		for i, res in enumerate(RES_LIST):
			# residue id field
			print>>f, "%6d" % (i+1),

			# residue name field
			if substructureNames:
				rname = substructureNames[res]
			elif resNum:
				rname = "%3s%-4d" % (res.type, res.id.position)
			else:
				rname = "%3s" % res.type
			print>>f, rname,

			# ID of the root atom of the residue
			from chimera.misc import principalAtom
			chainAtom = principalAtom(res)
			if chainAtom is None:
				if hasattr(res, 'atomsMap'):
					chainAtom = res.atoms[0]
				else:
					chainAtom = res.atoms.values()[0][0]
			print>>f, "%5d" % atomIndices[chainAtom],


			print>>f, "RESIDUE           4",

			# Sybyl seems to use chain 'A' when chain ID is blank,
			# so run with that
			chainID = res.id.chainId
			if len(chainID.strip()) != 1:
				chainID = 'A'
			print>>f, "%s     %3s" % (chainID, res.type),

			# number of out-of-substructure bonds
			crossResBonds = 0
			if hasattr(res, "atomsMap"):
				atoms = res.atoms
				for a in atoms:
					for oa in a.bondsMap.keys():
						if oa.residue != res:
							crossResBonds += 1
			else:
				atoms = [a for aList in res.atoms.values()
							for a in aList]
				for a in atoms:
					for oa in a.bonds.keys():
						if oa.residue != res:
							crossResBonds += 1
			print>>f, "%5d" % crossResBonds,
			# print "ROOT" if first or only residue of a chain
			if a.molecule.rootForAtom(a, True).atom.residue == res:
				print>>f, "ROOT"
			else:
				print>>f

		# write flexible ligand docking info
		if anchor:
			if status:
				status("writing anchor info")
			print>>f, "%s" % SET_HEADER
			atomIndices = {}
			for i, a in enumerate(ATOM_LIST):
				atomIndices[a] = i+1
			bondIndices = {}
			for i, b in enumerate(BOND_LIST):
				bondIndices[b] = i+1
			print>>f, "ANCHOR          STATIC     ATOMS    <user>   **** Anchor Atom Set"
			atoms = anchor.atoms()
			print>>f, len(atoms),
			for a in atoms:
				if a in atomIndices:
					print>>f, atomIndices[a],
			print>>f

			print>>f, "RIGID           STATIC     BONDS    <user>   **** Rigid Bond Set"
			bonds = anchor.bonds()
			print>>f, len(bonds),
			for b in bonds:
				if b in bondIndices:
					print>>f, bondIndices[b],
			print>>f

	f.close()
Exemplo n.º 20
0
	def selectRotamers(self, rotamers):
		from chimera import selectionOperation
		from chimera.selection import ItemizedSelection
		rotSel = ItemizedSelection()
		rotSel.add(rotamers)
		selectionOperation(rotSel)
Exemplo n.º 21
0
def createHelices(m, **kw):
    from chimera.specifier import evalSpec
    sel = evalSpec(":/isHelix & backbone.minimal", models=[m])
    residues = sel.residues()
    if not residues:
        return []
    from chimera.misc import oslCmp
    residues.sort(lambda r1, r2: oslCmp(r1.oslIdent(), r2.oslIdent()))
    from chimera import bondsBetween
    from chimera.selection import INTERSECT, ItemizedSelection
    curHelix = []
    axes = []
    from Geometry import geomManager
    geomManager.suspendUpdates()
    while residues:
        if not curHelix:
            r = residues.pop(0)
            curHelix.append(r)
            helixNum = r.ssId
            continue
        if helixNum > -1:
            if helixNum == residues[0].ssId:
                curHelix.append(residues.pop(0))
                continue
        elif bondsBetween(curHelix[-1], residues[0], True):
            curHelix.append(residues.pop(0))
            continue
        resSel = ItemizedSelection()
        resSel.add(curHelix)
        resSel.merge(INTERSECT, sel)
        atoms = resSel.atoms()
        if helixNum < 0:
            created += 1
            helixNum = created
        hname = "%s H%d" % (m.name, helixNum)
        axes.append(axisManager.createAxis(hname, atoms, **kw))
        curHelix = []
    if curHelix:
        resSel = ItemizedSelection()
        resSel.add(curHelix)
        resSel.merge(INTERSECT, sel)
        atoms = resSel.atoms()
        if helixNum < 0:
            created += 1
            helixNum = created
        hname = "%s H%d" % (m.name, helixNum)
        axes.append(axisManager.createAxis(hname, atoms, **kw))
    geomManager.enableUpdates()
    return axes
Exemplo n.º 22
0
 def selectRotamers(self, rotamers):
     from chimera import selectionOperation
     from chimera.selection import ItemizedSelection
     rotSel = ItemizedSelection()
     rotSel.add(rotamers)
     selectionOperation(rotSel)
Exemplo n.º 23
0
class DetectClashDialog(ModelessDialog):
    name = "detect clashes"
    title = "Find Clashes/Contacts"
    provideStatus = True
    statusPosition = "above"
    help = "ContributedSoftware/findclash/findclash.html"

    FREQ_APPLY = "when OK/Apply clicked"
    FREQ_MOTION = "after relative motions (until dialog closed)"
    FREQ_CONTINUOUS = "continuously (until dialog closed)"

    CHECK_SET = "second set of designated atoms"

    def fillInUI(self, parent):
        self._handlers = {}
        desigGroup = Pmw.Group(parent, tag_text="Atoms to Check", hull_padx=2)
        desigGroup.grid(row=0, sticky="ew")
        from chimera.tkgui import windowSystem
        Tkinter.Button(desigGroup.interior(),
                       command=self._desigCB,
                       text="Designate").grid(row=0, column=0, sticky='e')
        Tkinter.Label(desigGroup.interior(),
                      text="currently selected"
                      " atoms for checking").grid(row=0, column=1, sticky='w')
        self.desigStatus = Tkinter.Label(desigGroup.interior())
        from tkFont import Font
        font = Font(font=self.desigStatus.cget('font'))
        size = int(font.cget('size'))
        if size > 2:
            font.config(size=size - 2)
        font.config(weight='normal')
        self.desigStatus.config(font=font)
        from chimera.selection import ItemizedSelection
        self.designated = ItemizedSelection(
            selChangedCB=self._updateDesigStatus)
        self.desigStatus.grid(row=1, column=0, columnspan=2)
        self.designated2 = ItemizedSelection(selChangedCB=self._locButtonCB)
        if windowSystem == 'aqua':
            pady = None
        else:
            pady = 0
        Tkinter.Button(desigGroup.interior(),
                       command=self._desig2CB,
                       pady=pady,
                       text="Designate selection as second set").grid(row=3,
                                                                      column=1)
        self.desig2Status = Tkinter.Label(desigGroup.interior())
        if size > 4:
            font2 = Font(font=font)
            font2.config(size=size - 4)
        else:
            font2 = font
        self.desig2Status.config(font=font2)
        self.desig2Status.grid(row=4, column=1)
        self.checkLocButtons = Pmw.RadioSelect(
            desigGroup.interior(),
            pady=0,
            orient='vertical',
            buttontype='radiobutton',
            labelpos='w',
            label_text="Check designated\natoms"
            " against:",
            command=self._locButtonCB)
        self.checkLocButtons.grid(row=2, column=0, columnspan=2)
        self.checkLocButtons.add("themselves")
        self.checkLocButtons.add("all other atoms")
        self.checkLocButtons.add("other atoms in same model")
        self.checkLocButtons.add(self.CHECK_SET)
        self.checkLocButtons.invoke(1)

        defGroup = Pmw.Group(parent,
                             tag_text="Clash/Contact Parameters",
                             hull_padx=2)
        defGroup.grid(row=1, sticky='ew')
        self.clashDef = ClashDef(defGroup.interior(),
                                 command=self._checkContinuous,
                                 value=str(prefs[CLASH_THRESHOLD]))
        self.clashDef.grid(row=0, sticky='w')
        self.hbondAllow = HbondAllow(defGroup.interior(),
                                     command=self._checkContinuous,
                                     value=str(prefs[HBOND_ALLOWANCE]))
        self.hbondAllow.grid(row=1, sticky='w')
        defaultsFrame = Tkinter.Frame(defGroup.interior())
        defaultsFrame.grid(row=2)
        Tkinter.Label(defaultsFrame, text="Default").grid(row=0, column=0)
        Tkinter.Button(defaultsFrame,
                       text="clash",
                       pady=pady,
                       command=self._clashDefaultsCB).grid(row=0, column=1)
        Tkinter.Label(defaultsFrame, text="/").grid(row=0, column=2)
        Tkinter.Button(defaultsFrame,
                       text="contact",
                       pady=pady,
                       command=self._contactDefaultsCB).grid(row=0, column=3)
        Tkinter.Label(defaultsFrame, text="criteria").grid(row=0, column=4)
        bondsFrame = Tkinter.Frame(defGroup.interior())
        bondsFrame.grid(row=3, sticky='w')
        self.bondsApart = Pmw.OptionMenu(bondsFrame,
                                         labelpos='w',
                                         label_text="Ignore contacts of pairs",
                                         command=self._checkContinuous,
                                         initialitem=str(
                                             prefs[BOND_SEPARATION]),
                                         items=[str(i + 2) for i in range(4)])
        self.bondsApart.grid(row=0, column=0)
        Tkinter.Label(bondsFrame, text="or fewer bonds apart").grid(row=0,
                                                                    column=1)
        self.ignoreIntraResVar = Tkinter.IntVar(parent)
        self.ignoreIntraResVar.set(prefs[IGNORE_INTRA_RES])
        Tkinter.Checkbutton(defGroup.interior(),
                            text="Ignore intra-"
                            "residue contacts",
                            variable=self.ignoreIntraResVar,
                            command=self._checkContinuous).grid(row=4)

        actionGroup = Pmw.Group(parent,
                                tag_text="Treatment of Clash/Contact Atoms",
                                hull_padx=2)
        actionGroup.grid(row=2, sticky='ew')
        self.actionSelVar = Tkinter.IntVar(parent)
        self.actionSelVar.set(prefs[ACTION_SELECT])
        Tkinter.Checkbutton(actionGroup.interior(),
                            text="Select",
                            command=self._checkContinuous,
                            variable=self.actionSelVar).grid(row=0, sticky='w')
        self.actionColorVar = Tkinter.IntVar(parent)
        self.actionColorVar.set(prefs[ACTION_COLOR])
        f = Tkinter.Frame(actionGroup.interior())
        f.grid(row=1, sticky='w')
        Tkinter.Checkbutton(f,
                            text="Color",
                            command=self._checkContinuous,
                            variable=self.actionColorVar).grid(row=0, column=0)
        from CGLtk.color.ColorWell import ColorWell
        self.clashColorWell = ColorWell(f,
                                        noneOkay=True,
                                        callback=self._checkContinuous,
                                        color=prefs[CLASH_COLOR])
        self.clashColorWell.grid(row=0, column=1)
        Tkinter.Label(f, text=" (and color all other atoms").grid(row=0,
                                                                  column=2)
        self.nonclashColorWell = ColorWell(f,
                                           noneOkay=True,
                                           callback=self._checkContinuous,
                                           color=prefs[NONCLASH_COLOR])
        self.nonclashColorWell.grid(row=0, column=3)
        Tkinter.Label(f, text=")").grid(row=0, column=4)
        self.actionPBVar = Tkinter.IntVar(parent)
        self.actionPBVar.set(prefs[ACTION_PSEUDOBONDS])
        f = Tkinter.Frame(actionGroup.interior())
        f.grid(row=2, sticky='w')
        Tkinter.Checkbutton(f,
                            text="Draw pseudobonds of color",
                            command=self._checkContinuous,
                            variable=self.actionPBVar).grid(row=0, column=0)
        from CGLtk.color.ColorWell import ColorWell
        self.pbColorWell = ColorWell(f,
                                     noneOkay=False,
                                     callback=self._checkContinuous,
                                     color=prefs[PB_COLOR])
        self.pbColorWell.grid(row=0, column=1)
        self.pbWidthEntry = Pmw.EntryField(f,
                                           labelpos='w',
                                           label_text=" and width",
                                           validate={
                                               'validator': 'real',
                                               'min': 0.01
                                           },
                                           entry_width=4,
                                           entry_justify="center",
                                           command=self._checkContinuous,
                                           value=str(prefs[PB_WIDTH]))
        self.pbWidthEntry.grid(row=0, column=2)
        self.actionAttrVar = Tkinter.IntVar(parent)
        self.actionAttrVar.set(prefs[ACTION_ATTR])
        self.assignAttrButton = Tkinter.Checkbutton(
            actionGroup.interior(),
            text="Assign 'overlap' attribute",
            variable=self.actionAttrVar)
        self.assignAttrButton.grid(row=3, sticky='w')
        self.actionWriteInfoVar = Tkinter.IntVar(parent)
        self.actionWriteInfoVar.set(prefs[ACTION_WRITEINFO])
        self.writeInfoButton = Tkinter.Checkbutton(
            actionGroup.interior(),
            text="Write information to"
            " file",
            variable=self.actionWriteInfoVar)
        self.writeInfoButton.grid(row=4, sticky='w')
        self.actionLogInfoVar = Tkinter.IntVar(parent)
        self.actionLogInfoVar.set(prefs[ACTION_REPLYLOG])
        self.logInfoButton = Tkinter.Checkbutton(
            actionGroup.interior(),
            text="Write information to"
            " reply log",
            variable=self.actionLogInfoVar)
        self.logInfoButton.grid(row=5, sticky='w')

        freqGroup = Pmw.Group(parent,
                              tag_text="Frequency of Checking",
                              hull_padx=2)
        freqGroup.grid(row=3, sticky="ew")
        self.freqButtons = Pmw.RadioSelect(freqGroup.interior(),
                                           pady=0,
                                           orient='vertical',
                                           buttontype='radiobutton',
                                           labelpos='w',
                                           label_text="Check...",
                                           command=self._freqChangeCB)
        self.freqButtons.grid(sticky='w')
        self.freqButtons.add(self.FREQ_APPLY)
        self.freqButtons.add(self.FREQ_MOTION)
        self.freqButtons.add(self.FREQ_CONTINUOUS)

        self.freqButtons.invoke(0)
        self._updateDesigStatus()

    def OK(self, *args):
        # use main status line if dialog closing
        from chimera.replyobj import status
        self.status = status
        ModelessDialog.OK(self, *args)

    def Apply(self, *args):
        # workaround: remove pseudobonds before recreating colors
        # so C++ layer doesn't end up with pointers to deleted
        # colors in obscure circumstances
        from DetectClash import nukeGroup
        nukeGroup()
        from chimera import UserError
        self.status("")
        checkAtoms = self.designated.atoms()
        if not checkAtoms:
            self.enter()
            raise UserError("No atoms designated for clash detection")
        self.clashDef['command'] = None
        self.clashDef.invoke()
        self.clashDef['command'] = self._checkContinuous
        if not self.clashDef.valid():
            self.enter()
            raise UserError("Invalid clash amount"
                            " (in Clash/Contact Parameters)")
        prefs[CLASH_THRESHOLD] = float(self.clashDef.getvalue())
        self.hbondAllow['command'] = None
        self.hbondAllow.invoke()
        self.hbondAllow['command'] = self._checkContinuous
        if not self.hbondAllow.valid():
            self.enter()
            raise UserError("Invalid H-bond overlap amount"
                            " (in Clash/Contact Parameters)")
        prefs[HBOND_ALLOWANCE] = float(self.hbondAllow.getvalue())
        prefs[BOND_SEPARATION] = int(self.bondsApart.getvalue())
        prefs[IGNORE_INTRA_RES] = self.ignoreIntraResVar.get()
        checkVal = self.checkLocButtons.getvalue()
        if checkVal == "themselves":
            test = "self"
        elif checkVal == "all other atoms":
            test = "others"
        elif checkVal == "other atoms in same model":
            test = "model"
        else:
            test = self.designated2.atoms()
            if not test:
                self.enter()
                raise UserError("No second-set atoms designated")
        actionAttr = prefs[ACTION_ATTR] = self.actionAttrVar.get()
        actionSelect = prefs[ACTION_SELECT] = self.actionSelVar.get()
        actionColor = prefs[ACTION_COLOR] = self.actionColorVar.get()
        actionPseudobonds = prefs[ACTION_PSEUDOBONDS] = \
             self.actionPBVar.get()
        actionWriteInfo = prefs[ACTION_WRITEINFO] = \
            self.actionWriteInfoVar.get()
        actionLogInfo = prefs[ACTION_REPLYLOG] = \
            self.actionLogInfoVar.get()
        if self.freqButtons.getvalue() != self.FREQ_APPLY:
            actionAttr = actionWriteInfo = actionLogInfo = False
        if not actionAttr and not actionSelect and not actionColor \
        and not actionPseudobonds and not actionWriteInfo \
        and not actionLogInfo:
            self.enter()
            raise UserError("No actions selected for clashes")
        self.status("Checking for clashes")
        clashColor = nonclashColor = None
        if actionColor:
            prefs[CLASH_COLOR] = self.clashColorWell.rgba
            prefs[NONCLASH_COLOR] = self.nonclashColorWell.rgba
            if prefs[CLASH_COLOR] == None:
                clashColor = None
            else:
                clashColor = chimera.MaterialColor(*prefs[CLASH_COLOR])
            if prefs[NONCLASH_COLOR] == None:
                nonclashColor = None
            else:
                nonclashColor = chimera.MaterialColor(*prefs[NONCLASH_COLOR])
        pbColor = None
        if actionPseudobonds:
            prefs[PB_COLOR] = self.pbColorWell.rgba
            pbColor = chimera.MaterialColor(*prefs[PB_COLOR])
            self.pbWidthEntry['command'] = None
            self.pbWidthEntry.invoke()
            self.pbWidthEntry['command'] = self._checkContinuous
            if not self.pbWidthEntry.valid():
                self.enter()
                raise UserError("Invalid pseudobond width "
                                "(in Treatment of Clash/Contact Atoms)")
            prefs[PB_WIDTH] = float(self.pbWidthEntry.getvalue())

        from DetectClash import cmdDetectClash
        if actionWriteInfo:
            saveFile = "-"
        else:
            saveFile = None
        clashes = cmdDetectClash(checkAtoms,
                                 test=test,
                                 overlapCutoff=prefs[CLASH_THRESHOLD],
                                 hbondAllowance=prefs[HBOND_ALLOWANCE],
                                 bondSeparation=prefs[BOND_SEPARATION],
                                 ignoreIntraRes=prefs[IGNORE_INTRA_RES],
                                 setAttrs=actionAttr,
                                 selectClashes=actionSelect,
                                 colorClashes=actionColor,
                                 clashColor=clashColor,
                                 nonclashColor=nonclashColor,
                                 makePseudobonds=actionPseudobonds,
                                 pbColor=pbColor,
                                 lineWidth=prefs[PB_WIDTH],
                                 saveFile=saveFile,
                                 log=actionLogInfo,
                                 summary=self.status)
        if actionAttr:
            from ShowAttr import ShowAttrDialog
            from chimera import dialogs
            from DetectClash import attrName
            d = dialogs.display(ShowAttrDialog.name)
            d.configure(attrsOf="atoms", attrName=attrName, mode="Render")

    def Close(self):
        ModelessDialog.Close(self)
        if self.freqButtons.getvalue() != self.FREQ_APPLY:
            self.freqButtons.invoke(self.FREQ_APPLY)

    def _checkContinuous(self, *args):
        if self.freqButtons.getvalue() == self.FREQ_CONTINUOUS:
            self.Apply()

    def _clashDefaultsCB(self):
        from prefs import defaults
        self.hbondAllow.setvalue(str(defaults[HBOND_ALLOWANCE]))
        self.clashDef.setvalue(str(defaults[CLASH_THRESHOLD]))
        self._checkContinuous()

    def _clearHandlers(self):
        while self._handlers:
            trigName, handler = self._handlers.popitem()
            chimera.triggers.deleteHandler(trigName, handler)

    def _contactDefaultsCB(self):
        self.hbondAllow.setvalue("0.0")
        self.clashDef.setvalue("-0.4")
        self._checkContinuous()

    def _desigCB(self):
        self.designated.clear()
        self.designated.add(chimera.selection.currentAtoms())
        self._updateDesigStatus()

    def _desig2CB(self):
        self.designated2.clear()
        self.designated2.add(chimera.selection.currentAtoms())
        self._locButtonCB()
        self._updateDesig2Status()

    def _freqChangeCB(self, freqVal):
        self._clearHandlers()
        if freqVal == self.FREQ_APPLY:
            self.assignAttrButton.configure(state='normal')
            self.writeInfoButton.configure(state='normal')
            self.logInfoButton.configure(state='normal')
            return
        self.assignAttrButton.configure(state='disabled')
        self.writeInfoButton.configure(state='disabled')
        self.logInfoButton.configure(state='disabled')

        def modCoordSets(trigName, myData, changes):
            if changes.modified:
                self.Apply()

        self._handlers['CoordSet'] = chimera.triggers.addHandler(
            'CoordSet', modCoordSets, None)

        def justCoordSets(trigName, myData, changes):
            if 'activeCoordSet changed' in changes.reasons:
                self.Apply()

        self._handlers['Molecule'] = chimera.triggers.addHandler(
            'Molecule', justCoordSets, None)
        if freqVal == self.FREQ_MOTION:
            self._handlers[chimera.MOTION_STOP] = chimera.triggers\
              .addHandler(chimera.MOTION_STOP,
              self._motionCB, None)
        elif freqVal == self.FREQ_CONTINUOUS:

            def preCB(trigName, myData, changes):
                if 'transformation change' in changes.reasons:
                    self._motionCB()
            self._handlers['OpenState'] = chimera.triggers\
              .addHandler('OpenState', preCB, None)
        self.Apply()

    def _locButtonCB(self, butName=None):
        checkSetBut = self.checkLocButtons.button(self.CHECK_SET)
        if self.checkLocButtons.getvalue() == self.CHECK_SET \
        and not self.designated2.atoms():
            checkSetBut.config(fg="red", activeforeground="red")
        else:
            checkSetBut.config(fg="black", activeforeground="black")
        self._updateDesig2Status()

    def _motionCB(self, *args):
        # if all molecule activities are the same (i.e. no possible
        # relative motion), do nothing
        activity = None
        for m in chimera.openModels.list(modelTypes=[chimera.Molecule]):
            if activity is None:
                activity = m.openState.active
            elif activity != m.openState.active:
                self.Apply()
                return

    def _updateDesigStatus(self):
        numAtoms = len(self.designated.atoms())
        if numAtoms:
            statusText = "%d atoms designated" % numAtoms
            color = 'blue'
        else:
            statusText = "No atoms designated"
            color = 'red'
            self.freqButtons.invoke(self.FREQ_APPLY)
        self.desigStatus.config(text=statusText, fg=color)
        self._checkContinuous()

    def _updateDesig2Status(self):
        numAtoms = len(self.designated2.atoms())
        checkSet = self.checkLocButtons.getvalue() == self.CHECK_SET
        color = 'black'
        if numAtoms:
            statusText = "Second set: %d atoms" % numAtoms
        else:
            statusText = "No second set"
            if checkSet:
                color = 'red'
                self.freqButtons.invoke(self.FREQ_APPLY)
        self.desig2Status.config(text=statusText, fg=color)
        if checkSet:
            self._checkContinuous()
Exemplo n.º 24
0
    def fillInUI(self, parent):
        self._handlers = {}
        desigGroup = Pmw.Group(parent, tag_text="Atoms to Check", hull_padx=2)
        desigGroup.grid(row=0, sticky="ew")
        from chimera.tkgui import windowSystem
        Tkinter.Button(desigGroup.interior(),
                       command=self._desigCB,
                       text="Designate").grid(row=0, column=0, sticky='e')
        Tkinter.Label(desigGroup.interior(),
                      text="currently selected"
                      " atoms for checking").grid(row=0, column=1, sticky='w')
        self.desigStatus = Tkinter.Label(desigGroup.interior())
        from tkFont import Font
        font = Font(font=self.desigStatus.cget('font'))
        size = int(font.cget('size'))
        if size > 2:
            font.config(size=size - 2)
        font.config(weight='normal')
        self.desigStatus.config(font=font)
        from chimera.selection import ItemizedSelection
        self.designated = ItemizedSelection(
            selChangedCB=self._updateDesigStatus)
        self.desigStatus.grid(row=1, column=0, columnspan=2)
        self.designated2 = ItemizedSelection(selChangedCB=self._locButtonCB)
        if windowSystem == 'aqua':
            pady = None
        else:
            pady = 0
        Tkinter.Button(desigGroup.interior(),
                       command=self._desig2CB,
                       pady=pady,
                       text="Designate selection as second set").grid(row=3,
                                                                      column=1)
        self.desig2Status = Tkinter.Label(desigGroup.interior())
        if size > 4:
            font2 = Font(font=font)
            font2.config(size=size - 4)
        else:
            font2 = font
        self.desig2Status.config(font=font2)
        self.desig2Status.grid(row=4, column=1)
        self.checkLocButtons = Pmw.RadioSelect(
            desigGroup.interior(),
            pady=0,
            orient='vertical',
            buttontype='radiobutton',
            labelpos='w',
            label_text="Check designated\natoms"
            " against:",
            command=self._locButtonCB)
        self.checkLocButtons.grid(row=2, column=0, columnspan=2)
        self.checkLocButtons.add("themselves")
        self.checkLocButtons.add("all other atoms")
        self.checkLocButtons.add("other atoms in same model")
        self.checkLocButtons.add(self.CHECK_SET)
        self.checkLocButtons.invoke(1)

        defGroup = Pmw.Group(parent,
                             tag_text="Clash/Contact Parameters",
                             hull_padx=2)
        defGroup.grid(row=1, sticky='ew')
        self.clashDef = ClashDef(defGroup.interior(),
                                 command=self._checkContinuous,
                                 value=str(prefs[CLASH_THRESHOLD]))
        self.clashDef.grid(row=0, sticky='w')
        self.hbondAllow = HbondAllow(defGroup.interior(),
                                     command=self._checkContinuous,
                                     value=str(prefs[HBOND_ALLOWANCE]))
        self.hbondAllow.grid(row=1, sticky='w')
        defaultsFrame = Tkinter.Frame(defGroup.interior())
        defaultsFrame.grid(row=2)
        Tkinter.Label(defaultsFrame, text="Default").grid(row=0, column=0)
        Tkinter.Button(defaultsFrame,
                       text="clash",
                       pady=pady,
                       command=self._clashDefaultsCB).grid(row=0, column=1)
        Tkinter.Label(defaultsFrame, text="/").grid(row=0, column=2)
        Tkinter.Button(defaultsFrame,
                       text="contact",
                       pady=pady,
                       command=self._contactDefaultsCB).grid(row=0, column=3)
        Tkinter.Label(defaultsFrame, text="criteria").grid(row=0, column=4)
        bondsFrame = Tkinter.Frame(defGroup.interior())
        bondsFrame.grid(row=3, sticky='w')
        self.bondsApart = Pmw.OptionMenu(bondsFrame,
                                         labelpos='w',
                                         label_text="Ignore contacts of pairs",
                                         command=self._checkContinuous,
                                         initialitem=str(
                                             prefs[BOND_SEPARATION]),
                                         items=[str(i + 2) for i in range(4)])
        self.bondsApart.grid(row=0, column=0)
        Tkinter.Label(bondsFrame, text="or fewer bonds apart").grid(row=0,
                                                                    column=1)
        self.ignoreIntraResVar = Tkinter.IntVar(parent)
        self.ignoreIntraResVar.set(prefs[IGNORE_INTRA_RES])
        Tkinter.Checkbutton(defGroup.interior(),
                            text="Ignore intra-"
                            "residue contacts",
                            variable=self.ignoreIntraResVar,
                            command=self._checkContinuous).grid(row=4)

        actionGroup = Pmw.Group(parent,
                                tag_text="Treatment of Clash/Contact Atoms",
                                hull_padx=2)
        actionGroup.grid(row=2, sticky='ew')
        self.actionSelVar = Tkinter.IntVar(parent)
        self.actionSelVar.set(prefs[ACTION_SELECT])
        Tkinter.Checkbutton(actionGroup.interior(),
                            text="Select",
                            command=self._checkContinuous,
                            variable=self.actionSelVar).grid(row=0, sticky='w')
        self.actionColorVar = Tkinter.IntVar(parent)
        self.actionColorVar.set(prefs[ACTION_COLOR])
        f = Tkinter.Frame(actionGroup.interior())
        f.grid(row=1, sticky='w')
        Tkinter.Checkbutton(f,
                            text="Color",
                            command=self._checkContinuous,
                            variable=self.actionColorVar).grid(row=0, column=0)
        from CGLtk.color.ColorWell import ColorWell
        self.clashColorWell = ColorWell(f,
                                        noneOkay=True,
                                        callback=self._checkContinuous,
                                        color=prefs[CLASH_COLOR])
        self.clashColorWell.grid(row=0, column=1)
        Tkinter.Label(f, text=" (and color all other atoms").grid(row=0,
                                                                  column=2)
        self.nonclashColorWell = ColorWell(f,
                                           noneOkay=True,
                                           callback=self._checkContinuous,
                                           color=prefs[NONCLASH_COLOR])
        self.nonclashColorWell.grid(row=0, column=3)
        Tkinter.Label(f, text=")").grid(row=0, column=4)
        self.actionPBVar = Tkinter.IntVar(parent)
        self.actionPBVar.set(prefs[ACTION_PSEUDOBONDS])
        f = Tkinter.Frame(actionGroup.interior())
        f.grid(row=2, sticky='w')
        Tkinter.Checkbutton(f,
                            text="Draw pseudobonds of color",
                            command=self._checkContinuous,
                            variable=self.actionPBVar).grid(row=0, column=0)
        from CGLtk.color.ColorWell import ColorWell
        self.pbColorWell = ColorWell(f,
                                     noneOkay=False,
                                     callback=self._checkContinuous,
                                     color=prefs[PB_COLOR])
        self.pbColorWell.grid(row=0, column=1)
        self.pbWidthEntry = Pmw.EntryField(f,
                                           labelpos='w',
                                           label_text=" and width",
                                           validate={
                                               'validator': 'real',
                                               'min': 0.01
                                           },
                                           entry_width=4,
                                           entry_justify="center",
                                           command=self._checkContinuous,
                                           value=str(prefs[PB_WIDTH]))
        self.pbWidthEntry.grid(row=0, column=2)
        self.actionAttrVar = Tkinter.IntVar(parent)
        self.actionAttrVar.set(prefs[ACTION_ATTR])
        self.assignAttrButton = Tkinter.Checkbutton(
            actionGroup.interior(),
            text="Assign 'overlap' attribute",
            variable=self.actionAttrVar)
        self.assignAttrButton.grid(row=3, sticky='w')
        self.actionWriteInfoVar = Tkinter.IntVar(parent)
        self.actionWriteInfoVar.set(prefs[ACTION_WRITEINFO])
        self.writeInfoButton = Tkinter.Checkbutton(
            actionGroup.interior(),
            text="Write information to"
            " file",
            variable=self.actionWriteInfoVar)
        self.writeInfoButton.grid(row=4, sticky='w')
        self.actionLogInfoVar = Tkinter.IntVar(parent)
        self.actionLogInfoVar.set(prefs[ACTION_REPLYLOG])
        self.logInfoButton = Tkinter.Checkbutton(
            actionGroup.interior(),
            text="Write information to"
            " reply log",
            variable=self.actionLogInfoVar)
        self.logInfoButton.grid(row=5, sticky='w')

        freqGroup = Pmw.Group(parent,
                              tag_text="Frequency of Checking",
                              hull_padx=2)
        freqGroup.grid(row=3, sticky="ew")
        self.freqButtons = Pmw.RadioSelect(freqGroup.interior(),
                                           pady=0,
                                           orient='vertical',
                                           buttontype='radiobutton',
                                           labelpos='w',
                                           label_text="Check...",
                                           command=self._freqChangeCB)
        self.freqButtons.grid(sticky='w')
        self.freqButtons.add(self.FREQ_APPLY)
        self.freqButtons.add(self.FREQ_MOTION)
        self.freqButtons.add(self.FREQ_CONTINUOUS)

        self.freqButtons.invoke(0)
        self._updateDesigStatus()
def writeMol2(models,
              fileName,
              status=None,
              anchor=None,
              relModel=None,
              hydNamingStyle="sybyl",
              multimodelHandling="individual",
              skip=None,
              resNum=True,
              gaffType=False,
              gaffFailError=None):
    """Write a Mol2 file.

	   'models' are the models to write out into a file named 'fileName'.

	   'status', if not None, is a function that takes a string -- used
	   to report the progress of the write.
	   
	   'anchor' is a selection (i.e. instance of a subclass of
	   chimera.selection.Selection) containing atoms/bonds that should
	   be written out to the @SETS section of the file as the rigid
	   framework for flexible ligand docking.

	   'hydNamingStyle' controls whether hydrogen names should be
	   "Sybyl-like" (value: sybyl) or "PDB-like" (value: pdb)
	   -- e.g.  HG21 vs. 1HG2.

	   'multimodelHandling' controls whether multiple models will be
	   combined into a single @MOLECULE section (value: combined) or
	   each given its own section (value: individual).

	   'skip' is a list of atoms to not output

	   'resNum' controls whether residue sequence numbers are included
	   in the substructure name.  Since Sybyl Mol2 files include them,
	   this defaults to True.

	   If 'gaffType' is True, outout GAFF atom types instead of Sybyl
	   atom types.  'gaffFailError', if specified, is the type of error
	   to throw (e.g. UserError) if there is no gaffType attribute for
	   an atom, otherwise throw the standard AttributeError.
	"""

    # open the given file name for writing
    from OpenSave import osOpen
    f = osOpen(fileName, "w")

    sortFunc = serialSort = lambda a1, a2: cmp(a1.coordIndex, a2.coordIndex)

    if isinstance(models, chimera.Molecule):
        models = [models]
    elif isinstance(models, Selection):
        # create a fictitious jumbo model
        if isinstance(models, ItemizedSelection):
            sel = models
        else:
            sel = ItemizedSelection()
            sel.merge(models)
        sel.addImplied()

        class Jumbo:
            def __init__(self, sel):
                self.atoms = sel.atoms()
                self.residues = sel.residues()
                self.bonds = sel.bonds()
                self.name = "(selection)"

        models = [Jumbo(sel)]
        sortFunc = lambda a1, a2: cmp(a1.molecule.id, a2.molecule.id) \
         or cmp(a1.molecule.subid, a2.molecule.subid) \
         or serialSort(a1, a2)
        multimodelHandling = "individual"

    # transform...
    if relModel is None:
        xform = chimera.Xform.identity()
    else:
        xform = relModel.openState.xform
        xform.invert()

    # need to find amide moieties since Sybyl has an explicit amide type
    if status:
        status("Finding amides\n")
    from ChemGroup import findGroup
    amides = findGroup("amide", models)
    amideNs = dict.fromkeys([amide[2] for amide in amides])
    amideCNs = dict.fromkeys([amide[0] for amide in amides])
    amideCNs.update(amideNs)
    amideOs = dict.fromkeys([amide[1] for amide in amides])

    substructureNames = None
    if multimodelHandling == "combined":
        # create a fictitious jumbo model
        class Jumbo:
            def __init__(self, models):
                self.atoms = []
                self.residues = []
                self.bonds = []
                self.name = models[0].name + " (combined)"
                for m in models:
                    self.atoms.extend(m.atoms)
                    self.residues.extend(m.residues)
                    self.bonds.extend(m.bonds)
                # if combining single-residue models,
                # can be more informative to use model name
                # instead of residue type for substructure
                if len(models) == len(self.residues):
                    rtypes = [r.type for r in self.residues]
                    if len(set(rtypes)) < len(rtypes):
                        mnames = [m.name for m in models]
                        if len(set(mnames)) == len(mnames):
                            self.substructureNames = dict(
                                zip(self.residues, mnames))

        models = [Jumbo(models)]
        if hasattr(models[-1], 'substructureNames'):
            substructureNames = models[-1].substructureNames
            delattr(models[-1], 'substructureNames')
        sortFunc = lambda a1, a2: cmp(a1.molecule.id, a2.molecule.id) \
         or cmp(a1.molecule.subid, a2.molecule.subid) \
         or serialSort(a1, a2)

    # write out models
    for mol in models:
        if hasattr(mol, 'mol2comments'):
            for m2c in mol.mol2comments:
                print >> f, m2c
        if hasattr(mol, 'solventInfo'):
            print >> f, mol.solventInfo

        # molecule section header
        print >> f, "%s" % MOLECULE_HEADER

        # molecule name
        print >> f, "%s" % mol.name

        ATOM_LIST = mol.atoms
        BOND_LIST = mol.bonds
        if skip:
            skip = set(skip)
            ATOM_LIST = [a for a in ATOM_LIST if a not in skip]
            BOND_LIST = [
                b for b in BOND_LIST
                if b.atoms[0] not in skip and b.atoms[1] not in skip
            ]
        RES_LIST = mol.residues

        # Chimera has an unusual internal order for its atoms, so
        # sort them by input order
        if status:
            status("Putting atoms in input order")
        ATOM_LIST.sort(sortFunc)

        # if anchor is not None, then there will be two entries in
        # the @SETS section of the file...
        if anchor:
            sets = 2
        else:
            sets = 0
        # number of entries for various sections...
        print >> f, "%d %d %d 0 %d" % (len(ATOM_LIST), len(BOND_LIST),
                                       len(RES_LIST), sets)

        # type of molecule
        if hasattr(mol, "mol2type"):
            mtype = mol.mol2type
        else:
            mtype = "SMALL"
            from chimera.resCode import nucleic3to1, protein3to1
            for r in mol.residues:
                if r.type in protein3to1:
                    mtype = "PROTEIN"
                    break
                if r.type in nucleic3to1:
                    mtype = "NUCLEIC_ACID"
                    break
        print >> f, mtype

        # indicate type of charge information
        if hasattr(mol, 'chargeModel'):
            print >> f, mol.chargeModel
        else:
            print >> f, "NO_CHARGES"

        if hasattr(mol, 'mol2comment'):
            print >> f, "\n%s" % mol.mol2comment
        else:
            print >> f, "\n"

        if status:
            status("writing atoms\n")
        # atom section header
        print >> f, "%s" % ATOM_HEADER

        # make a dictionary of residue indices so that we can do
        # quick look ups
        resIndices = {}
        for i, r in enumerate(RES_LIST):
            resIndices[r] = i + 1
        for i, atom in enumerate(ATOM_LIST):
            # atom ID, starting from 1
            print >> f, "%7d" % (i + 1),

            # atom name, possibly rearranged if it's a hydrogen
            if hydNamingStyle == "sybyl" \
               and not atom.name[0].isalpha():
                atomName = atom.name[1:] + atom.name[0]
            else:
                atomName = atom.name
            print >> f, "%-8s" % atomName,

            # untransformed coordinate position
            coord = xform.apply(atom.xformCoord())
            print >> f, "%9.4f %9.4f %9.4f" % (coord.x, coord.y, coord.z),

            # atom type
            if gaffType:
                try:
                    atomType = atom.gaffType
                except AttributeError:
                    if not gaffFailError:
                        raise
                    raise gaffFailError(
                        "%s has no Amber/GAFF type assigned.\n"
                        "Use the AddCharge tool to assign Amber/GAFF types." %
                        atom)
            elif hasattr(atom, 'mol2type'):
                atomType = atom.mol2type
            elif atom in amideNs:
                atomType = "N.am"
            elif atom.residue.id.chainId == "water":
                if atom.element.name == "O":
                    atomType = "O.t3p"
                else:
                    atomType = "H.t3p"
            elif atom.element.name == "N" and len(
                [r for r in atom.minimumRings() if r.aromatic()]) > 0:
                atomType = "N.ar"
            elif atom.idatmType == "C2" and len(
                [nb for nb in atom.neighbors if nb.idatmType == "Ng+"]) > 2:
                atomType = "C.cat"
            else:
                try:
                    atomType = chimera2sybyl[atom.idatmType]
                except KeyError:
                    chimera.replyobj.warning("Atom whose"
                                             " IDATM type has no equivalent"
                                             " Sybyl type: %s (type: %s)\n" %
                                             (atom.oslIdent(), atom.idatmType))
                    atomType = str(atom.element)
            print >> f, "%-5s" % atomType,

            # residue-related info
            res = atom.residue

            # residue index
            print >> f, "%5d" % resIndices[res],

            # substructure identifier and charge
            if hasattr(atom, 'charge'):
                charge = atom.charge
            else:
                charge = 0.0
            if substructureNames:
                rname = substructureNames[res]
            elif resNum:
                rname = "%3s%-5d" % (res.type, res.id.position)
            else:
                rname = "%3s" % res.type
            print >> f, "%s %9.4f" % (rname, charge)

        if status:
            status("writing bonds\n")
        # bond section header
        print >> f, "%s" % BOND_HEADER

        # make an atom-index dictionary to speed lookups
        atomIndices = {}
        for i, a in enumerate(ATOM_LIST):
            atomIndices[a] = i + 1
        for i, bond in enumerate(BOND_LIST):
            a1, a2 = bond.atoms

            # ID
            print >> f, "%6d" % (i + 1),

            # atom IDs
            print >> f, "%4d %4d" % (atomIndices[a1], atomIndices[a2]),

            # bond order; give it our best shot...
            amideA1 = a1 in amideCNs
            amideA2 = a2 in amideCNs
            if amideA1 and amideA2:
                print >> f, "am"
                continue
            if amideA1 or amideA2:
                if a1 in amideOs or a2 in amideOs:
                    print >> f, "2"
                else:
                    print >> f, "1"
                continue

            aromatic = False
            for ring in bond.minimumRings():
                if ring.aromatic():
                    aromatic = True
                    break
            if aromatic:
                print >> f, "ar"
                continue

            try:
                geom1 = typeInfo[a1.idatmType].geometry
            except KeyError:
                print >> f, "1"
                continue
            try:
                geom2 = typeInfo[a2.idatmType].geometry
            except KeyError:
                print >> f, "1"
                continue
            if geom1 not in [2, 3] or geom2 not in [2, 3]:
                print >> f, "1"
                continue
            # if either endpoint atom is in an aromatic ring and
            # the bond isn't, it's a single bond...
            for endp in [a1, a2]:
                aromatic = False
                for ring in endp.minimumRings():
                    if ring.aromatic():
                        aromatic = True
                        break
                if aromatic:
                    break
            else:
                # neither endpoint in aromatic ring
                print >> f, "2"
                continue
            print >> f, "1"

        if status:
            status("writing residues")
        # residue section header
        print >> f, "%s" % SUBSTR_HEADER

        for i, res in enumerate(RES_LIST):
            # residue id field
            print >> f, "%6d" % (i + 1),

            # residue name field
            if substructureNames:
                rname = substructureNames[res]
            elif resNum:
                rname = "%3s%-4d" % (res.type, res.id.position)
            else:
                rname = "%3s" % res.type
            print >> f, rname,

            # ID of the root atom of the residue
            from chimera.misc import principalAtom
            chainAtom = principalAtom(res)
            if chainAtom is None:
                if hasattr(res, 'atomsMap'):
                    chainAtom = res.atoms[0]
                else:
                    chainAtom = res.atoms.values()[0][0]
            print >> f, "%5d" % atomIndices[chainAtom],

            print >> f, "RESIDUE           4",

            # Sybyl seems to use chain 'A' when chain ID is blank,
            # so run with that
            chainID = res.id.chainId
            if len(chainID.strip()) != 1:
                chainID = 'A'
            print >> f, "%s     %3s" % (chainID, res.type),

            # number of out-of-substructure bonds
            crossResBonds = 0
            if hasattr(res, "atomsMap"):
                atoms = res.atoms
                for a in atoms:
                    for oa in a.bondsMap.keys():
                        if oa.residue != res:
                            crossResBonds += 1
            else:
                atoms = [a for aList in res.atoms.values() for a in aList]
                for a in atoms:
                    for oa in a.bonds.keys():
                        if oa.residue != res:
                            crossResBonds += 1
            print >> f, "%5d" % crossResBonds,
            # print "ROOT" if first or only residue of a chain
            if a.molecule.rootForAtom(a, True).atom.residue == res:
                print >> f, "ROOT"
            else:
                print >> f

        # write flexible ligand docking info
        if anchor:
            if status:
                status("writing anchor info")
            print >> f, "%s" % SET_HEADER
            atomIndices = {}
            for i, a in enumerate(ATOM_LIST):
                atomIndices[a] = i + 1
            bondIndices = {}
            for i, b in enumerate(BOND_LIST):
                bondIndices[b] = i + 1
            print >> f, "ANCHOR          STATIC     ATOMS    <user>   **** Anchor Atom Set"
            atoms = anchor.atoms()
            print >> f, len(atoms),
            for a in atoms:
                if a in atomIndices:
                    print >> f, atomIndices[a],
            print >> f

            print >> f, "RIGID           STATIC     BONDS    <user>   **** Rigid Bond Set"
            bonds = anchor.bonds()
            print >> f, len(bonds),
            for b in bonds:
                if b in bondIndices:
                    print >> f, bondIndices[b],
            print >> f

    f.close()