def __init__(self, parent): from Trajectory.prefs import prefs, INPUT_FILES, GROMOS_SCALING inputPrefs = prefs[INPUT_FILES].setdefault('Gromos', {}) self.options = [] for i in range(len(self.labels)): label = self.labels[i] self.options.append( InputFileOption(parent, i, label, inputPrefs.get(label, True), None, title="Choose %s File" % label, historyID="Gromos %s" % label)) self.scalingOption = FloatOption( parent, len(self.labels), "Angstrom conversion", prefs[GROMOS_SCALING], None, balloon="scale factor to convert trajectory\n" "coordinates to angstroms", width=4, sticky='w') parent.columnconfigure(1, weight=1)
def fillInUI(self, parent): Tkinter.Label(parent, text="Collect positions of selected" " atoms over trajectory", relief="ridge", bd=4).grid( row=0, column=0, columnspan=2, sticky="ew") startFrame = self.movie.startFrame endFrame = self.movie.endFrame from chimera.tkoptions import IntOption, BooleanOption, \ FloatOption, StringOption self.startFrame = IntOption(parent, 1, "Starting frame", startFrame, None, min=startFrame, max=endFrame, width=6) numFrames = endFrame - startFrame + 1 defStride = 1 + int(numFrames/300) self.stride = IntOption(parent, 2, "Step size", defStride, None, min=1, max=numFrames, width=3) self.endFrame = IntOption(parent, 3, "Ending frame", endFrame, None, min=startFrame, max=endFrame, width=6) self.doCutoff = BooleanOption(parent, 4, 'Limit data collection' ' to within cutoff distance of any "held steady" atoms', True, None) self.cutoff = FloatOption(parent, 5, "Cutoff distance", prefs[VOLUME_CUTOFF], None, width=4) self.resolution = FloatOption(parent, 6, "Volume grid spacing", prefs[VOLUME_RESOLUTION], None, min=0.0001, width=4) self.volumeName = StringOption(parent, 7, "Volume data name", self.movie.ensemble.name, None, width=20) self.byAtomType = BooleanOption(parent, 8, "Collect data" " separately for each atom type in selection", True, None, balloon="Create a volume data set for" " each type of atom type\n(sp2 oxygen, aromatic carbon," " etc.) in current selection")
def fillInUI(self, parent): from chimera.tkoptions import IntOption, BooleanOption, \ FloatOption Tkinter.Label(parent, text="Create RMSD map of trajectory " "against itself", relief="ridge", bd=4).grid(row=0, column=0, columnspan=2, sticky="ew") startFrame = self.movie.startFrame endFrame = self.movie.endFrame self.startFrame = IntOption(parent, 1, "Starting frame", startFrame, None, min=startFrame, max=endFrame, width=6) numFrames = endFrame - startFrame + 1 defStride = 1 + int(numFrames/300) self.stride = IntOption(parent, 2, "Step size", defStride, None, min=1, max=numFrames, width=3) self.endFrame = IntOption(parent, 3, "Ending frame", endFrame, None, min=startFrame, max=endFrame, width=6) self.minRmsd = FloatOption(parent, 4, "Lower RMSD threshold" " (white)", prefs[RMSD_MIN], None, width=6) self.maxRmsd = FloatOption(parent, 5, "Upper RMSD threshold" " (black)", prefs[RMSD_MAX], None, width=6) self.useSel = BooleanOption(parent, 6, "Restrict map to " "current selection, if any", True, None) self.ignoreBulk = BooleanOption(parent, 7, "Ignore solvent/" "ions", True, None) self.ignoreHyds = BooleanOption(parent, 8, "Ignore hydrogens", True, None) self.recolor = BooleanOption(parent, 9, "Auto-recolor for" " contrast", prefs[RMSD_AUTOCOLOR], None)
class SelectClusterMode(ModalDialog): buttons = ('Frames', 'Density') def __init__(self, movie): self.movie = movie self.volgridspacing = None ModalDialog.__init__(self) def fillInUI(self, parent): import Tkinter from chimera.tkoptions import IntOption, BooleanOption, FloatOption Tkinter.Label(parent, text="Please select visualization mode", relief="ridge", bd=4).grid(row=0, column=0, columnspan=2, sticky="ew") minspacing = 1 maxspacing = 15 defaultspacing=10 self.volgridspacing = FloatOption(parent, 1, "Volume grid Spacing", defaultspacing, None, min=minspacing, max=maxspacing, width=6) def Frames(self): volgridspacing = self.volgridspacing.get() ModalDialog.Cancel(self, value=(volgridspacing, "Frames")) def Density(self): volgridspacing = self.volgridspacing.get() ModalDialog.Cancel(self, value=(volgridspacing, "Density")) def destroy(self): self.movie = None ModelessDialog.destroy(self)
def fillInUI(self, parent): from chimera.tkoptions import FloatOption self.newMin = FloatOption(parent, 0, "New lower RMSD threshold (white)", prefs[RMSD_MIN], None) self.newMax = FloatOption(parent, 1, "New upper RMSD threshold (black)", prefs[RMSD_MAX], None)
def __init__(self, parent): from chimera.tkoptions import IntOption, FloatOption Tkinter.Frame.__init__(self, parent) self.nsteps = IntOption(self, 0, "Steps", 100, None) self.stepsize = FloatOption(self, 1, "Step size (A)", 0.02, None, min=0.0001, max=1.0) self.interval = IntOption(self, 2, "Update interval", 10, None) self.freeze = FreezeOption(self, 3, "Fixed atoms", base.FreezeNone, None)
def fillInUI(self, parent): import Tkinter from chimera.tkoptions import IntOption, BooleanOption, FloatOption Tkinter.Label(parent, text="Please select visualization mode", relief="ridge", bd=4).grid(row=0, column=0, columnspan=2, sticky="ew") minspacing = 1 maxspacing = 15 defaultspacing=10 self.volgridspacing = FloatOption(parent, 1, "Volume grid Spacing", defaultspacing, None, min=minspacing, max=maxspacing, width=6)
def fillInUI(self, parent): import Pmw, Tkinter row = 0 Tkinter.Label(parent, text="Create plane for selected atoms...").grid( row=row, columnspan=2) row += 1 from chimera.tkoptions import StringOption, BooleanOption self.nameOpt = StringOption(parent, row, "Plane name", "plane", None) row += 1 self.replaceExistingOpt = BooleanOption(parent, row, "Replace existing planes", False, None) row += 1 from chimera.tkoptions import ColorOption, FloatOption self.colorOpt = ColorOption(parent, row, "Color", None, None, balloon="Plane color. If No Color, then the plane" " will be colored to match the structure") row += 1 self.autoRadiusOpt = BooleanOption(parent, row, "Set disk size to enclose atom projections", True, self._radCB) row += 1 self.radRow = row self.radOffsetOpt = FloatOption(parent, row, "Extra radius" " (padding)", 0.0, None) self.radiusOpt = FloatOption(parent, row, "Fixed radius", 10.0, None) self.radiusOpt.forget() row += 1 self.thicknessOpt = FloatOption(parent, row, "Disk thickness", prefs[PLANE_THICKNESS], None)
class ParamGUI: labels = ["Topology", "Coordinates", "PROMD"] def __init__(self, parent): from Trajectory.prefs import prefs, INPUT_FILES, GROMOS_SCALING inputPrefs = prefs[INPUT_FILES].setdefault('Gromos', {}) self.options = [] for i in range(len(self.labels)): label = self.labels[i] self.options.append( InputFileOption(parent, i, label, inputPrefs.get(label, True), None, title="Choose %s File" % label, historyID="Gromos %s" % label)) self.scalingOption = FloatOption( parent, len(self.labels), "Angstrom conversion", prefs[GROMOS_SCALING], None, balloon="scale factor to convert trajectory\n" "coordinates to angstroms", width=4, sticky='w') parent.columnconfigure(1, weight=1) def loadEnsemble(self, startFrame, endFrame, callback): args = [] from Trajectory.prefs import prefs, INPUT_FILES, GROMOS_SCALING # need to change a _copy_ of the dictionary, otherwise # when we try to save the "original" dictionary will also # have our changes and no save will occur from copy import deepcopy inputPrefs = deepcopy(prefs[INPUT_FILES]) for i in range(len(self.labels)): path = self.options[i].get() label = self.labels[i] if not os.path.exists(path): raise ValueError, \ "%s file '%s' does not exist!" % ( label, path) inputPrefs['Gromos'][label] = path args.append(path) prefs[INPUT_FILES] = inputPrefs scale = self.scalingOption.get() prefs[GROMOS_SCALING] = scale args.append(scale) loadEnsemble(args, startFrame, endFrame, callback)
def __init__(self, parent): from Trajectory.prefs import prefs, INPUT_FILES, GROMOS_SCALING inputPrefs = prefs[INPUT_FILES].setdefault('Gromos', {}) self.options = [] for i in range(len(self.labels)): label = self.labels[i] self.options.append(InputFileOption(parent, i, label, inputPrefs.get(label, True), None, title="Choose %s File" % label, historyID="Gromos %s" % label)) self.scalingOption = FloatOption(parent, len(self.labels), "Angstrom conversion", prefs[GROMOS_SCALING], None, balloon="scale factor to convert trajectory\n" "coordinates to angstroms", width=4, sticky='w') parent.columnconfigure(1, weight=1)
class ParamGUI: labels = ["Topology", "Coordinates", "PROMD"] def __init__(self, parent): from Trajectory.prefs import prefs, INPUT_FILES, GROMOS_SCALING inputPrefs = prefs[INPUT_FILES].setdefault('Gromos', {}) self.options = [] for i in range(len(self.labels)): label = self.labels[i] self.options.append(InputFileOption(parent, i, label, inputPrefs.get(label, True), None, title="Choose %s File" % label, historyID="Gromos %s" % label)) self.scalingOption = FloatOption(parent, len(self.labels), "Angstrom conversion", prefs[GROMOS_SCALING], None, balloon="scale factor to convert trajectory\n" "coordinates to angstroms", width=4, sticky='w') parent.columnconfigure(1, weight=1) def loadEnsemble(self, startFrame, endFrame, callback): args = [] from Trajectory.prefs import prefs, INPUT_FILES, GROMOS_SCALING # need to change a _copy_ of the dictionary, otherwise # when we try to save the "original" dictionary will also # have our changes and no save will occur from copy import deepcopy inputPrefs = deepcopy(prefs[INPUT_FILES]) for i in range(len(self.labels)): path = self.options[i].get() label = self.labels[i] if not os.path.exists(path): raise ValueError, \ "%s file '%s' does not exist!" % ( label, path) inputPrefs['Gromos'][label] = path args.append(path) prefs[INPUT_FILES] = inputPrefs scale = self.scalingOption.get() prefs[GROMOS_SCALING] = scale args.append(scale) loadEnsemble(args, startFrame, endFrame, callback)
def fillInUI(self, parent): row = 0 parent.columnconfigure(0, weight=1) parent.rowconfigure(row, weight=1) self.chainList = MoleculeChainScrolledListBox(parent, selectioncommand=self._updateIterRef, listbox_selectmode='multiple') self.chainList.grid(row=row, column=0, sticky='nsew') row += 1 mols = {} for chain in self.chainList.get(): mol = chain.molecule if mol in mols: continue mols[mol] = chain self.chainList.setvalue(mols.values()) f = Tkinter.Frame(parent) f.grid(row=row, column=0, sticky='w') row += 1 self.distCutoff = FloatOption(f, 0, "Residue-residue distance cutoff (angstroms)", prefs[DIST_CUTOFF], None, balloon="""\ residues whose principal atoms are further apart than this distance will not be aligned in the generated sequence alignment""") self.distCutoff.min = 0.0 class MatchTypeOption(SymbolicEnumOption): values = ["any", "all"] labels = ["at least one other", "all others"] f = Tkinter.Frame(parent) f.grid(row=row, column=0, sticky='w') row += 1 self.matchType = MatchTypeOption(f, 0, "Residue aligned in column if within cutoff of", prefs[ANYALL], None, balloon="""\ whether a residue needs to match the distance cutoff to all other residues in its column, or just to one residue in the column""") class GapCharOption(SymbolicEnumOption): values = [".", "-", "~"] labels = [". (period)", "- (dash)", "~ (tilde)"] f = Tkinter.Frame(parent) f.grid(row=row, column=0, sticky='w') row += 1 self.gapChar = GapCharOption(f, 0, "Gap character", prefs[GAPCHAR], None, balloon="""\ character used to depict gaps in alignment""") self.circularVar = Tkinter.IntVar(parent) self.circularVar.set(prefs[CIRCULAR]) Tkinter.Checkbutton(parent, variable=self.circularVar, text= "Allow for circular permutation").grid(row=row, column=0, sticky='w') row += 1 self.iterateVar = Tkinter.IntVar(parent) self.iterateVar.set(prefs[ITERATE]) Tkinter.Checkbutton(parent, command=self._iterParamsDisplay, text="Iterate superposition/alignment...", variable=self.iterateVar).grid( row=row, column=0, columnspan=2, sticky='w') row += 1 self.iterParams = Pmw.Group(parent, hull_padx=2, tag_text="Iteration Parameters") self.iterParams.grid(row=row, column=0, columnspan=2) row += 1 inside = self.iterParams.interior() Tkinter.Label(inside, text="Iterate alignment:").grid( row=0, column=0, rowspan=2, sticky='e') self.iterConvergeVar = Tkinter.IntVar(parent) self.iterConvergeVar.set(prefs[ITER_CONVERGE]) f = Tkinter.Frame(inside) f.grid(row=0, column=1, sticky='w') Tkinter.Radiobutton(f, value=False, text="at most", variable=self.iterConvergeVar).grid(row=0, column=0) self.iterLimit = Pmw.EntryField(f, labelpos='e', label_text="times", validate={'min': 1, 'validator': 'numeric'}, value=str(prefs[ITER_AMOUNT]), entry_width=2, entry_justify="center") self.iterLimit.grid(row=0, column=1) Tkinter.Radiobutton(inside, text="until convergence", value=True, variable=self.iterConvergeVar).grid( row=1, column=1, sticky='w') inside.rowconfigure(2, minsize="0.1i") Tkinter.Label(inside, text="Superimpose full columns:" ).grid(row=3, rowspan=2, column=0, sticky='e') self.iterAllColsVar = Tkinter.IntVar(parent) self.iterAllColsVar.set(prefs[ITER_ALL_COLS]) Tkinter.Radiobutton(inside, text="across entire alignment", value=True, variable=self.iterAllColsVar).grid( row=3, column=1, sticky='w') f = Tkinter.Frame(inside) f.grid(row=4, column=1, sticky='w') Tkinter.Radiobutton(f, text="in stretches of at least", variable=self.iterAllColsVar, value=False).grid(row=0, column=0) self.stretchLen = Pmw.EntryField(f, labelpos='e', label_text="consecutive columns", validate={'min': 2, 'validator': 'numeric'}, value=str(prefs[ITER_CONSECUTIVE_COLS]), entry_width=1, entry_justify="center") self.stretchLen.grid(row=0, column=1) self.referenceMenu = Pmw.OptionMenu(inside, labelpos='w', items=Pmw.ScrolledListBox.get(self.chainList), label_text="Reference chain for matching:") self.referenceMenu.grid(row=5, column=0, columnspan=2) self._iterParamsDisplay() f = Tkinter.Frame(parent) f.grid(row=row, column=0, columnspan=2, sticky='ew') row += 1 from chimera import help b = Tkinter.Button(f, text="Save settings", pady=0, command=self._saveSettings) b.grid(row=0, column=0) help.register(b, balloon="Save current settings") b = Tkinter.Button(f, text="Reset to defaults", pady=0, command=self._restoreSettings) b.grid(row=0, column=1) help.register(b, balloon="Reset dialog to factory defaults") f.columnconfigure(0, weight=1) f.columnconfigure(1, weight=1)
class Match2Align(ModelessDialog): title = "Create Alignment from Superposition" oneshot = True help = "ContributedSoftware/matchalign/matchalign.html" def fillInUI(self, parent): row = 0 parent.columnconfigure(0, weight=1) parent.rowconfigure(row, weight=1) self.chainList = MoleculeChainScrolledListBox(parent, selectioncommand=self._updateIterRef, listbox_selectmode='multiple') self.chainList.grid(row=row, column=0, sticky='nsew') row += 1 mols = {} for chain in self.chainList.get(): mol = chain.molecule if mol in mols: continue mols[mol] = chain self.chainList.setvalue(mols.values()) f = Tkinter.Frame(parent) f.grid(row=row, column=0, sticky='w') row += 1 self.distCutoff = FloatOption(f, 0, "Residue-residue distance cutoff (angstroms)", prefs[DIST_CUTOFF], None, balloon="""\ residues whose principal atoms are further apart than this distance will not be aligned in the generated sequence alignment""") self.distCutoff.min = 0.0 class MatchTypeOption(SymbolicEnumOption): values = ["any", "all"] labels = ["at least one other", "all others"] f = Tkinter.Frame(parent) f.grid(row=row, column=0, sticky='w') row += 1 self.matchType = MatchTypeOption(f, 0, "Residue aligned in column if within cutoff of", prefs[ANYALL], None, balloon="""\ whether a residue needs to match the distance cutoff to all other residues in its column, or just to one residue in the column""") class GapCharOption(SymbolicEnumOption): values = [".", "-", "~"] labels = [". (period)", "- (dash)", "~ (tilde)"] f = Tkinter.Frame(parent) f.grid(row=row, column=0, sticky='w') row += 1 self.gapChar = GapCharOption(f, 0, "Gap character", prefs[GAPCHAR], None, balloon="""\ character used to depict gaps in alignment""") self.circularVar = Tkinter.IntVar(parent) self.circularVar.set(prefs[CIRCULAR]) Tkinter.Checkbutton(parent, variable=self.circularVar, text= "Allow for circular permutation").grid(row=row, column=0, sticky='w') row += 1 self.iterateVar = Tkinter.IntVar(parent) self.iterateVar.set(prefs[ITERATE]) Tkinter.Checkbutton(parent, command=self._iterParamsDisplay, text="Iterate superposition/alignment...", variable=self.iterateVar).grid( row=row, column=0, columnspan=2, sticky='w') row += 1 self.iterParams = Pmw.Group(parent, hull_padx=2, tag_text="Iteration Parameters") self.iterParams.grid(row=row, column=0, columnspan=2) row += 1 inside = self.iterParams.interior() Tkinter.Label(inside, text="Iterate alignment:").grid( row=0, column=0, rowspan=2, sticky='e') self.iterConvergeVar = Tkinter.IntVar(parent) self.iterConvergeVar.set(prefs[ITER_CONVERGE]) f = Tkinter.Frame(inside) f.grid(row=0, column=1, sticky='w') Tkinter.Radiobutton(f, value=False, text="at most", variable=self.iterConvergeVar).grid(row=0, column=0) self.iterLimit = Pmw.EntryField(f, labelpos='e', label_text="times", validate={'min': 1, 'validator': 'numeric'}, value=str(prefs[ITER_AMOUNT]), entry_width=2, entry_justify="center") self.iterLimit.grid(row=0, column=1) Tkinter.Radiobutton(inside, text="until convergence", value=True, variable=self.iterConvergeVar).grid( row=1, column=1, sticky='w') inside.rowconfigure(2, minsize="0.1i") Tkinter.Label(inside, text="Superimpose full columns:" ).grid(row=3, rowspan=2, column=0, sticky='e') self.iterAllColsVar = Tkinter.IntVar(parent) self.iterAllColsVar.set(prefs[ITER_ALL_COLS]) Tkinter.Radiobutton(inside, text="across entire alignment", value=True, variable=self.iterAllColsVar).grid( row=3, column=1, sticky='w') f = Tkinter.Frame(inside) f.grid(row=4, column=1, sticky='w') Tkinter.Radiobutton(f, text="in stretches of at least", variable=self.iterAllColsVar, value=False).grid(row=0, column=0) self.stretchLen = Pmw.EntryField(f, labelpos='e', label_text="consecutive columns", validate={'min': 2, 'validator': 'numeric'}, value=str(prefs[ITER_CONSECUTIVE_COLS]), entry_width=1, entry_justify="center") self.stretchLen.grid(row=0, column=1) self.referenceMenu = Pmw.OptionMenu(inside, labelpos='w', items=Pmw.ScrolledListBox.get(self.chainList), label_text="Reference chain for matching:") self.referenceMenu.grid(row=5, column=0, columnspan=2) self._iterParamsDisplay() f = Tkinter.Frame(parent) f.grid(row=row, column=0, columnspan=2, sticky='ew') row += 1 from chimera import help b = Tkinter.Button(f, text="Save settings", pady=0, command=self._saveSettings) b.grid(row=0, column=0) help.register(b, balloon="Save current settings") b = Tkinter.Button(f, text="Reset to defaults", pady=0, command=self._restoreSettings) b.grid(row=0, column=1) help.register(b, balloon="Reset dialog to factory defaults") f.columnconfigure(0, weight=1) f.columnconfigure(1, weight=1) def Apply(self): chains = self.chainList.getvalue() if len(chains) < 2: replyobj.error("Must choose at least two chains\n") self.enter() return mols = {} for chain in chains: if chain.molecule in mols: replyobj.error( "Please choose only one chain per model\n") self.enter() return mols[chain.molecule] = 1 cutoff = float(self.distCutoff.get()) matchType = self.matchType.get() gapChar = self.gapChar.get() circular = self.circularVar.get() from align import match2align from Midas import match, rmsd seqs = match2align(chains, cutoff, matchType, gapChar, circular) cols = alignedCols(seqs) replyobj.info("%d fully populated columns\n" % (len(cols))) if self.iterateVar.get(): best = None iteration = 1 refChain = self.chainList.itemMap[ self.referenceMenu.getvalue()] if self.iterConvergeVar.get(): iterLimit = None else: self.iterLimit.invoke() iterLimit = int(self.iterLimit.getvalue()) if self.iterAllColsVar.get(): stretchLen = 1 else: self.stretchLen.invoke() stretchLen = int(self.stretchLen.getvalue()) while True: refSeq = [s for s in seqs if s.molecule == refChain.molecule][0] # cull columns based on stretch len criteria stretch = [] culled = [] for col in cols: if not stretch or stretch[-1]+1 == col: stretch.append(col) continue if len(stretch) >= stretchLen: culled.extend(stretch) stretch = [col] if len(stretch) >= stretchLen: culled.extend(stretch) if stretchLen > 1: replyobj.info("%d fully populated" " columns in at least %d" " column stretches\n" % ( len(culled), stretchLen)) if not culled: break # match refAtoms = columnAtoms(refSeq, culled) for seq in seqs: if seq.molecule == refSeq.molecule: continue seqAtoms = columnAtoms(seq, culled) replyobj.info("Matching %s onto %s\n" % (seq.name, refSeq.name)) match(seqAtoms, refAtoms) seqs = match2align(chains, cutoff, matchType, gapChar, circular, statusPrefix= "Iteration %d: " % iteration) cols = alignedCols(seqs) replyobj.info("Iteration %d: %d fully populated" " columns\n" % (iteration, len(cols))) if best == None or len(cols) > len(best): best = cols else: break if iterLimit and iteration >= iterLimit: break iteration += 1 if len(seqs) == 2: mav = showAlignment(seqs, "Match of %s and %s" % (seqs[0].name, seqs[1].name)) else: mav = showAlignment(seqs, "Match -> Align (%d models)" % len(seqs)) from MultAlignViewer.MAViewer import MATCHED_REGION_INFO name, fill, outline = MATCHED_REGION_INFO mav.newRegion(name="Fully populated columns", columns=cols, fill=fill, outline=outline) if cols: # show pairwise RMSD matrix in fully populated columns matchAtoms = {} for seq in seqs: matchAtoms[seq] = columnAtoms(seq, cols) replyobj.info("\nEvaluating superpositions across all %d fully" " populated columns in the final alignment:\n" % len(cols)) dsqSum = 0 for i, s1 in enumerate(seqs): for s2 in seqs[i+1:]: v = rmsd(matchAtoms[s1], matchAtoms[s2], log=False) dsqSum += v * v replyobj.info("RMSD of %s with %s: %.3f\n" % (s1.name, s2.name, v)) from math import sqrt replyobj.info("Overall RMSD: %.3f\n\n" % sqrt(2 * dsqSum / (len(seqs) * (len(seqs)-1)))) mav.status("RMSDs reported in Reply Log", color="purple") replyobj.status("RMSDs reported in Reply Log", color="purple") else: mav.status("No fully populated columns in alignment", color="blue") def _iterParamsDisplay(self): if self.iterateVar.get(): self.iterParams.grid() else: self.iterParams.grid_remove() def _restoreSettings(self): from prefs import defaults self.distCutoff.set(defaults[DIST_CUTOFF]) self.matchType.set(defaults[ANYALL]) self.gapChar.set(defaults[GAPCHAR]) self.circularVar.set(defaults[CIRCULAR]) self.iterateVar.set(defaults[ITERATE]) self._iterParamsDisplay() self.iterConvergeVar.set(defaults[ITER_CONVERGE]) self.iterLimit.setvalue(str(defaults[ITER_AMOUNT])) self.iterAllColsVar.set(defaults[ITER_ALL_COLS]) self.stretchLen.setvalue(str(defaults[ITER_CONSECUTIVE_COLS])) def _saveSettings(self): prefs[DIST_CUTOFF] = float(self.distCutoff.get()) prefs[ANYALL] = self.matchType.get() prefs[GAPCHAR] = self.gapChar.get() prefs[CIRCULAR] = self.circularVar.get() prefs[ITERATE] = self.iterateVar.get() prefs[ITER_CONVERGE] = self.iterConvergeVar.get() self.iterLimit.invoke() prefs[ITER_AMOUNT] = int(self.iterLimit.getvalue()) prefs[ITER_ALL_COLS] = self.iterAllColsVar.get() self.stretchLen.invoke() prefs[ITER_CONSECUTIVE_COLS] = int(self.stretchLen.getvalue()) def _updateIterRef(self, *args): self.referenceMenu.setitems([self.chainList.valueMap[chain] for chain in self.chainList.getvalue()])
def fillInUI(self, parent): Tkinter.Label(parent, text="Collect positions of selected" " atoms over trajectory", relief="ridge", bd=4).grid(row=0, column=0, columnspan=2, sticky="ew") startFrame = self.movie.startFrame endFrame = self.movie.endFrame from chimera.tkoptions import IntOption, BooleanOption, \ FloatOption, StringOption self.startFrame = IntOption(parent, 1, "Starting frame", startFrame, None, min=startFrame, max=endFrame, width=6) numFrames = endFrame - startFrame + 1 defStride = 1 + int(numFrames / 300) self.stride = IntOption(parent, 2, "Step size", defStride, None, min=1, max=numFrames, width=3) self.endFrame = IntOption(parent, 3, "Ending frame", endFrame, None, min=startFrame, max=endFrame, width=6) self.doCutoff = BooleanOption( parent, 4, 'Limit data collection' ' to within cutoff distance of any "held steady" atoms', True, None) self.cutoff = FloatOption(parent, 5, "Cutoff distance", prefs[VOLUME_CUTOFF], None, width=4) self.resolution = FloatOption(parent, 6, "Volume grid spacing", prefs[VOLUME_RESOLUTION], None, min=0.0001, width=4) self.volumeName = StringOption(parent, 7, "Volume data name", self.movie.ensemble.name, None, width=20) self.byAtomType = BooleanOption( parent, 8, "Collect data" " separately for each atom type in selection", True, None, balloon="Create a volume data set for" " each type of atom type\n(sp2 oxygen, aromatic carbon," " etc.) in current selection")
class CreatePlaneDialog(ModelessDialog): title = "Define Plane" help = "ContributedSoftware/structuremeas/structuremeas.html#define-plane" provideStatus = True statusPosition = "above" def fillInUI(self, parent): import Pmw, Tkinter row = 0 Tkinter.Label(parent, text="Create plane for selected atoms...").grid( row=row, columnspan=2) row += 1 from chimera.tkoptions import StringOption, BooleanOption self.nameOpt = StringOption(parent, row, "Plane name", "plane", None) row += 1 self.replaceExistingOpt = BooleanOption(parent, row, "Replace existing planes", False, None) row += 1 from chimera.tkoptions import ColorOption, FloatOption self.colorOpt = ColorOption(parent, row, "Color", None, None, balloon="Plane color. If No Color, then the plane" " will be colored to match the structure") row += 1 self.autoRadiusOpt = BooleanOption(parent, row, "Set disk size to enclose atom projections", True, self._radCB) row += 1 self.radRow = row self.radOffsetOpt = FloatOption(parent, row, "Extra radius" " (padding)", 0.0, None) self.radiusOpt = FloatOption(parent, row, "Fixed radius", 10.0, None) self.radiusOpt.forget() row += 1 self.thicknessOpt = FloatOption(parent, row, "Disk thickness", prefs[PLANE_THICKNESS], None) def Apply(self): from chimera import UserError if self.replaceExistingOpt.get(): planeManager.removePlanes(planeManager.planes) kw = { 'color': self.colorOpt.get(), 'thickness': self.thicknessOpt.get() } prefs[PLANE_THICKNESS] = kw['thickness'] if self.autoRadiusOpt.get(): kw['radiusOffset'] = self.radOffsetOpt.get() else: kw['radius'] = self.radiusOpt.get() replyobj.info("Creating plane\n") selAtoms = selection.currentAtoms() if len(selAtoms) < 3: self.enter() raise UserError("Need to select at least three" " atoms to define a plane") planeManager.createPlane(self.nameOpt.get().strip(), selAtoms, **kw) def _radCB(self, opt): if opt.get(): self.radiusOpt.forget() self.radOffsetOpt.manage() else: self.radOffsetOpt.forget() self.radiusOpt.manage()
class RmsdStarter(ModelessDialog): title = "Get RMSD Map Parameters" help = "ContributedSoftware/movie/movie.html#rmsd" def __init__(self, movie): self.movie = movie movie.subdialogs.append(self) ModelessDialog.__init__(self) def fillInUI(self, parent): from chimera.tkoptions import IntOption, BooleanOption, \ FloatOption Tkinter.Label(parent, text="Create RMSD map of trajectory " "against itself", relief="ridge", bd=4).grid(row=0, column=0, columnspan=2, sticky="ew") startFrame = self.movie.startFrame endFrame = self.movie.endFrame self.startFrame = IntOption(parent, 1, "Starting frame", startFrame, None, min=startFrame, max=endFrame, width=6) numFrames = endFrame - startFrame + 1 defStride = 1 + int(numFrames / 300) self.stride = IntOption(parent, 2, "Step size", defStride, None, min=1, max=numFrames, width=3) self.endFrame = IntOption(parent, 3, "Ending frame", endFrame, None, min=startFrame, max=endFrame, width=6) self.minRmsd = FloatOption(parent, 4, "Lower RMSD threshold" " (white)", prefs[RMSD_MIN], None, width=6) self.maxRmsd = FloatOption(parent, 5, "Upper RMSD threshold" " (black)", prefs[RMSD_MAX], None, width=6) self.useSel = BooleanOption( parent, 6, "Restrict map to " "current selection, if any", True, None) self.ignoreBulk = BooleanOption(parent, 7, "Ignore solvent/" "ions", True, None) self.ignoreHyds = BooleanOption(parent, 8, "Ignore hydrogens", True, None) self.recolor = BooleanOption(parent, 9, "Auto-recolor for" " contrast", prefs[RMSD_AUTOCOLOR], None) def Apply(self): startFrame = self.startFrame.get() stride = self.stride.get() if (len(self.movie.ensemble) - (startFrame - 1)) / stride > 1000: dlg = AskYesNoDialog("RMSD map will be %d pixels wide" " and tall. Okay?") if dlg.run(self.uiMaster()) == "no": self.enter() return endFrame = self.endFrame.get() if endFrame <= startFrame: self.enter() raise UserError("Start frame must be less" " than end frame") if startFrame < self.movie.startFrame \ or endFrame > self.movie.endFrame: self.enter() raise UserError("Start or end frame outside" " of trajectory") prefs[RMSD_MIN] = self.minRmsd.get() prefs[RMSD_MAX] = self.maxRmsd.get() prefs[RMSD_AUTOCOLOR] = self.recolor.get() RmsdMapDialog(self.movie, startFrame, self.stride.get(), endFrame, self.useSel.get(), prefs[RMSD_MIN], prefs[RMSD_MAX], self.ignoreBulk.get(), self.ignoreHyds.get(), prefs[RMSD_AUTOCOLOR])
class VolumeDialog(ModelessDialog): title = "Calculate Atomic Occupancy" help = "ContributedSoftware/movie/movie.html#occupancy" provideStatus = True statusPosition = "left" buttons = ('OK', 'Close') default= 'OK' def __init__(self, movie): self.movie = movie movie.subdialogs.append(self) ModelessDialog.__init__(self) def map(self, e=None): if not self.movie.holdingSteady: self.status("No atoms being held steady -- see Help", color="red") def fillInUI(self, parent): Tkinter.Label(parent, text="Collect positions of selected" " atoms over trajectory", relief="ridge", bd=4).grid( row=0, column=0, columnspan=2, sticky="ew") startFrame = self.movie.startFrame endFrame = self.movie.endFrame from chimera.tkoptions import IntOption, BooleanOption, \ FloatOption, StringOption self.startFrame = IntOption(parent, 1, "Starting frame", startFrame, None, min=startFrame, max=endFrame, width=6) numFrames = endFrame - startFrame + 1 defStride = 1 + int(numFrames/300) self.stride = IntOption(parent, 2, "Step size", defStride, None, min=1, max=numFrames, width=3) self.endFrame = IntOption(parent, 3, "Ending frame", endFrame, None, min=startFrame, max=endFrame, width=6) self.doCutoff = BooleanOption(parent, 4, 'Limit data collection' ' to within cutoff distance of any "held steady" atoms', True, None) self.cutoff = FloatOption(parent, 5, "Cutoff distance", prefs[VOLUME_CUTOFF], None, width=4) self.resolution = FloatOption(parent, 6, "Volume grid spacing", prefs[VOLUME_RESOLUTION], None, min=0.0001, width=4) self.volumeName = StringOption(parent, 7, "Volume data name", self.movie.ensemble.name, None, width=20) self.byAtomType = BooleanOption(parent, 8, "Collect data" " separately for each atom type in selection", True, None, balloon="Create a volume data set for" " each type of atom type\n(sp2 oxygen, aromatic carbon," " etc.) in current selection") def Apply(self): from chimera import UserError atoms = chimera.selection.currentAtoms() if not atoms: self.enter() raise UserError("No atoms selected") startFrame = self.startFrame.get() endFrame = self.endFrame.get() if endFrame <= startFrame: self.enter() raise UserError("Start frame must be less" " than end frame") if startFrame < self.movie.startFrame \ or endFrame > self.movie.endFrame: self.enter() raise UserError("Start or end frame outside" " of trajectory") if self.doCutoff.get(): bound = prefs[VOLUME_CUTOFF] = self.cutoff.get() else: bound = None prefs[VOLUME_RESOLUTION] = self.resolution.get() step = self.stride.get() spacing = self.resolution.get() name = self.volumeName.get() atomTypes = {} if self.byAtomType.get(): for a in atoms: atomTypes.setdefault(a.idatmType, []).append(a) if len(atomTypes) > 1: for atomType, atAtoms in atomTypes.items(): self.movie.computeVolume(atAtoms, startFrame=startFrame, endFrame=endFrame, step=step, bound=bound, spacing=spacing, volumeName=name+" ["+atomType+"]") else: self.movie.computeVolume(atoms, startFrame=startFrame, endFrame=endFrame, step=step, bound=bound, spacing=spacing, volumeName=name)
class Interface(ModelessDialog): title = 'Nucleotides' help = "ContributedSoftware/nucleotides/nucleotides.html" buttons = ("NDB Colors",) + ModelessDialog.buttons provideStatus = True def __init__(self, *args, **kw): self.currentStyle = self.saveui_defaultItem() ModelessDialog.__init__(self, *args, **kw) self.__firstcanvas = True def fillInUI(self, parent): parent.columnconfigure(0, pad=2) parent.columnconfigure(1, pad=2) import itertools row = itertools.count() self.showBackbone = BackboneOption(parent, row.next(), 'Show backbone as', 'ribbon', None) self.showSide = SideOption(parent, row.next(), 'Show side (sugar/base) as', 'fill/slab', self._showSideCB) self.showOrientation = BooleanOption(parent, row.next(), 'Show base orientation', default.ORIENT, None) import Tix self.nb = Tix.NoteBook(parent) self.nb.grid(row=row.next(), column=0, columnspan=2, sticky=Tk.EW, padx=2) # ladder page self.nb.add("ladder", label="Ladder Options") f = self.nb.page("ladder") if Tk.TkVersion >= 8.5: parent.tk.call('grid', 'anchor', f._w, Tk.N) prow = itertools.count() self.skipNonBase = BooleanOption(f, prow.next(), 'Ignore non-base H-bonds', default.IGNORE, None) self.showStubs = BooleanOption(f, prow.next(), 'Show stubs', default.STUBS, None) self.rungRadius = FloatOption(f, prow.next(), 'Rung radius', default.RADIUS, None) self.rungRadius.min = 0.0 self.useExisting = BooleanOption(f, prow.next(), 'Using existing H-bonds', default.USE_EXISTING, self._useExistingCB) from FindHBond.gui import RelaxParams self.relaxParams = RelaxParams(f, None, colorOptions=False) #self.relaxParams.relaxConstraints = False self.relaxParams.grid(row=prow.next(), columnspan=2, sticky='nsew', padx=2) # slab page self.nb.add("slab", label="Slab Options") f = self.nb.page("slab") if Tk.TkVersion >= 8.5: parent.tk.call('grid', 'anchor', f._w, Tk.N) prow = itertools.count() self.thickness = FloatOption(f, prow.next(), 'Thickness', default.THICKNESS, None) self.thickness.min = 0.01 self.shape = ShapeOption(f, prow.next(), 'Slab object', default.SHAPE, None) self.hideBases = BooleanOption(f, prow.next(), 'Hide base atoms', default.HIDE, None) self.showGlycosidic = BooleanOption(f, prow.next(), 'Separate glycosidic bond', default.GLYCOSIDIC, None) self.nb.add("style", label="Slab Style", raisecmd=self.map) # style page f = self.nb.page("style") if Tk.TkVersion >= 8.5: f.tk.call('grid', 'anchor', f._w, Tk.N) info = NA.findStyle(self.currentStyle) from chimera.preferences import saveui f2 = Tk.Frame(f) self.saveui = saveui.SaveUI(f2, self) f2.grid(row=prow.next(), column=0, columnspan=2, sticky=Tk.EW, padx=2, pady=2) self.anchor = AnchorOption(f, prow.next(), 'Anchor', info[NA.ANCHOR], self._drawStyle) f2 = Pmw.Group(f, tag_text=NA.PURINE.title()) f2.grid(row=prow.next(), column=0, columnspan=2, sticky=Tk.EW, padx=2) f2 = f2.interior() f2.columnconfigure(0, weight=1, pad=2, uniform='a') f2.columnconfigure(1, weight=1, uniform='a') f2.columnconfigure(2, weight=1) self.purine_canvas = Tk.Canvas(f2, width=1, height=1) #, #borderwidth=2, relief=Tk.RIDGE) r = prow.next() self.purine_canvas.grid(row=r, column=0, rowspan=3, sticky=Tk.NSEW, padx=2, pady=2) corners = info[NA.PURINE] self.puLL = Float2Option(f2, prow.next(), 'Lower left', corners[0], self._drawStyle, startCol=1) self.puUR = Float2Option(f2, prow.next(), 'Upper right', corners[1], self._drawStyle, startCol=1) f3 = Pmw.Group(f, tag_text="%s, %s" % (NA.PYRIMIDINE.title(), NA.PSEUDO_PYRIMIDINE.title())) r = prow.next() f3.grid(row=r, column=0, columnspan=2, sticky=Tk.EW, padx=2) f3 = f3.interior() f3.columnconfigure(0, weight=1, pad=2, uniform='a') f3.columnconfigure(1, weight=1, uniform='a') f3.columnconfigure(2, weight=1) self.pyrimidine_canvas = Tk.Canvas(f3, width=1, height=1) #, #borderwidth=2, relief=Tk.RIDGE) r = prow.next() self.pyrimidine_canvas.grid(row=r, column=0, rowspan=3, sticky=Tk.NSEW, padx=2, pady=2) corners = info[NA.PYRIMIDINE] self.pyLL = Float2Option(f3, prow.next(), 'Lower left', corners[0], self._drawStyle, startCol=1) self.pyUR = Float2Option(f3, prow.next(), 'Upper right', corners[1], self._drawStyle, startCol=1) self.restrict = Tk.IntVar(parent) self.restrict.set(1) cb = Tk.Checkbutton(parent, variable=self.restrict, text="Restrict OK/Apply to current selection, if any") cb.grid(row=row.next(), columnspan=2) parent.pack(ipady=2) self._showSideCB() chimera.triggers.addHandler(NA.TRIGGER_SLAB_STYLES, self._updateStyles, None) def map(self, event=None): # need to update_idletasks so canvases in grid will have a size page = self.nb.raised() if page == 'style': if self.__firstcanvas: self.uiMaster().update_idletasks() self._drawStyle() self.__firstcanvas = False def _updateStyles(self, trigger, closure, arg): # pick up programmic changes in list of slab styles self.saveui.updateComboList() def saveui_label(self): return "Slab Style" def saveui_presetItems(self): return NA.SystemStyles.keys() def saveui_userItems(self): return NA.userStyles.keys() def saveui_defaultItem(self): return 'long' def saveui_select(self, name): self.currentStyle = name self._setSlabStyle(name) def saveui_save(self, name): info = self._getInfo() NA.addStyle(name, info) self.status("Slab style \"%s\" saved" % name) return True # successful def saveui_delete(self, name): NA.removeStyle(name) self.status("Slab style \"%s\" deleted" % name) return True # successful def _showSideCB(self, *args): side = self.showSide.get() hasSlab = 'slab' in side if side.startswith('fill') or hasSlab: self.showOrientation.enable() else: self.showOrientation.disable() if hasSlab: self.nb.raise_page('slab') elif side == 'ladder': self.nb.raise_page('ladder') if side == 'tube/slab': # tube connects to C1' if no slab # if slab, it goes to the middle of slab self.showGlycosidic.enable() return self.showGlycosidic.disable() def _useExistingCB(self, *args): useExisting = self.useExisting.get() if useExisting: self.relaxParams.disable() else: self.relaxParams.enable() def Apply(self): from chimera import selection if not self.restrict.get() or selection.currentEmpty(): molecules = chimera.openModels.list( modelTypes=[chimera.Molecule]) residues = [] for mol in molecules: residues.extend(mol.residues) else: residues = selection.currentResidues() molecules = tuple(set(r.molecule for r in residues)) residues = [r for r in residues if r.ribbonResidueClass.isNucleic()] backbone = self.showBackbone.get() display = backbone != 'atoms & bonds' for r in residues: r.ribbonDisplay = display side = self.showSide.get() if side == 'ladder': distSlop = 0.0 angleSlop = 0.0 relax = self.relaxParams.relaxConstraints if relax: distSlop = self.relaxParams.relaxDist angleSlop = self.relaxParams.relaxAngle NA.set_ladder(molecules, residues, rungRadius=self.rungRadius.get(), showStubs=self.showStubs.get(), skipNonBaseHBonds=self.skipNonBase.get(), useExisting=self.useExisting.get(), distSlop=distSlop, angleSlop=angleSlop) return if side.endswith('slab'): if self.currentStyle is None: info = self._getInfo() NA.addStyle(None, info) showGly = self.anchor.get() != NA.SUGAR if showGly and side.startswith('tube'): showGly = self.showGlycosidic.get() NA.set_slab(side, molecules, residues, style=self.currentStyle, thickness=self.thickness.get(), orient=self.showOrientation.get(), shape=self.shape.get(), showGly=showGly, hide=self.hideBases.get()) if side.startswith('fill'): for r in residues: r.fillDisplay = True else: for r in residues: r.fillDisplay = False if side.endswith('fill'): if self.showOrientation.get(): NA.set_orient(molecules, residues) else: NA.set_normal(molecules, residues) elif side.startswith('atoms'): NA.set_normal(molecules, residues) return def _showBase(self, type, info, canvas): # assume height is greater than width # keep in mind, canvases are "left-handed", so y is inverted # get unique bases of given type unique_bases = {} for b in NA.standard_bases.values(): if b['type'] == type: unique_bases[id(b)] = b # compute drawing parameters win_width = canvas.winfo_width() if win_width == 1: # no size assigned yet return win_height = canvas.winfo_height() # TODO: figure out how much room we really need for text if win_width < win_height: win_scale = .8 * win_width else: win_scale = .8 * win_height x_offset = .1 * win_width + 2 # 2==borderwidth if type == NA.PURINE: min = NA.purine_min max = NA.purine_max other = NA.pyrimidine_max[0] - NA.pyrimidine_min[0] elif type == NA.PYRIMIDINE: min = NA.pyrimidine_min max = NA.pyrimidine_max other = NA.purine_max[0] - NA.purine_min[0] width = max[0] - min[0] if other > width: width = other scale = win_scale / width # center vertically height = (max[1] - min[1]) * scale win_height -= (win_height - height) / 2 # clear canvas canvas.addtag_all('all') canvas.delete('all') def cvt_coords(c): for i in range(0, len(c), 2): c[i] = (c[i] - min[0]) * scale + x_offset c[i + 1] = win_height \ - (c[i + 1] - min[1]) * scale def draw_line(b, names): coords = [] for n in names: c = b[n] coords += [c[0], c[1]] if len(names) > 2: # close line coords += coords[0:2] cvt_coords(coords) kw = {'width':2} canvas.create_line(*coords, **kw) c1p_coords = None for b in unique_bases.values(): rn = b['ring atom names'] draw_line(b, rn) for o in b['other bonds']: draw_line(b, o) if c1p_coords is None: c1p_coords = list(b["C1'"][0:2]) else: coords = b["C1'"][0:2] if coords[0] < c1p_coords[0]: c1p_coords[0] = coords[0] if coords[1] > c1p_coords[1]: c1p_coords[1] = coords[1] corners = info[type] anchor = NA.anchor(info[NA.ANCHOR], type) offset = b[anchor] coords = [ offset[0] + corners[0][0], offset[1] + corners[0][1], offset[0] + corners[1][0], offset[1] + corners[1][1] ] cvt_coords(coords) kw = {'fill':'gray25', 'stipple':'gray25'} canvas.create_rectangle(*coords, **kw) coords = [min[0], max[1]] cvt_coords(c1p_coords) kw = {'text':" C1'", 'anchor':'s'} canvas.create_text(*c1p_coords, **kw) def _getInfo(self): info = { NA.ANCHOR: self.anchor.get(), NA.PURINE: (self.puLL.get(), self.puUR.get()), NA.PYRIMIDINE: (self.pyLL.get(), self.pyUR.get()), NA.PSEUDO_PYRIMIDINE: (self.pyLL.get(), self.pyUR.get()) } return info def _drawStyle(self, *args): if args: self.saveui.setItemChanged(True) self.currentStyle = None # fill in parameters info = self._getInfo() # show bases self._showBase(NA.PURINE, info, self.purine_canvas) self._showBase(NA.PYRIMIDINE, info, self.pyrimidine_canvas) def _setSlabStyle(self, name): # make options reflect current style info = NA.findStyle(name) if not info: return self.currentStyle = name self.anchor.set(info[NA.ANCHOR]) corners = info[NA.PURINE] self.puLL.set(corners[0]) self.puUR.set(corners[1]) corners = info[NA.PYRIMIDINE] self.pyLL.set(corners[0]) self.pyUR.set(corners[1]) self._drawStyle() def NDBColors(self): from chimera import selection if selection.currentEmpty(): import Midas residues = Midas._selectedResidues('#') else: residues = selection.currentResidues() NA.NDBColors(residues)
class ImageSaveDialog(ModelessDialog): name = "Save Image" buttons = ['Tips', 'Save As', Cancel] default = 'Save As' help = 'UsersGuide/print.html' provideStatus = True def fillInUI(self, master): self._ModelTrigger = None #self._SetupTrigger = None self._SizeTrigger = None self.raytrace = None # Image Size imageSetup = Tix.LabelFrame(master, label="Image Size") imageSetup.pack(fill=Tk.X, ipadx=2, ipady=2) subframe = imageSetup.frame #subframe = Tk.Frame(imageSetup.frame) #subframe.pack(fill=Tk.BOTH, expand=1) # add in conversion factor for pixels and graphics screen from chimera import tkgui win = tkgui.app.graphics res = tkgui.getScreenMMWidth() / win.winfo_screenwidth() convert['pixels'] = mm2pt(res) self.matchAspect = Tk.BooleanVar(master) self.matchAspect.set(1) self.usePrint = Tk.BooleanVar(master) self.usePrint.set(preferences.get(IMAGE_SETUP, USE_PRINT_UNITS)) import itertools row = itertools.count() self.showUsePrint = Tk.Checkbutton(subframe, indicatoron=1, variable=self.usePrint, highlightthickness=0, text=USE_PRINT_UNITS, command=self._updateUsePrint) self.showUsePrint.grid(columnspan=2, row=row.next(), sticky=Tk.W) w, h = chimera.viewer.windowSize self.units = ImageUnitsOption(subframe, row.next(), UNITS, 'pixels', self.updateImageUnits) self.iWidth = FloatOption(subframe, row.next(), 'Image width', w, self.updateImageWidth, min=1e-10) self.iHeight = FloatOption(subframe, row.next(), 'Image height', h, self.updateImageHeight, min=1e-10) matchAspect = Tk.Checkbutton(subframe, indicatoron=1, variable=self.matchAspect, highlightthickness=0, text="Maintain current aspect ratio", command=self.updateMatchAspect) matchAspect.grid(columnspan=2, row=row.next(), sticky=Tk.W) self.grow = Tk.Button(imageSetup.frame, text="Grow to Fit", command=self.Resize, state=Tk.DISABLED) fitrow = row.next() self.grow.grid(row=fitrow, column=0, padx=2, pady=2, sticky=Tk.NSEW) self.shrink = Tk.Button(imageSetup.frame, text="Shrink to Fit", command=lambda f=self.Resize: f(False), state=Tk.DISABLED) self.shrink.grid(row=fitrow, column=1, padx=2, pady=2, sticky=Tk.NSEW) #fetch = Tk.Button(imageSetup.frame, text="Get Pixels", # command=self.fetchWindowSize) #fetch.grid(row=row.next(), column=0, padx=2, pady=2, sticky=Tk.NSEW) #calc = Tk.Button(imageSetup.frame, text="Image Setup", # command=self.showImageSetupDialog) #calc.grid(row=row.next(), column=1, padx=2, pady=2, sticky=Tk.NSEW) self.printRes = FloatOption(subframe, row.next(), DPI, preferences.get(IMAGE_SETUP, DPI), self._updatePrint, min=1) # Image Information info = Tix.LabelFrame(master, label="Image Information") info.pack(fill=Tk.X) d = Tk.Label(info.frame, text="Description:") d.grid(columnspan=2, row=0, column=0, sticky=Tk.W, padx=2, pady=1) self.description = Tk.Entry(info.frame) info.frame.grid_columnconfigure(0, weight=1) info.frame.grid_columnconfigure(1, weight=1) self.description.grid(columnspan=2, row=1, column=0, sticky=Tk.EW, padx=2, pady=2) imageCredits = Tk.Button(info.frame, text="Image Credits", command=self.showImageCreditsDialog) imageCredits.grid(row=2, column=0, padx=2, pady=2) credit = Tk.Button(info.frame, text="Citing Chimera", command=lambda: help.display("credits.html")) credit.grid(row=2, column=1, padx=2, pady=2) # Image camera self.raytrace = BooleanOption(master, -1, 'Raytrace with POV-Ray', False, self._updateRaytrace) self.raytraceOptions = Tk.Button(master, text=POVRAY_SETUP, command=self.showPOVRayOptions) self.raytraceOptions.pack() self.raytraceOptions.pack_forget() self.supersample = SupersampleOption(master, -1, SUPERSAMPLE, preferences.get(IMAGE_SETUP, SUPERSAMPLE), self._updateSS) self.adjustFOV = AdjustFOVOption(master, -1, ADJUST_FOV, preferences.get(IMAGE_SETUP, ADJUST_FOV), self._updateAdjustFOV) self.printMode = _PrintModeOption(master, -1, 'Image camera mode', _PrintModeOption.SAME, self._updatePrintMode) self.lenticular = IntOption(master, -1, 'Number of lenticular images', chimera.Camera.lenticularImageCount(), self._updateLenticular, min=2, width=4) self.lenticular.forget() # switch to user's prefered units self.adjust = convert['pixels'] units = preferences.get(IMAGE_SETUP, UNITS) self._updateUsePrint() self.units.set(units) self.updateImageUnits() def map(self, event=None): self._ModelTrigger = chimera.triggers.addHandler('Model', self._computeMaxLineWidth, None) #self._SetupTrigger = chimera.triggers.addHandler(IMAGE_SETUP, # self._computeMaxLineWidth, None) self._SizeTrigger = chimera.triggers.addHandler( 'graphics window size', self._resetSize, None) self._computeMaxLineWidth() def unmap(self, event=None): if self._ModelTrigger: chimera.triggers.deleteHandler('Model', self._ModelTrigger) self._ModelTrigger = None #if self._SetupTrigger: # chimera.triggers.deleteHandler(IMAGE_SETUP, # self._SetupTrigger) # self._SetupTrigger = None def _computeMaxLineWidth(self, *args): if self.raytrace and self.raytrace.get(): # not relevant if raytracing self.status('', blankAfter=0) return # this should be called models are modified, when the # image size changes and when image setup parameters # change (DPI, supersampling) opengl_max = min( chimera.opengl_getFloat("max point size"), chimera.opengl_getFloat("max line width")) max_lw = max([m.lineWidth for m in chimera.openModels.list(all=True) if hasattr(m, 'lineWidth')]) # compute tile scaling factor like C++ code does width = self.iWidth.get() height = self.iHeight.get() horizPixels, vertPixels, supersample = \ imageArgs(self.units.get(), width, height) width, height = chimera.viewer.windowSize tileScale = float(horizPixels) / float(width) tmp = float(vertPixels) / float(height) if tmp > tileScale: tileScale = tmp tileScale *= supersample opengl_max /= tileScale if max_lw > opengl_max: color = 'red' else: color = 'black' self.status('effective maximum line width is %g' % opengl_max, color=color, blankAfter=0) #def Print(self): # self.Cancel() # image, options = self.getImage() # filename = tempfile.mktemp() # image.save(filename, **options) # cmd = preferences.get(PAGE_SETUP, PRINTER_CMD) # cmd = re.sub('%s', "'" + filename + "'", cmd) # os.system(cmd) # os.unlink(filename) def SaveAs(self): # now save the image self.Cancel() printMode = self.printMode.get() raytrace = self.raytrace.get() if printMode == _PrintModeOption.SAME: printMode = None if not chimera.nogui and raytrace and chimera.viewer.clipping: dialog = ClipWarning() if not dialog.run(chimera.tkgui.app): return saveImage(None, self.iWidth.get(), self.iHeight.get(), units=self.units.get(), master=self.uiMaster(), description=self.description.get().strip(), printMode=printMode, raytrace=raytrace) def Tips(self): import help help.display(self.help + "#tips") def Resize(self, larger=True): vw, vh = chimera.viewer.windowSize iw = self.iWidth.get() ih = self.iHeight.get() vaspect = vw / float(vh) iaspect = iw / float(ih) from chimera import tkgui top = tkgui.app.winfo_toplevel() if larger: if vaspect < iaspect: w = int(vw * iaspect / vaspect + 0.5) if w != vw: top.wm_geometry('') tkgui.app.graphics.config(width=w) elif vaspect > iaspect: h = int(vh * vaspect / iaspect + 0.5) if h != vh: top.wm_geometry('') tkgui.app.graphics.config(height=h) else: if vaspect < iaspect: h = int(vh * vaspect / iaspect + 0.5) if h != vh: top.wm_geometry('') tkgui.app.graphics.config(height=h) elif vaspect > iaspect: w = int(vw * iaspect / vaspect + 0.5) if w != vw: top.wm_geometry('') tkgui.app.graphics.config(width=w) def fetchWindowSize(self): w, h = chimera.viewer.windowSize self.units.set('pixels') self.updateImageUnits() self.iWidth.set(w) self.iHeight.set(h) def _updateRaytrace(self, option): raytrace = option.get() if raytrace: self.printMode.forget() self.lenticular.forget() self.supersample.forget() self.raytraceOptions.pack() else: self.raytraceOptions.pack_forget() self.printMode.manage() self.supersample.manage() self._updatePrintMode(self.printMode) self._computeMaxLineWidth() def _updatePrintMode(self, option): printMode = option.get() if printMode == 'lenticular': self.lenticular.manage() else: self.lenticular.forget() def _updateLenticular(self, option): count = option.get() chimera.Camera.setLenticularImageCount(count) def updateMatchAspect(self, *args): if self.matchAspect.get(): self.grow.config(state=Tk.DISABLED) self.shrink.config(state=Tk.DISABLED) self.Resize() else: self.grow.config(state=Tk.NORMAL) self.shrink.config(state=Tk.NORMAL) def updateImageUnits(self, *args): units = self.units.get() if units == 'pixels': self.printRes.disable() self.adjustFOV.disable() else: self.printRes.enable() self.adjustFOV.enable() if units != preferences.get(IMAGE_SETUP, UNITS): preferences.set(IMAGE_SETUP, UNITS, units) try: adjust = convert[units] except KeyError: adjust = -1 if adjust == self.adjust: return if self.adjust != -1 and adjust != -1: factor = self.adjust / adjust w = self.iWidth.get() * factor self.iWidth.set(w) h = self.iHeight.get() * factor self.iHeight.set(h) if adjust == -1: # entering pixel mode w, h = chimera.viewer.windowSize self.iWidth.set(w) self.iHeight.set(h) elif self.adjust == -1: pass # leaving pixel mode, sanity check #w, h = paper_types[preferences.get(PAGE_SETUP, PAPER_TYPE)] #if self.iWidth.get() > w: # self.iWidth.set(w) #if self.iHeight.get() > h: # self.iHeight.set(h) self.adjust = adjust self._computeMaxLineWidth() def updateImageWidth(self, option): # adjust height to compensate for new width if self.matchAspect.get(): iWidth = option.get() w, h = chimera.viewer.windowSize self.iHeight.set(iWidth * h / w) self._computeMaxLineWidth() def updateImageHeight(self, option): # adjust width to compensate for new height if self.matchAspect.get(): iHeight = option.get() w, h = chimera.viewer.windowSize self.iWidth.set(iHeight * w / h) self._computeMaxLineWidth() def _resetSize(self, triggerName, myData, sizes): width, height, mmwidth, mmheight = sizes units = self.units.get() if units == 'pixels': self.iWidth.set(width) self.iHeight.set(height) else: adjust = convert['millimeters'] / convert[units] self.iWidth.set(mmwidth * adjust) self.iHeight.set(mmheight * adjust) self._computeMaxLineWidth() def _updateUsePrint(self): usePrint = self.usePrint.get() preferences.set(IMAGE_SETUP, USE_PRINT_UNITS, usePrint) if not usePrint: values = ['pixels'] else: values = convert.keys() try: values.remove('pixels') except ValueError: pass values.sort() self.units.values = values self.units.remakeMenu() if usePrint: self.units.set('inches') else: self.units.set('pixels') self.updateImageUnits() if not usePrint: self.fetchWindowSize() def _updatePrint(self, option): res = option.get() preferences.set(IMAGE_SETUP, DPI, res) def _updateAdjustFOV(self, option): adjust = option.get() preferences.set(IMAGE_SETUP, ADJUST_FOV, adjust) def _updateSS(self, option): ss = option.get() preferences.set(IMAGE_SETUP, SUPERSAMPLE, ss) self._computeMaxLineWidth() #def showImageSetupDialog(self, *args): # import dialogs # d = dialogs.display("preferences") # d.setCategoryMenu(IMAGE_SETUP) def showImageCreditsDialog(self, *args): import dialogs d = dialogs.display("preferences") d.setCategoryMenu(IMAGE_CREDITS) def showPOVRayOptions(self, *args): import dialogs d = dialogs.display("preferences") d.setCategoryMenu(POVRAY_SETUP)
class CreateAxesDialog(ModelessDialog): title = "Define Axes" help = "ContributedSoftware/structuremeas/structuremeas.html#define-axes" provideStatus = True statusPosition = "above" MODE_HELICES, MODE_SELECTION = range(2) def fillInUI(self, parent): import Pmw, Tkinter row = 0 Tkinter.Label(parent, text="Create axis for...").grid(row=row, sticky='w') row += 1 self.modeVar = Tkinter.IntVar(parent) self.modeVar.set(self.MODE_HELICES) f = Tkinter.Frame(parent) f.grid(row=row, sticky='nsew') row += 1 Tkinter.Radiobutton(f, text="Each helix in:", command=self._helixCB, variable=self.modeVar, value=self.MODE_HELICES).grid(row=0, column=0) from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(f, listbox_selectmode='extended') self.molList.grid(row=0, column=1, sticky="nsew") parent.rowconfigure(1, weight=1) parent.columnconfigure(0, weight=1) f.rowconfigure(0, weight=1) f.columnconfigure(1, weight=1) f = Tkinter.Frame(parent) f.grid(row=row, sticky='w') row += 1 Tkinter.Radiobutton(f, text="Selected atoms (axis name:", command=self._selCB, variable=self.modeVar, value=self.MODE_SELECTION).grid(row=0, column=0) self.axisNameVar = Tkinter.StringVar(parent) self.axisNameVar.set("axis") Tkinter.Entry(f, textvariable=self.axisNameVar, width=10).grid(row=0, column=1) Tkinter.Label(f, text=")").grid(row=0, column=2) paramGroup = Pmw.Group(parent, tag_text="Axis Parameters") paramGroup.grid(row=row, column=0) row += 1 paramFrame = paramGroup.interior() prow = 0 butFrame = Tkinter.Frame(paramFrame) butFrame.grid(row=prow, column=0, columnspan=3) prow += 1 self.massWeighting = Tkinter.IntVar(parent) self.massWeighting.set(False) self._mwButton = Tkinter.Checkbutton(butFrame, command=self._mwCB, text="Mass weighting", variable=self.massWeighting) self._mwButton.grid(row=0, column=0, sticky='w') self._mwButton.grid_remove() self.helixCorrection = Tkinter.IntVar(parent) self.helixCorrection.set(True) Tkinter.Checkbutton(butFrame, text="Use helical correction", command=self._hcCB, variable=self.helixCorrection).grid(row=1, column=0, sticky='w') self.replaceExisting = Tkinter.IntVar(parent) self.replaceExisting.set(True) Tkinter.Checkbutton(butFrame, text="Replace existing axes", variable=self.replaceExisting).grid(row=2, column=0, sticky='w') f = Tkinter.Frame(paramFrame) f.grid(row=prow, column=0, columnspan=3) prow += 1 from chimera.tkoptions import ColorOption, FloatOption self.colorOpt = ColorOption( f, prow, "Color", None, None, balloon="Axis color. If No Color, then the axis" " will be colored to match the structure") Tkinter.Label(paramFrame, text="Radius:").grid(row=prow, column=0, rowspan=2) self.fixedRadiusVar = Tkinter.IntVar(parent) self.fixedRadiusVar.set(False) Tkinter.Radiobutton(paramFrame, variable=self.fixedRadiusVar, padx=0, value=False).grid(row=prow, column=1) Tkinter.Label(paramFrame, text="average axis-atom distance").grid(row=prow, column=2, sticky='w') Tkinter.Radiobutton(paramFrame, variable=self.fixedRadiusVar, padx=0, value=True).grid(row=prow + 1, column=1) f = Tkinter.Frame(paramFrame) f.grid(row=prow + 1, column=2, sticky='w') self.radiusOpt = FloatOption(f, 0, "angstroms", prefs[AXIS_RADIUS], None, min=0.01) def Apply(self): from chimera import UserError if self.replaceExisting.get(): axisManager.removeAxes(axisManager.axes) kw = {} kw['color'] = self.colorOpt.get() if self.fixedRadiusVar.get(): kw['radius'] = prefs[AXIS_RADIUS] = self.radiusOpt.get() kw['massWeighting'] = self.massWeighting.get() \ and self.modeVar.get() == self.MODE_SELECTION kw['helicalCorrection'] = self.helixCorrection.get() \ and not kw['massWeighting'] if kw['helicalCorrection']: replyobj.info("Creating axes with helical correction\n") elif kw['massWeighting']: replyobj.info("Creating axes with mass weighting\n") else: replyobj.info("Creating axes\n") if self.modeVar.get() == self.MODE_HELICES: mols = self.molList.getvalue() if not mols: self.enter() raise UserError("No molecules chosen") created = 0 for m in mols: createHelices(m, **kw) else: selAtoms = selection.currentAtoms() if len(selAtoms) < 3: self.enter() raise UserError("Need to select at least three" " atoms to define an axis") axisManager.createAxis(self.axisNameVar.get().strip(), selAtoms, **kw) def _helixCB(self): self._mwButton.grid_remove() def _hcCB(self): if self.helixCorrection.get() and self.massWeighting.get(): self.massWeighting.set(False) def _mwCB(self): if self.massWeighting.get() and self.helixCorrection.get(): self.helixCorrection.set(False) def _selCB(self): self._mwButton.grid()
def fillInUI(self, parent): parent.columnconfigure(0, pad=2) parent.columnconfigure(1, pad=2) import itertools row = itertools.count() self.showBackbone = BackboneOption(parent, row.next(), 'Show backbone as', 'ribbon', None) self.showSide = SideOption(parent, row.next(), 'Show side (sugar/base) as', 'fill/slab', self._showSideCB) self.showOrientation = BooleanOption(parent, row.next(), 'Show base orientation', default.ORIENT, None) import Tix self.nb = Tix.NoteBook(parent) self.nb.grid(row=row.next(), column=0, columnspan=2, sticky=Tk.EW, padx=2) # ladder page self.nb.add("ladder", label="Ladder Options") f = self.nb.page("ladder") if Tk.TkVersion >= 8.5: parent.tk.call('grid', 'anchor', f._w, Tk.N) prow = itertools.count() self.skipNonBase = BooleanOption(f, prow.next(), 'Ignore non-base H-bonds', default.IGNORE, None) self.showStubs = BooleanOption(f, prow.next(), 'Show stubs', default.STUBS, None) self.rungRadius = FloatOption(f, prow.next(), 'Rung radius', default.RADIUS, None) self.rungRadius.min = 0.0 self.useExisting = BooleanOption(f, prow.next(), 'Using existing H-bonds', default.USE_EXISTING, self._useExistingCB) from FindHBond.gui import RelaxParams self.relaxParams = RelaxParams(f, None, colorOptions=False) #self.relaxParams.relaxConstraints = False self.relaxParams.grid(row=prow.next(), columnspan=2, sticky='nsew', padx=2) # slab page self.nb.add("slab", label="Slab Options") f = self.nb.page("slab") if Tk.TkVersion >= 8.5: parent.tk.call('grid', 'anchor', f._w, Tk.N) prow = itertools.count() self.thickness = FloatOption(f, prow.next(), 'Thickness', default.THICKNESS, None) self.thickness.min = 0.01 self.shape = ShapeOption(f, prow.next(), 'Slab object', default.SHAPE, None) self.hideBases = BooleanOption(f, prow.next(), 'Hide base atoms', default.HIDE, None) self.showGlycosidic = BooleanOption(f, prow.next(), 'Separate glycosidic bond', default.GLYCOSIDIC, None) self.nb.add("style", label="Slab Style", raisecmd=self.map) # style page f = self.nb.page("style") if Tk.TkVersion >= 8.5: f.tk.call('grid', 'anchor', f._w, Tk.N) info = NA.findStyle(self.currentStyle) from chimera.preferences import saveui f2 = Tk.Frame(f) self.saveui = saveui.SaveUI(f2, self) f2.grid(row=prow.next(), column=0, columnspan=2, sticky=Tk.EW, padx=2, pady=2) self.anchor = AnchorOption(f, prow.next(), 'Anchor', info[NA.ANCHOR], self._drawStyle) f2 = Pmw.Group(f, tag_text=NA.PURINE.title()) f2.grid(row=prow.next(), column=0, columnspan=2, sticky=Tk.EW, padx=2) f2 = f2.interior() f2.columnconfigure(0, weight=1, pad=2, uniform='a') f2.columnconfigure(1, weight=1, uniform='a') f2.columnconfigure(2, weight=1) self.purine_canvas = Tk.Canvas(f2, width=1, height=1) #, #borderwidth=2, relief=Tk.RIDGE) r = prow.next() self.purine_canvas.grid(row=r, column=0, rowspan=3, sticky=Tk.NSEW, padx=2, pady=2) corners = info[NA.PURINE] self.puLL = Float2Option(f2, prow.next(), 'Lower left', corners[0], self._drawStyle, startCol=1) self.puUR = Float2Option(f2, prow.next(), 'Upper right', corners[1], self._drawStyle, startCol=1) f3 = Pmw.Group(f, tag_text="%s, %s" % (NA.PYRIMIDINE.title(), NA.PSEUDO_PYRIMIDINE.title())) r = prow.next() f3.grid(row=r, column=0, columnspan=2, sticky=Tk.EW, padx=2) f3 = f3.interior() f3.columnconfigure(0, weight=1, pad=2, uniform='a') f3.columnconfigure(1, weight=1, uniform='a') f3.columnconfigure(2, weight=1) self.pyrimidine_canvas = Tk.Canvas(f3, width=1, height=1) #, #borderwidth=2, relief=Tk.RIDGE) r = prow.next() self.pyrimidine_canvas.grid(row=r, column=0, rowspan=3, sticky=Tk.NSEW, padx=2, pady=2) corners = info[NA.PYRIMIDINE] self.pyLL = Float2Option(f3, prow.next(), 'Lower left', corners[0], self._drawStyle, startCol=1) self.pyUR = Float2Option(f3, prow.next(), 'Upper right', corners[1], self._drawStyle, startCol=1) self.restrict = Tk.IntVar(parent) self.restrict.set(1) cb = Tk.Checkbutton(parent, variable=self.restrict, text="Restrict OK/Apply to current selection, if any") cb.grid(row=row.next(), columnspan=2) parent.pack(ipady=2) self._showSideCB() chimera.triggers.addHandler(NA.TRIGGER_SLAB_STYLES, self._updateStyles, None)
class AnisoDialog(ModelessDialog): title = "Thermal Ellipsoids" name = "anisotropic ellipsoids" buttons = ("Show Ellipsoids", "Hide Ellipsoids", "Close") help = "ContributedSoftware/thermal/thermal.html" builtinPresets = [("Simple ellipsoid", {}), ("Principal axes", { "ellipsoid": False, "axisFactor": 1.0 }), ("Principal ellipses", { "ellipsoid": False, "ellipseFactor": 1.0 }), ("Ellipsoid and principal axes", { "axisFactor": 1.5 }), ("Octant lines", { "ellipseFactor": 1.01, "ellipseColor": (0, 0, 0, 1) }), ("Snow globe axes", { "ellipsoidColor": (1, 1, 1, 1), "transparency": 50.0, "axisFactor": 0.99 }), ("Snow globe ellipses", { "ellipsoidColor": (1, 1, 1, 1), "transparency": 50.0, "ellipseFactor": 0.99 })] def fillInUI(self, parent): import Pmw, Tkinter top = parent.winfo_toplevel() menubar = Tkinter.Menu(top, type="menubar", tearoff=False) top.config(menu=menubar) self.presetsMenu = Tkinter.Menu(menubar) menubar.add_cascade(label="Presets", menu=self.presetsMenu) presets = self.builtinPresets + prefs[PRESETS] for label, kw in presets: self.presetsMenu.add_command( label=label, command=lambda kw=kw: self.preset(**kw)) self.presetsMenu.add_separator() self.presetsMenu.add_command(label="Preset from current settings...", command=self.startDefinePreset) self.presetsMenu.add_command(label="Delete user preset...", command=self.startDeletePreset) from chimera.tkgui import aquaMenuBar row = aquaMenuBar(menubar, parent, row=0, columnspan=2) parent.columnconfigure(0, weight=1) parent.columnconfigure(1, weight=1) self._modFromCalc = False self.scaling = Pmw.EntryField(parent, labelpos='w', value='1', label_text="Scale factor:", entry_width=5, validate={ 'validator': 'real', 'min': 0.0 }, modifiedcommand=self._scaleTypingCB, command=self.ShowEllipsoids) self.scaling.grid(row=row, column=0) self.smoothing = Pmw.EntryField(parent, labelpos='w', label_text="Smoothing level:", validate={ 'validator': 'numeric', 'min': 1, 'max': 100 }, value='3', entry_width=2, command=self.ShowEllipsoids) self.smoothing.grid(row=row, column=1) row += 1 self.calculator = Pmw.EntryField( parent, labelpos='w', label_text="Set scale factor for probability (%):", entry_width=4, command=self._prob2scaling) self.calculator.grid(row=row, column=0, columnspan=2) row += 1 from chimera.tkoptions import SymbolicEnumOption, \ FloatOption, RGBAOption self.showEllipsoidVar = Tkinter.IntVar(parent) self.showEllipsoidVar.set(True) ellipsoidGroup = Pmw.Group(parent, tag_pyclass=Tkinter.Checkbutton, tag_text="Depict ellipsoids", tag_variable=self.showEllipsoidVar) ellipsoidGroup.grid(row=row, column=0, columnspan=2, sticky="ew") row += 1 inside = ellipsoidGroup.interior() inside.columnconfigure(0, weight=1, uniform=1) inside.columnconfigure(1, weight=1, uniform=1) self.ellipsoidColorOpt = RGBAOption( inside, 0, 'Color', None, None, noneOkay=True, balloon='"No color" means use atom colors') class TransparencyOption(SymbolicEnumOption): values = [ None, 0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0 ] labels = [ "same as color", "0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%" ] self.transparencyOpt = TransparencyOption(inside, 1, "Transparency", None, None) self.showAxesVar = Tkinter.IntVar(parent) self.showAxesVar.set(False) axesGroup = Pmw.Group(parent, tag_pyclass=Tkinter.Checkbutton, tag_text="Depict principal axes", tag_variable=self.showAxesVar) axesGroup.grid(row=row, column=0, columnspan=2, sticky="ew") row += 1 inside = axesGroup.interior() inside.columnconfigure(0, weight=1, uniform=1) inside.columnconfigure(1, weight=1, uniform=1) self.axisColorOpt = RGBAOption( inside, 0, 'Color', None, None, noneOkay=True, balloon='"No color" means use atom colors') self.axisFactorOpt = FloatOption(inside, 1, "Length factor", 1.5, self.ShowEllipsoids, balloon="relative to ellipsoids", sticky="w") self.axisThicknessOpt = FloatOption(inside, 2, "Thickness", 0.01, self.ShowEllipsoids, sticky="w") self.showEllipsesVar = Tkinter.IntVar(parent) self.showEllipsesVar.set(False) ellipsesGroup = Pmw.Group(parent, tag_pyclass=Tkinter.Checkbutton, tag_text="Depict principal ellipses", tag_variable=self.showEllipsesVar) ellipsesGroup.grid(row=row, column=0, columnspan=2, sticky="ew") row += 1 inside = ellipsesGroup.interior() inside.columnconfigure(0, weight=1, uniform=1) inside.columnconfigure(1, weight=1, uniform=1) self.ellipseColorOpt = RGBAOption( inside, 0, 'Color', None, None, noneOkay=True, balloon='"No color" means use atom colors') self.ellipseFactorOpt = FloatOption(inside, 1, "Size factor", 1.0, self.ShowEllipsoids, balloon="relative to ellipsoids", sticky="w") self.ellipseThicknessOpt = FloatOption(inside, 2, "Thickness", 0.02, self.ShowEllipsoids, sticky="w") self.selRestrictVar = Tkinter.IntVar(parent) self.selRestrictVar.set(False) Tkinter.Checkbutton(parent, text="Restrict Show/Hide to current" " selection, if any", variable=self.selRestrictVar).grid(row=row, column=0, columnspan=2) row += 1 def ShowEllipsoids(self, *args): if self.showAxesVar.get(): axisFactor = self.axisFactorOpt.get() else: axisFactor = None if self.showEllipsesVar.get(): ellipseFactor = self.ellipseFactorOpt.get() else: ellipseFactor = None kw = { 'color': self.ellipsoidColorOpt.get(), 'smoothing': int(self.smoothing.getvalue()), 'scale': float(self.scaling.getvalue()), 'showEllipsoid': self.showEllipsoidVar.get(), 'transparency': self.transparencyOpt.get(), 'axisFactor': axisFactor, 'axisColor': self.axisColorOpt.get(), 'axisThickness': self.axisThicknessOpt.get(), 'ellipseFactor': ellipseFactor, 'ellipseColor': self.ellipseColorOpt.get(), 'ellipseThickness': self.ellipseThicknessOpt.get() } if self.selRestrictVar.get(): from chimera.selection import currentAtoms selAtoms = currentAtoms() if selAtoms: kw['targets'] = selAtoms from Aniso import aniso from Midas import MidasError try: aniso(**kw) except MidasError: from chimera import UserError raise UserError("No atoms chosen had anisotropic" " information") def HideEllipsoids(self): kw = {} if self.selRestrictVar.get(): from chimera.selection import currentAtoms selAtoms = currentAtoms() if selAtoms: kw['targets'] = selAtoms from Aniso import unaniso unaniso(**kw) def preset(self, ellipsoid=True, ellipsoidColor=None, transparency=None, axisFactor=None, axisColor=None, axisThickness=0.01, ellipseFactor=None, ellipseColor=None, ellipseThickness=0.02): self.showEllipsoidVar.set(ellipsoid) if ellipsoid: self.ellipsoidColorOpt.set(ellipsoidColor) self.transparencyOpt.set(transparency) if axisFactor: self.showAxesVar.set(True) self.axisFactorOpt.set(axisFactor) self.axisColorOpt.set(axisColor) self.axisThicknessOpt.set(axisThickness) else: self.showAxesVar.set(False) if ellipseFactor: self.showEllipsesVar.set(True) self.ellipseFactorOpt.set(ellipseFactor) self.ellipseColorOpt.set(ellipseColor) self.ellipseThicknessOpt.set(ellipseThickness) else: self.showEllipsesVar.set(False) self.ShowEllipsoids() def startDefinePreset(self): if not hasattr(self, "_presetNameDialog"): import Pmw self._presetNameDialog = Pmw.PromptDialog( self.uiMaster(), title="Preset Name", label_text="Preset name:", entryfield_labelpos='w', defaultbutton=0, buttons=('OK', 'Cancel'), command=self._definePresetCB) self._presetNameDialog.show() def startDeletePreset(self): if not prefs[PRESETS]: from chimera import UserError raise UserError("No user presets have been defined") if not hasattr(self, "_presetDeleteDialog"): import Pmw self._presetDeleteDialog = Pmw.SelectionDialog( self.uiMaster(), title="Delete Preset", label_text="Preset name:", scrolledlist_labelpos='n', defaultbutton=0, scrolledlist_items=[ps[0] for ps in prefs[PRESETS]], buttons=('OK', 'Cancel'), command=self._deletePresetCB) self._presetDeleteDialog.show() def _definePresetCB(self, button): self._presetNameDialog.withdraw() if button is None or button == 'Cancel': return name = self._presetNameDialog.get().strip() if not name: self._presetNameDialog.show() from chimera import UserError UserError("Must provide preset name") if name in [x[0] for x in self.builtinPresets]: self._presetNameDialog.show() from chimera import UserError UserError("Cannot redefine builtin preset") anisoKw = {} anisoKw['ellipsoid'] = self.showEllipsoidVar.get() if anisoKw['ellipsoid']: anisoKw['ellipsoidColor'] = self.ellipsoidColorOpt.get() anisoKw['transparency'] = self.transparencyOpt.get() if self.showAxesVar.get(): anisoKw['axisFactor'] = self.axisFactorOpt.get() anisoKw['axisColor'] = self.axisColorOpt.get() anisoKw['axisThickness'] = self.axisThicknessOpt.get() if self.showEllipsesVar.get(): anisoKw['ellipseFactor'] = self.ellipseFactorOpt.get() anisoKw['ellipseColor'] = self.ellipseColorOpt.get() anisoKw['ellipseThickness'] = self.ellipseThicknessOpt.get() newPreset = (name, anisoKw) customPresets = prefs[PRESETS][:] for info in customPresets: if info[0] == name: # changing _contents_ of kw dictionary means we don't # have to redefine the menu command action info[1].clear() info[1].update(anisoKw) break else: customPresets.append(newPreset) self.presetsMenu.insert_command( len(self.builtinPresets) + len(customPresets), label=name, command=lambda kw=anisoKw: self.preset(**kw)) prefs[PRESETS] = customPresets def _deletePresetCB(self, result): self._presetDeleteDialog.withdraw() if result is None or result == 'Cancel': self._presetDeleteDialog.destroy() delattr(self, '_presetDeleteDialog') return deletions = self._presetDeleteDialog.getvalue() remaining = [ps for ps in prefs[PRESETS] if ps[0] not in deletions] prefs[PRESETS] = remaining for name in deletions: self.presetsMenu.delete(name) self._presetDeleteDialog.destroy() delattr(self, '_presetDeleteDialog') def _prob2scaling(self): try: prob = float(self.calculator.getvalue()) / 100.0 if prob < 0.0 or prob >= 1.0: raise ValueError("bad prob") except ValueError: from chimera import UserError raise UserError("Probability must be >= 0 and < 100") from Aniso import prob2scale self._modFromCalc = True self.scaling.setvalue("%g" % prob2scale(prob)) self._modFromCalc = False def _scaleTypingCB(self): if not self._modFromCalc: self.calculator.setvalue("")
def fillInUI(self, parent): import Pmw, Tkinter row = 0 Tkinter.Label(parent, text="Create axis for...").grid(row=row, sticky='w') row += 1 self.modeVar = Tkinter.IntVar(parent) self.modeVar.set(self.MODE_HELICES) f = Tkinter.Frame(parent) f.grid(row=row, sticky='nsew') row += 1 Tkinter.Radiobutton(f, text="Each helix in:", command=self._helixCB, variable=self.modeVar, value=self.MODE_HELICES).grid(row=0, column=0) from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(f, listbox_selectmode='extended') self.molList.grid(row=0, column=1, sticky="nsew") parent.rowconfigure(1, weight=1) parent.columnconfigure(0, weight=1) f.rowconfigure(0, weight=1) f.columnconfigure(1, weight=1) f = Tkinter.Frame(parent) f.grid(row=row, sticky='w') row += 1 Tkinter.Radiobutton(f, text="Selected atoms (axis name:", command=self._selCB, variable=self.modeVar, value=self.MODE_SELECTION).grid(row=0, column=0) self.axisNameVar = Tkinter.StringVar(parent) self.axisNameVar.set("axis") Tkinter.Entry(f, textvariable=self.axisNameVar, width=10).grid(row=0, column=1) Tkinter.Label(f, text=")").grid(row=0, column=2) paramGroup = Pmw.Group(parent, tag_text="Axis Parameters") paramGroup.grid(row=row, column=0) row += 1 paramFrame = paramGroup.interior() prow = 0 butFrame = Tkinter.Frame(paramFrame) butFrame.grid(row=prow, column=0, columnspan=3) prow += 1 self.massWeighting = Tkinter.IntVar(parent) self.massWeighting.set(False) self._mwButton = Tkinter.Checkbutton(butFrame, command=self._mwCB, text="Mass weighting", variable=self.massWeighting) self._mwButton.grid(row=0, column=0, sticky='w') self._mwButton.grid_remove() self.helixCorrection = Tkinter.IntVar(parent) self.helixCorrection.set(True) Tkinter.Checkbutton(butFrame, text="Use helical correction", command=self._hcCB, variable=self.helixCorrection).grid(row=1, column=0, sticky='w') self.replaceExisting = Tkinter.IntVar(parent) self.replaceExisting.set(True) Tkinter.Checkbutton(butFrame, text="Replace existing axes", variable=self.replaceExisting).grid(row=2, column=0, sticky='w') f = Tkinter.Frame(paramFrame) f.grid(row=prow, column=0, columnspan=3) prow += 1 from chimera.tkoptions import ColorOption, FloatOption self.colorOpt = ColorOption( f, prow, "Color", None, None, balloon="Axis color. If No Color, then the axis" " will be colored to match the structure") Tkinter.Label(paramFrame, text="Radius:").grid(row=prow, column=0, rowspan=2) self.fixedRadiusVar = Tkinter.IntVar(parent) self.fixedRadiusVar.set(False) Tkinter.Radiobutton(paramFrame, variable=self.fixedRadiusVar, padx=0, value=False).grid(row=prow, column=1) Tkinter.Label(paramFrame, text="average axis-atom distance").grid(row=prow, column=2, sticky='w') Tkinter.Radiobutton(paramFrame, variable=self.fixedRadiusVar, padx=0, value=True).grid(row=prow + 1, column=1) f = Tkinter.Frame(paramFrame) f.grid(row=prow + 1, column=2, sticky='w') self.radiusOpt = FloatOption(f, 0, "angstroms", prefs[AXIS_RADIUS], None, min=0.01)
def fillInUI(self, parent): from chimera.tkoptions import IntOption, BooleanOption, \ FloatOption Tkinter.Label(parent, text="Create RMSD map of trajectory " "against itself", relief="ridge", bd=4).grid(row=0, column=0, columnspan=2, sticky="ew") startFrame = self.movie.startFrame endFrame = self.movie.endFrame self.startFrame = IntOption(parent, 1, "Starting frame", startFrame, None, min=startFrame, max=endFrame, width=6) numFrames = endFrame - startFrame + 1 defStride = 1 + int(numFrames / 300) self.stride = IntOption(parent, 2, "Step size", defStride, None, min=1, max=numFrames, width=3) self.endFrame = IntOption(parent, 3, "Ending frame", endFrame, None, min=startFrame, max=endFrame, width=6) self.minRmsd = FloatOption(parent, 4, "Lower RMSD threshold" " (white)", prefs[RMSD_MIN], None, width=6) self.maxRmsd = FloatOption(parent, 5, "Upper RMSD threshold" " (black)", prefs[RMSD_MAX], None, width=6) self.useSel = BooleanOption( parent, 6, "Restrict map to " "current selection, if any", True, None) self.ignoreBulk = BooleanOption(parent, 7, "Ignore solvent/" "ions", True, None) self.ignoreHyds = BooleanOption(parent, 8, "Ignore hydrogens", True, None) self.recolor = BooleanOption(parent, 9, "Auto-recolor for" " contrast", prefs[RMSD_AUTOCOLOR], None)
class EspDialog(ModelessDialog): title = "Coulombic Surface Coloring" name = "ESP computation" help = "ContributedSoftware/coulombic/coulombic.html" HB = "estimated from H-bonds" def fillInUI(self, parent): import Pmw, Tkinter self.buttonWidgets['OK']['state'] = 'disabled' self.buttonWidgets['Apply']['state'] = 'disabled' from chimera.widgets import ModelScrolledListBox self.surfListBox = ModelScrolledListBox( parent, labelpos='n', label_text='Surfaces to color by ESP:', listbox_selectmode="extended", filtFunc=lambda m: isinstance(m, chimera.MSMSModel), selectioncommand=self._selSurfCB) self.surfListBox.grid(row=0, column=0, sticky="nsew", columnspan=2) Pmw.OptionMenu(parent, command=self._menuCB, initialitem="3", items=[str(x) for x in range(2, 12)], labelpos='w', label_text="Number of colors/values:").grid( row=1, column=0, columnspan=2) f = self.interpFrame = Tkinter.Frame(parent) f.grid(row=2, column=0, columnspan=2) self.wells = [] self.values = [] self._entryOpts = { 'validate': 'real', 'entry_justify': 'center', 'entry_width': 6 } from CGLtk.color.ColorWell import ColorWell for color, value in [("red", -10), ("white", 0), ("blue", 10)]: well = ColorWell(f, color=color) well.grid(row=0, column=len(self.wells)) self.wells.append(well) entry = Pmw.EntryField(f, value=str(value), **self._entryOpts) entry.grid(row=1, column=len(self.values)) self.values.append(entry) from chimera.tkoptions import FloatOption, BooleanOption self.distDep = BooleanOption( parent, 3, "Distance-dependent dielectric", True, None, balloon="If true, charge falls off with distance squared to\n" "simulate solvent screening effects") self.dielectric = FloatOption(parent, 4, "Dielectric constant", 4.0, None) self.surfDist = FloatOption(parent, 5, "Distance from surface", 1.4, None, balloon="Potential at this distance from\n" "the surface is used for coloring") self.hisGroup = Pmw.Group(parent, hull_padx=2, tag_text="Implicit Histidine Protonation") self.hisGroup.grid(row=6, column=0, columnspan=2, sticky="nsew") self.hisProtVar = Tkinter.StringVar(parent) self.hisProtVar.set("name") interior = self.hisGroup.interior() interior.columnconfigure(0, weight=1) lab = Tkinter.Label( interior, text="Assumed histidine " "protonation for\nstructures without explicit hydrogens") from tkFont import Font font = Font(font=lab.cget('font')) font.config(size=int(0.75 * float(font.cget('size'))), slant='italic') lab.config(font=font) lab.grid(row=0) Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="name", text="Residue name-based", command=self._switchHisList).grid(row=1, sticky='w') f = Tkinter.Frame(interior) f.grid(row=2) Tkinter.Label(f, text="HID/HIE/HIP = delta/epsilon/both").grid(row=0, sticky='w') self.hisDefault = Pmw.OptionMenu( f, initialitem=self.HB, items=[self.HB, "delta", "epsilon", "both"], labelpos='w', label_text="HIS = ", command=lambda a, s=self: setattr(s, 'hisChanged', True)) self.hisDefault.grid(row=1, sticky='w') self._pickText = Tkinter.StringVar(parent) self._pickText.set("Specified individually...") Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="pick", textvariable=self._pickText, command=self._switchHisList).grid(row=3, sticky='w') Tkinter.Button(parent, pady=0, command=self._colorKeyCB, text="Create corresponding color key").grid( row=7, column=0, columnspan=2) self.hisChanged = False def Apply(self): for entry in self.values: entry.invoke() colors = [w.rgba for w in self.wells] values = [float(e.getvalue()) for e in self.values] if self.hisProtVar.get() == "name": hisScheme = { self.HB: None, 'delta': 'HID', 'epsilon': 'HIE', 'both': 'HIP' }[self.hisDefault.getvalue()] else: hisScheme = self.hisListingData from ESP import colorEsp for surf in self.surfListBox.getvalue(): if self.hisChanged: # clear out charge values so that histidines # get new charges for a in surf.atoms: a.charge = None colorEsp(surf, colors, values, dielectric=self.dielectric.get(), distDep=self.distDep.get(), surfDist=self.surfDist.get(), hisScheme=hisScheme) self.hisChanged = False def _colorKeyCB(self): for entry in self.values: entry.invoke() from Ilabel.gui import IlabelDialog from chimera import dialogs d = dialogs.display(IlabelDialog.name) d.keyConfigure( zip([w.rgba for w in self.wells], [e.getvalue() for e in self.values])) def _menuCB(self, val): newNum = int(val) oldSettings = [] for well, entry in zip(self.wells, self.values): entry.invoke() oldSettings.append((well.rgba, float(entry.getvalue()))) well.grid_forget() well.destroy() entry.grid_forget() entry.destroy() import Pmw from CGLtk.color.ColorWell import ColorWell self.wells = [] self.values = [] scale = (len(oldSettings) - 1.0) / (newNum - 1.0) f = self.interpFrame for i in range(newNum): index = i * scale if index == int(index) \ or int(index) >= len(oldSettings): color, value = oldSettings[int(index)] else: lowc, lowv = oldSettings[int(index)] highc, highv = oldSettings[int(index) + 1] frac = index - int(index) color = [] for lowcomp, highcomp in zip(lowc, highc): color.append((1.0 - frac) * lowcomp + frac * highcomp) value = (1.0 - frac) * lowv + frac * highv well = ColorWell(f, color=color) well.grid(row=0, column=len(self.wells)) self.wells.append(well) entry = Pmw.EntryField(f, value=str(value), **self._entryOpts) entry.grid(row=1, column=len(self.values)) self.values.append(entry) def _selSurfCB(self): if self.surfListBox.getvalue(): state = 'normal' else: state = 'disabled' self.buttonWidgets['OK']['state'] = state self.buttonWidgets['Apply']['state'] = state self._updateHisListing() def _select(self, hisType): for r, vars in self._vars.items(): dv, ev = vars if hisType == "delta": dv.set(True) ev.set(False) self.hisListingData[r] = "HID" elif hisType == "epsilon": dv.set(False) ev.set(True) self.hisListingData[r] = "HIE" else: dv.set(True) ev.set(True) self.hisListingData[r] = "HIP" def _switchHisList(self): self.hisChanged = True if not hasattr(self, 'hisListing'): if self.hisProtVar.get() != "pick": return self.hisListingData = {} import Tix, Tkinter self.hisFrame = Tkinter.Frame(self.hisGroup.interior()) self.hisListing = Tix.ScrolledHList(self.hisFrame, width="3i", options="""hlist.columns 4 hlist.header 1 hlist.indicator 1""") self.hisListing.hlist.configure( selectbackground=self.hisListing['background'], selectborderwidth=0) self.hisListing.grid(row=0, column=0, columnspan=3, sticky="nsew") self.hisFrame.rowconfigure(1, weight=1) self.hisFrame.columnconfigure(0, weight=1) self.hisFrame.columnconfigure(1, weight=1) hlist = self.hisListing.hlist hlist.header_create(0, itemtype="text", text="Model") hlist.header_create(1, itemtype="text", text="Residue") hlist.header_create(2, itemtype="text", text="Delta") hlist.header_create(3, itemtype="text", text="Epsilon") self._checkButtonStyle = Tix.DisplayStyle( "window", background=hlist['background'], refwindow=self.hisListing, anchor='center') self._updateHisListing() Tkinter.Button(self.hisFrame, text="All Delta", pady=0, highlightthickness=0, command=lambda p="delta": self._select(p)).grid( row=1, column=0) Tkinter.Button(self.hisFrame, text="All Epsilon", pady=0, highlightthickness=0, command=lambda p="epsilon": self._select(p)).grid( row=1, column=1) Tkinter.Button(self.hisFrame, text="All Both", pady=0, highlightthickness=0, command=lambda p="both": self._select(p)).grid( row=1, column=2) if self.hisProtVar.get() == "pick": self._pickText.set("Specified individually:") self.hisFrame.grid(row=4, sticky="nsew") interior = self.hisGroup.interior() interior.rowconfigure(4, weight=1) self.uiMaster().rowconfigure(6, weight=4) else: self._pickText.set("Specified individually...") self.hisFrame.grid_forget() interior = self.hisGroup.interior() interior.rowconfigure(4, weight=0) self.uiMaster().rowconfigure(6, weight=0) def _toggleDelta(self, res): self.hisChanged = True old = self.hisListingData[res] if old == "HIS": new = "HID" elif old == "HID": new = "HIS" elif old == "HIE": new = "HIP" else: new = "HIE" self.hisListingData[res] = new def _toggleEpsilon(self, res): self.hisChanged = True old = self.hisListingData[res] if old == "HIS": new = "HIE" elif old == "HID": new = "HIP" elif old == "HIE": new = "HIS" else: new = "HID" self.hisListingData[res] = new def _updateHisListing(self): if not hasattr(self, 'hisListing'): return self._updateHisListingData() hlist = self.hisListing.hlist on = self.hisListing.tk.call('tix', 'getimage', 'ck_on') off = self.hisListing.tk.call('tix', 'getimage', 'ck_off') hlist.delete_all() import Tkinter row = 0 self._vars = {} for m in [s.molecule for s in self.surfListBox.getvalue()]: for r in m.residues: try: hisType = self.hisListingData[r] except KeyError: continue hlist.add(row, itemtype="text", text="%s (%s)" % (m.name, m.oslIdent())) hlist.item_create(row, 1, itemtype="text", text=r.oslIdent(start=chimera.SelResidue)) var = Tkinter.IntVar(hlist) var.set(hisType in ["HID", "HIP"]) cmd = lambda r=r: self._toggleDelta(r) self._vars[r] = [var] toggle = Tkinter.Checkbutton(hlist, command=cmd, variable=var, image=off, selectimage=on, selectcolor="", indicatoron=False, borderwidth=0) hlist.item_create(row, 2, itemtype="window", window=toggle, style=self._checkButtonStyle) var = Tkinter.IntVar(hlist) var.set(hisType in ["HIE", "HIP"]) cmd = lambda r=r: self._toggleEpsilon(r) self._vars[r].append(var) toggle = Tkinter.Checkbutton(hlist, command=cmd, variable=var, image=off, selectimage=on, selectcolor="", indicatoron=False, borderwidth=0) hlist.item_create(row, 3, itemtype="window", window=toggle, style=self._checkButtonStyle) row += 1 def _updateHisListingData(self): newData = {} default = { 'delta': 'HID', 'epsilon': 'HIE', 'both': 'HIP', self.HB: 'HID' }[self.hisDefault.getvalue()] for m in [s.molecule for s in self.surfListBox.getvalue()]: for r in m.residues: if r.type not in ["HIS", "HIE", "HIP", "HID"]: continue try: newData[r] = self.hisListingData[r] except KeyError: if r.type == 'HIS': newData[r] = default else: newData[r] = r.type self.hisListingData = newData
def fillInUI(self, master): self._ModelTrigger = None #self._SetupTrigger = None self._SizeTrigger = None self.raytrace = None # Image Size imageSetup = Tix.LabelFrame(master, label="Image Size") imageSetup.pack(fill=Tk.X, ipadx=2, ipady=2) subframe = imageSetup.frame #subframe = Tk.Frame(imageSetup.frame) #subframe.pack(fill=Tk.BOTH, expand=1) # add in conversion factor for pixels and graphics screen from chimera import tkgui win = tkgui.app.graphics res = tkgui.getScreenMMWidth() / win.winfo_screenwidth() convert['pixels'] = mm2pt(res) self.matchAspect = Tk.BooleanVar(master) self.matchAspect.set(1) self.usePrint = Tk.BooleanVar(master) self.usePrint.set(preferences.get(IMAGE_SETUP, USE_PRINT_UNITS)) import itertools row = itertools.count() self.showUsePrint = Tk.Checkbutton(subframe, indicatoron=1, variable=self.usePrint, highlightthickness=0, text=USE_PRINT_UNITS, command=self._updateUsePrint) self.showUsePrint.grid(columnspan=2, row=row.next(), sticky=Tk.W) w, h = chimera.viewer.windowSize self.units = ImageUnitsOption(subframe, row.next(), UNITS, 'pixels', self.updateImageUnits) self.iWidth = FloatOption(subframe, row.next(), 'Image width', w, self.updateImageWidth, min=1e-10) self.iHeight = FloatOption(subframe, row.next(), 'Image height', h, self.updateImageHeight, min=1e-10) matchAspect = Tk.Checkbutton(subframe, indicatoron=1, variable=self.matchAspect, highlightthickness=0, text="Maintain current aspect ratio", command=self.updateMatchAspect) matchAspect.grid(columnspan=2, row=row.next(), sticky=Tk.W) self.grow = Tk.Button(imageSetup.frame, text="Grow to Fit", command=self.Resize, state=Tk.DISABLED) fitrow = row.next() self.grow.grid(row=fitrow, column=0, padx=2, pady=2, sticky=Tk.NSEW) self.shrink = Tk.Button(imageSetup.frame, text="Shrink to Fit", command=lambda f=self.Resize: f(False), state=Tk.DISABLED) self.shrink.grid(row=fitrow, column=1, padx=2, pady=2, sticky=Tk.NSEW) #fetch = Tk.Button(imageSetup.frame, text="Get Pixels", # command=self.fetchWindowSize) #fetch.grid(row=row.next(), column=0, padx=2, pady=2, sticky=Tk.NSEW) #calc = Tk.Button(imageSetup.frame, text="Image Setup", # command=self.showImageSetupDialog) #calc.grid(row=row.next(), column=1, padx=2, pady=2, sticky=Tk.NSEW) self.printRes = FloatOption(subframe, row.next(), DPI, preferences.get(IMAGE_SETUP, DPI), self._updatePrint, min=1) # Image Information info = Tix.LabelFrame(master, label="Image Information") info.pack(fill=Tk.X) d = Tk.Label(info.frame, text="Description:") d.grid(columnspan=2, row=0, column=0, sticky=Tk.W, padx=2, pady=1) self.description = Tk.Entry(info.frame) info.frame.grid_columnconfigure(0, weight=1) info.frame.grid_columnconfigure(1, weight=1) self.description.grid(columnspan=2, row=1, column=0, sticky=Tk.EW, padx=2, pady=2) imageCredits = Tk.Button(info.frame, text="Image Credits", command=self.showImageCreditsDialog) imageCredits.grid(row=2, column=0, padx=2, pady=2) credit = Tk.Button(info.frame, text="Citing Chimera", command=lambda: help.display("credits.html")) credit.grid(row=2, column=1, padx=2, pady=2) # Image camera self.raytrace = BooleanOption(master, -1, 'Raytrace with POV-Ray', False, self._updateRaytrace) self.raytraceOptions = Tk.Button(master, text=POVRAY_SETUP, command=self.showPOVRayOptions) self.raytraceOptions.pack() self.raytraceOptions.pack_forget() self.supersample = SupersampleOption(master, -1, SUPERSAMPLE, preferences.get(IMAGE_SETUP, SUPERSAMPLE), self._updateSS) self.adjustFOV = AdjustFOVOption(master, -1, ADJUST_FOV, preferences.get(IMAGE_SETUP, ADJUST_FOV), self._updateAdjustFOV) self.printMode = _PrintModeOption(master, -1, 'Image camera mode', _PrintModeOption.SAME, self._updatePrintMode) self.lenticular = IntOption(master, -1, 'Number of lenticular images', chimera.Camera.lenticularImageCount(), self._updateLenticular, min=2, width=4) self.lenticular.forget() # switch to user's prefered units self.adjust = convert['pixels'] units = preferences.get(IMAGE_SETUP, UNITS) self._updateUsePrint() self.units.set(units) self.updateImageUnits()
def fillInUI(self, parent): import Pmw, Tkinter self.buttonWidgets['OK']['state'] = 'disabled' self.buttonWidgets['Apply']['state'] = 'disabled' from chimera.widgets import ModelScrolledListBox self.surfListBox = ModelScrolledListBox( parent, labelpos='n', label_text='Surfaces to color by ESP:', listbox_selectmode="extended", filtFunc=lambda m: isinstance(m, chimera.MSMSModel), selectioncommand=self._selSurfCB) self.surfListBox.grid(row=0, column=0, sticky="nsew", columnspan=2) Pmw.OptionMenu(parent, command=self._menuCB, initialitem="3", items=[str(x) for x in range(2, 12)], labelpos='w', label_text="Number of colors/values:").grid( row=1, column=0, columnspan=2) f = self.interpFrame = Tkinter.Frame(parent) f.grid(row=2, column=0, columnspan=2) self.wells = [] self.values = [] self._entryOpts = { 'validate': 'real', 'entry_justify': 'center', 'entry_width': 6 } from CGLtk.color.ColorWell import ColorWell for color, value in [("red", -10), ("white", 0), ("blue", 10)]: well = ColorWell(f, color=color) well.grid(row=0, column=len(self.wells)) self.wells.append(well) entry = Pmw.EntryField(f, value=str(value), **self._entryOpts) entry.grid(row=1, column=len(self.values)) self.values.append(entry) from chimera.tkoptions import FloatOption, BooleanOption self.distDep = BooleanOption( parent, 3, "Distance-dependent dielectric", True, None, balloon="If true, charge falls off with distance squared to\n" "simulate solvent screening effects") self.dielectric = FloatOption(parent, 4, "Dielectric constant", 4.0, None) self.surfDist = FloatOption(parent, 5, "Distance from surface", 1.4, None, balloon="Potential at this distance from\n" "the surface is used for coloring") self.hisGroup = Pmw.Group(parent, hull_padx=2, tag_text="Implicit Histidine Protonation") self.hisGroup.grid(row=6, column=0, columnspan=2, sticky="nsew") self.hisProtVar = Tkinter.StringVar(parent) self.hisProtVar.set("name") interior = self.hisGroup.interior() interior.columnconfigure(0, weight=1) lab = Tkinter.Label( interior, text="Assumed histidine " "protonation for\nstructures without explicit hydrogens") from tkFont import Font font = Font(font=lab.cget('font')) font.config(size=int(0.75 * float(font.cget('size'))), slant='italic') lab.config(font=font) lab.grid(row=0) Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="name", text="Residue name-based", command=self._switchHisList).grid(row=1, sticky='w') f = Tkinter.Frame(interior) f.grid(row=2) Tkinter.Label(f, text="HID/HIE/HIP = delta/epsilon/both").grid(row=0, sticky='w') self.hisDefault = Pmw.OptionMenu( f, initialitem=self.HB, items=[self.HB, "delta", "epsilon", "both"], labelpos='w', label_text="HIS = ", command=lambda a, s=self: setattr(s, 'hisChanged', True)) self.hisDefault.grid(row=1, sticky='w') self._pickText = Tkinter.StringVar(parent) self._pickText.set("Specified individually...") Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="pick", textvariable=self._pickText, command=self._switchHisList).grid(row=3, sticky='w') Tkinter.Button(parent, pady=0, command=self._colorKeyCB, text="Create corresponding color key").grid( row=7, column=0, columnspan=2) self.hisChanged = False
class EspDialog(ModelessDialog): title = "Coulombic Surface Coloring" name = "ESP computation" help = "ContributedSoftware/coulombic/coulombic.html" HB = "estimated from H-bonds" def fillInUI(self, parent): import Pmw, Tkinter self.buttonWidgets['OK']['state'] = 'disabled' self.buttonWidgets['Apply']['state'] = 'disabled' from chimera.widgets import ModelScrolledListBox self.surfListBox = ModelScrolledListBox(parent, labelpos='n', label_text='Surfaces to color by ESP:', listbox_selectmode="extended", filtFunc=lambda m: isinstance(m, chimera.MSMSModel), selectioncommand=self._selSurfCB) self.surfListBox.grid(row=0, column=0, sticky="nsew", columnspan=2) Pmw.OptionMenu(parent, command=self._menuCB, initialitem="3", items=[str(x) for x in range(2, 12)], labelpos='w', label_text="Number of colors/values:").grid(row=1, column=0, columnspan=2) f = self.interpFrame = Tkinter.Frame(parent) f.grid(row=2, column=0, columnspan=2) self.wells = [] self.values = [] self._entryOpts = { 'validate': 'real', 'entry_justify': 'center', 'entry_width': 6 } from CGLtk.color.ColorWell import ColorWell for color, value in [("red", -10), ("white", 0), ("blue", 10)]: well = ColorWell(f, color=color) well.grid(row=0, column=len(self.wells)) self.wells.append(well) entry = Pmw.EntryField(f, value=str(value), **self._entryOpts) entry.grid(row=1, column=len(self.values)) self.values.append(entry) from chimera.tkoptions import FloatOption, BooleanOption self.distDep = BooleanOption(parent, 3, "Distance-dependent dielectric", True, None, balloon= "If true, charge falls off with distance squared to\n" "simulate solvent screening effects") self.dielectric = FloatOption(parent, 4, "Dielectric constant", 4.0, None) self.surfDist = FloatOption(parent, 5, "Distance from surface", 1.4, None, balloon="Potential at this distance from\n" "the surface is used for coloring") self.hisGroup = Pmw.Group(parent, hull_padx=2, tag_text="Implicit Histidine Protonation") self.hisGroup.grid(row=6, column=0, columnspan=2, sticky="nsew") self.hisProtVar = Tkinter.StringVar(parent) self.hisProtVar.set("name") interior = self.hisGroup.interior() interior.columnconfigure(0, weight=1) lab = Tkinter.Label(interior, text="Assumed histidine " "protonation for\nstructures without explicit hydrogens") from tkFont import Font font = Font(font=lab.cget('font')) font.config(size=int(0.75 * float(font.cget('size'))), slant='italic') lab.config(font=font) lab.grid(row=0) Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="name", text="Residue name-based", command= self._switchHisList).grid(row=1, sticky='w') f = Tkinter.Frame(interior) f.grid(row=2) Tkinter.Label(f, text="HID/HIE/HIP = delta/epsilon/both").grid( row=0, sticky='w') self.hisDefault = Pmw.OptionMenu(f, initialitem=self.HB, items=[self.HB, "delta", "epsilon", "both"], labelpos='w', label_text="HIS = ", command=lambda a, s=self: setattr(s, 'hisChanged', True)) self.hisDefault.grid(row=1, sticky='w') self._pickText = Tkinter.StringVar(parent) self._pickText.set("Specified individually...") Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="pick", textvariable=self._pickText, command=self._switchHisList).grid(row=3, sticky='w') Tkinter.Button(parent, pady=0, command=self._colorKeyCB, text="Create corresponding color key").grid(row=7, column=0, columnspan=2) self.hisChanged = False def Apply(self): for entry in self.values: entry.invoke() colors = [w.rgba for w in self.wells] values = [float(e.getvalue()) for e in self.values] if self.hisProtVar.get() == "name": hisScheme = { self.HB: None, 'delta': 'HID', 'epsilon': 'HIE', 'both': 'HIP' }[self.hisDefault.getvalue()] else: hisScheme = self.hisListingData from ESP import colorEsp for surf in self.surfListBox.getvalue(): if self.hisChanged: # clear out charge values so that histidines # get new charges for a in surf.atoms: a.charge = None colorEsp(surf, colors, values, dielectric=self.dielectric.get(), distDep=self.distDep.get(), surfDist=self.surfDist.get(), hisScheme=hisScheme) self.hisChanged = False def _colorKeyCB(self): for entry in self.values: entry.invoke() from Ilabel.gui import IlabelDialog from chimera import dialogs d = dialogs.display(IlabelDialog.name) d.keyConfigure(zip([w.rgba for w in self.wells], [e.getvalue() for e in self.values])) def _menuCB(self, val): newNum = int(val) oldSettings = [] for well, entry in zip(self.wells, self.values): entry.invoke() oldSettings.append((well.rgba, float(entry.getvalue()))) well.grid_forget() well.destroy() entry.grid_forget() entry.destroy() import Pmw from CGLtk.color.ColorWell import ColorWell self.wells = [] self.values = [] scale = (len(oldSettings) - 1.0) / (newNum - 1.0) f = self.interpFrame for i in range(newNum): index = i * scale if index == int(index) \ or int(index) >= len(oldSettings): color, value = oldSettings[int(index)] else: lowc, lowv = oldSettings[int(index)] highc, highv = oldSettings[int(index)+1] frac = index - int(index) color = [] for lowcomp, highcomp in zip(lowc, highc): color.append((1.0 - frac) * lowcomp + frac * highcomp) value = (1.0 - frac) * lowv + frac * highv well = ColorWell(f, color=color) well.grid(row=0, column=len(self.wells)) self.wells.append(well) entry = Pmw.EntryField(f, value=str(value), **self._entryOpts) entry.grid(row=1, column=len(self.values)) self.values.append(entry) def _selSurfCB(self): if self.surfListBox.getvalue(): state = 'normal' else: state = 'disabled' self.buttonWidgets['OK']['state'] = state self.buttonWidgets['Apply']['state'] = state self._updateHisListing() def _select(self, hisType): for r, vars in self._vars.items(): dv, ev = vars if hisType == "delta": dv.set(True) ev.set(False) self.hisListingData[r] = "HID" elif hisType == "epsilon": dv.set(False) ev.set(True) self.hisListingData[r] = "HIE" else: dv.set(True) ev.set(True) self.hisListingData[r] = "HIP" def _switchHisList(self): self.hisChanged = True if not hasattr(self, 'hisListing'): if self.hisProtVar.get() != "pick": return self.hisListingData = {} import Tix, Tkinter self.hisFrame = Tkinter.Frame(self.hisGroup.interior()) self.hisListing = Tix.ScrolledHList(self.hisFrame, width="3i", options="""hlist.columns 4 hlist.header 1 hlist.indicator 1""") self.hisListing.hlist.configure( selectbackground=self.hisListing['background'], selectborderwidth=0) self.hisListing.grid(row=0, column=0, columnspan=3, sticky="nsew") self.hisFrame.rowconfigure(1, weight=1) self.hisFrame.columnconfigure(0, weight=1) self.hisFrame.columnconfigure(1, weight=1) hlist = self.hisListing.hlist hlist.header_create(0, itemtype="text", text="Model") hlist.header_create(1, itemtype="text", text="Residue") hlist.header_create(2, itemtype="text", text="Delta") hlist.header_create(3, itemtype="text", text="Epsilon") self._checkButtonStyle = Tix.DisplayStyle("window", background=hlist['background'], refwindow=self.hisListing, anchor='center') self._updateHisListing() Tkinter.Button(self.hisFrame, text="All Delta", pady=0, highlightthickness=0, command=lambda p="delta": self._select(p) ).grid(row=1, column=0) Tkinter.Button(self.hisFrame, text="All Epsilon", pady=0, highlightthickness=0, command=lambda p="epsilon": self._select(p) ).grid(row=1, column=1) Tkinter.Button(self.hisFrame, text="All Both", pady=0, highlightthickness=0, command=lambda p="both": self._select(p) ).grid(row=1, column=2) if self.hisProtVar.get() == "pick": self._pickText.set("Specified individually:") self.hisFrame.grid(row=4, sticky="nsew") interior = self.hisGroup.interior() interior.rowconfigure(4, weight=1) self.uiMaster().rowconfigure(6, weight=4) else: self._pickText.set("Specified individually...") self.hisFrame.grid_forget() interior = self.hisGroup.interior() interior.rowconfigure(4, weight=0) self.uiMaster().rowconfigure(6, weight=0) def _toggleDelta(self, res): self.hisChanged = True old = self.hisListingData[res] if old == "HIS": new = "HID" elif old == "HID": new = "HIS" elif old == "HIE": new = "HIP" else: new = "HIE" self.hisListingData[res] = new def _toggleEpsilon(self, res): self.hisChanged = True old = self.hisListingData[res] if old == "HIS": new = "HIE" elif old == "HID": new = "HIP" elif old == "HIE": new = "HIS" else: new = "HID" self.hisListingData[res] = new def _updateHisListing(self): if not hasattr(self, 'hisListing'): return self._updateHisListingData() hlist = self.hisListing.hlist on = self.hisListing.tk.call('tix', 'getimage', 'ck_on') off = self.hisListing.tk.call('tix', 'getimage', 'ck_off') hlist.delete_all() import Tkinter row = 0 self._vars = {} for m in [s.molecule for s in self.surfListBox.getvalue()]: for r in m.residues: try: hisType = self.hisListingData[r] except KeyError: continue hlist.add(row, itemtype="text", text="%s (%s)" % (m.name, m.oslIdent())) hlist.item_create(row, 1, itemtype="text", text=r.oslIdent( start=chimera.SelResidue)) var = Tkinter.IntVar(hlist) var.set(hisType in ["HID", "HIP"]) cmd = lambda r=r: self._toggleDelta(r) self._vars[r] = [var] toggle = Tkinter.Checkbutton(hlist, command=cmd, variable=var, image=off, selectimage=on, selectcolor="", indicatoron=False, borderwidth=0) hlist.item_create(row, 2, itemtype="window", window=toggle, style=self._checkButtonStyle) var = Tkinter.IntVar(hlist) var.set(hisType in ["HIE", "HIP"]) cmd = lambda r=r: self._toggleEpsilon(r) self._vars[r].append(var) toggle = Tkinter.Checkbutton(hlist, command=cmd, variable=var, image=off, selectimage=on, selectcolor="", indicatoron=False, borderwidth=0) hlist.item_create(row, 3, itemtype="window", window=toggle, style=self._checkButtonStyle) row += 1 def _updateHisListingData(self): newData = {} default = { 'delta': 'HID', 'epsilon': 'HIE', 'both': 'HIP', self.HB: 'HID' }[self.hisDefault.getvalue()] for m in [s.molecule for s in self.surfListBox.getvalue()]: for r in m.residues: if r.type not in ["HIS", "HIE", "HIP", "HID"]: continue try: newData[r] = self.hisListingData[r] except KeyError: if r.type == 'HIS': newData[r] = default else: newData[r] = r.type self.hisListingData = newData
class VolumeDialog(ModelessDialog): title = "Calculate Atomic Occupancy" help = "ContributedSoftware/movie/movie.html#occupancy" provideStatus = True statusPosition = "left" buttons = ('OK', 'Close') default = 'OK' def __init__(self, movie): self.movie = movie movie.subdialogs.append(self) ModelessDialog.__init__(self) def map(self, e=None): if not self.movie.holdingSteady: self.status("No atoms being held steady -- see Help", color="red") def fillInUI(self, parent): Tkinter.Label(parent, text="Collect positions of selected" " atoms over trajectory", relief="ridge", bd=4).grid(row=0, column=0, columnspan=2, sticky="ew") startFrame = self.movie.startFrame endFrame = self.movie.endFrame from chimera.tkoptions import IntOption, BooleanOption, \ FloatOption, StringOption self.startFrame = IntOption(parent, 1, "Starting frame", startFrame, None, min=startFrame, max=endFrame, width=6) numFrames = endFrame - startFrame + 1 defStride = 1 + int(numFrames / 300) self.stride = IntOption(parent, 2, "Step size", defStride, None, min=1, max=numFrames, width=3) self.endFrame = IntOption(parent, 3, "Ending frame", endFrame, None, min=startFrame, max=endFrame, width=6) self.doCutoff = BooleanOption( parent, 4, 'Limit data collection' ' to within cutoff distance of any "held steady" atoms', True, None) self.cutoff = FloatOption(parent, 5, "Cutoff distance", prefs[VOLUME_CUTOFF], None, width=4) self.resolution = FloatOption(parent, 6, "Volume grid spacing", prefs[VOLUME_RESOLUTION], None, min=0.0001, width=4) self.volumeName = StringOption(parent, 7, "Volume data name", self.movie.ensemble.name, None, width=20) self.byAtomType = BooleanOption( parent, 8, "Collect data" " separately for each atom type in selection", True, None, balloon="Create a volume data set for" " each type of atom type\n(sp2 oxygen, aromatic carbon," " etc.) in current selection") def Apply(self): from chimera import UserError atoms = chimera.selection.currentAtoms() if not atoms: self.enter() raise UserError("No atoms selected") startFrame = self.startFrame.get() endFrame = self.endFrame.get() if endFrame <= startFrame: self.enter() raise UserError("Start frame must be less" " than end frame") if startFrame < self.movie.startFrame \ or endFrame > self.movie.endFrame: self.enter() raise UserError("Start or end frame outside" " of trajectory") if self.doCutoff.get(): bound = prefs[VOLUME_CUTOFF] = self.cutoff.get() else: bound = None prefs[VOLUME_RESOLUTION] = self.resolution.get() step = self.stride.get() spacing = self.resolution.get() name = self.volumeName.get() atomTypes = {} if self.byAtomType.get(): for a in atoms: atomTypes.setdefault(a.idatmType, []).append(a) if len(atomTypes) > 1: for atomType, atAtoms in atomTypes.items(): self.movie.computeVolume(atAtoms, startFrame=startFrame, endFrame=endFrame, step=step, bound=bound, spacing=spacing, volumeName=name + " [" + atomType + "]") else: self.movie.computeVolume(atoms, startFrame=startFrame, endFrame=endFrame, step=step, bound=bound, spacing=spacing, volumeName=name)
def fillInUI(self, parent): import Pmw, Tkinter self.buttonWidgets['OK']['state'] = 'disabled' self.buttonWidgets['Apply']['state'] = 'disabled' from chimera.widgets import ModelScrolledListBox self.surfListBox = ModelScrolledListBox(parent, labelpos='n', label_text='Surfaces to color by ESP:', listbox_selectmode="extended", filtFunc=lambda m: isinstance(m, chimera.MSMSModel), selectioncommand=self._selSurfCB) self.surfListBox.grid(row=0, column=0, sticky="nsew", columnspan=2) Pmw.OptionMenu(parent, command=self._menuCB, initialitem="3", items=[str(x) for x in range(2, 12)], labelpos='w', label_text="Number of colors/values:").grid(row=1, column=0, columnspan=2) f = self.interpFrame = Tkinter.Frame(parent) f.grid(row=2, column=0, columnspan=2) self.wells = [] self.values = [] self._entryOpts = { 'validate': 'real', 'entry_justify': 'center', 'entry_width': 6 } from CGLtk.color.ColorWell import ColorWell for color, value in [("red", -10), ("white", 0), ("blue", 10)]: well = ColorWell(f, color=color) well.grid(row=0, column=len(self.wells)) self.wells.append(well) entry = Pmw.EntryField(f, value=str(value), **self._entryOpts) entry.grid(row=1, column=len(self.values)) self.values.append(entry) from chimera.tkoptions import FloatOption, BooleanOption self.distDep = BooleanOption(parent, 3, "Distance-dependent dielectric", True, None, balloon= "If true, charge falls off with distance squared to\n" "simulate solvent screening effects") self.dielectric = FloatOption(parent, 4, "Dielectric constant", 4.0, None) self.surfDist = FloatOption(parent, 5, "Distance from surface", 1.4, None, balloon="Potential at this distance from\n" "the surface is used for coloring") self.hisGroup = Pmw.Group(parent, hull_padx=2, tag_text="Implicit Histidine Protonation") self.hisGroup.grid(row=6, column=0, columnspan=2, sticky="nsew") self.hisProtVar = Tkinter.StringVar(parent) self.hisProtVar.set("name") interior = self.hisGroup.interior() interior.columnconfigure(0, weight=1) lab = Tkinter.Label(interior, text="Assumed histidine " "protonation for\nstructures without explicit hydrogens") from tkFont import Font font = Font(font=lab.cget('font')) font.config(size=int(0.75 * float(font.cget('size'))), slant='italic') lab.config(font=font) lab.grid(row=0) Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="name", text="Residue name-based", command= self._switchHisList).grid(row=1, sticky='w') f = Tkinter.Frame(interior) f.grid(row=2) Tkinter.Label(f, text="HID/HIE/HIP = delta/epsilon/both").grid( row=0, sticky='w') self.hisDefault = Pmw.OptionMenu(f, initialitem=self.HB, items=[self.HB, "delta", "epsilon", "both"], labelpos='w', label_text="HIS = ", command=lambda a, s=self: setattr(s, 'hisChanged', True)) self.hisDefault.grid(row=1, sticky='w') self._pickText = Tkinter.StringVar(parent) self._pickText.set("Specified individually...") Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="pick", textvariable=self._pickText, command=self._switchHisList).grid(row=3, sticky='w') Tkinter.Button(parent, pady=0, command=self._colorKeyCB, text="Create corresponding color key").grid(row=7, column=0, columnspan=2) self.hisChanged = False
def fillInUI(self, parent): import Pmw, Tkinter top = parent.winfo_toplevel() menubar = Tkinter.Menu(top, type="menubar", tearoff=False) top.config(menu=menubar) self.presetsMenu = Tkinter.Menu(menubar) menubar.add_cascade(label="Presets", menu=self.presetsMenu) presets = self.builtinPresets + prefs[PRESETS] for label, kw in presets: self.presetsMenu.add_command( label=label, command=lambda kw=kw: self.preset(**kw)) self.presetsMenu.add_separator() self.presetsMenu.add_command(label="Preset from current settings...", command=self.startDefinePreset) self.presetsMenu.add_command(label="Delete user preset...", command=self.startDeletePreset) from chimera.tkgui import aquaMenuBar row = aquaMenuBar(menubar, parent, row=0, columnspan=2) parent.columnconfigure(0, weight=1) parent.columnconfigure(1, weight=1) self._modFromCalc = False self.scaling = Pmw.EntryField(parent, labelpos='w', value='1', label_text="Scale factor:", entry_width=5, validate={ 'validator': 'real', 'min': 0.0 }, modifiedcommand=self._scaleTypingCB, command=self.ShowEllipsoids) self.scaling.grid(row=row, column=0) self.smoothing = Pmw.EntryField(parent, labelpos='w', label_text="Smoothing level:", validate={ 'validator': 'numeric', 'min': 1, 'max': 100 }, value='3', entry_width=2, command=self.ShowEllipsoids) self.smoothing.grid(row=row, column=1) row += 1 self.calculator = Pmw.EntryField( parent, labelpos='w', label_text="Set scale factor for probability (%):", entry_width=4, command=self._prob2scaling) self.calculator.grid(row=row, column=0, columnspan=2) row += 1 from chimera.tkoptions import SymbolicEnumOption, \ FloatOption, RGBAOption self.showEllipsoidVar = Tkinter.IntVar(parent) self.showEllipsoidVar.set(True) ellipsoidGroup = Pmw.Group(parent, tag_pyclass=Tkinter.Checkbutton, tag_text="Depict ellipsoids", tag_variable=self.showEllipsoidVar) ellipsoidGroup.grid(row=row, column=0, columnspan=2, sticky="ew") row += 1 inside = ellipsoidGroup.interior() inside.columnconfigure(0, weight=1, uniform=1) inside.columnconfigure(1, weight=1, uniform=1) self.ellipsoidColorOpt = RGBAOption( inside, 0, 'Color', None, None, noneOkay=True, balloon='"No color" means use atom colors') class TransparencyOption(SymbolicEnumOption): values = [ None, 0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0 ] labels = [ "same as color", "0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%" ] self.transparencyOpt = TransparencyOption(inside, 1, "Transparency", None, None) self.showAxesVar = Tkinter.IntVar(parent) self.showAxesVar.set(False) axesGroup = Pmw.Group(parent, tag_pyclass=Tkinter.Checkbutton, tag_text="Depict principal axes", tag_variable=self.showAxesVar) axesGroup.grid(row=row, column=0, columnspan=2, sticky="ew") row += 1 inside = axesGroup.interior() inside.columnconfigure(0, weight=1, uniform=1) inside.columnconfigure(1, weight=1, uniform=1) self.axisColorOpt = RGBAOption( inside, 0, 'Color', None, None, noneOkay=True, balloon='"No color" means use atom colors') self.axisFactorOpt = FloatOption(inside, 1, "Length factor", 1.5, self.ShowEllipsoids, balloon="relative to ellipsoids", sticky="w") self.axisThicknessOpt = FloatOption(inside, 2, "Thickness", 0.01, self.ShowEllipsoids, sticky="w") self.showEllipsesVar = Tkinter.IntVar(parent) self.showEllipsesVar.set(False) ellipsesGroup = Pmw.Group(parent, tag_pyclass=Tkinter.Checkbutton, tag_text="Depict principal ellipses", tag_variable=self.showEllipsesVar) ellipsesGroup.grid(row=row, column=0, columnspan=2, sticky="ew") row += 1 inside = ellipsesGroup.interior() inside.columnconfigure(0, weight=1, uniform=1) inside.columnconfigure(1, weight=1, uniform=1) self.ellipseColorOpt = RGBAOption( inside, 0, 'Color', None, None, noneOkay=True, balloon='"No color" means use atom colors') self.ellipseFactorOpt = FloatOption(inside, 1, "Size factor", 1.0, self.ShowEllipsoids, balloon="relative to ellipsoids", sticky="w") self.ellipseThicknessOpt = FloatOption(inside, 2, "Thickness", 0.02, self.ShowEllipsoids, sticky="w") self.selRestrictVar = Tkinter.IntVar(parent) self.selRestrictVar.set(False) Tkinter.Checkbutton(parent, text="Restrict Show/Hide to current" " selection, if any", variable=self.selRestrictVar).grid(row=row, column=0, columnspan=2) row += 1
class RmsdStarter(ModelessDialog): title = "Get RMSD Map Parameters" help = "ContributedSoftware/movie/movie.html#rmsd" def __init__(self, movie): self.movie = movie movie.subdialogs.append(self) ModelessDialog.__init__(self) def fillInUI(self, parent): from chimera.tkoptions import IntOption, BooleanOption, \ FloatOption Tkinter.Label(parent, text="Create RMSD map of trajectory " "against itself", relief="ridge", bd=4).grid(row=0, column=0, columnspan=2, sticky="ew") startFrame = self.movie.startFrame endFrame = self.movie.endFrame self.startFrame = IntOption(parent, 1, "Starting frame", startFrame, None, min=startFrame, max=endFrame, width=6) numFrames = endFrame - startFrame + 1 defStride = 1 + int(numFrames/300) self.stride = IntOption(parent, 2, "Step size", defStride, None, min=1, max=numFrames, width=3) self.endFrame = IntOption(parent, 3, "Ending frame", endFrame, None, min=startFrame, max=endFrame, width=6) self.minRmsd = FloatOption(parent, 4, "Lower RMSD threshold" " (white)", prefs[RMSD_MIN], None, width=6) self.maxRmsd = FloatOption(parent, 5, "Upper RMSD threshold" " (black)", prefs[RMSD_MAX], None, width=6) self.useSel = BooleanOption(parent, 6, "Restrict map to " "current selection, if any", True, None) self.ignoreBulk = BooleanOption(parent, 7, "Ignore solvent/" "ions", True, None) self.ignoreHyds = BooleanOption(parent, 8, "Ignore hydrogens", True, None) self.recolor = BooleanOption(parent, 9, "Auto-recolor for" " contrast", prefs[RMSD_AUTOCOLOR], None) def Apply(self): startFrame = self.startFrame.get() stride = self.stride.get() if (len(self.movie.ensemble) - (startFrame-1)) / stride > 1000: dlg = AskYesNoDialog("RMSD map will be %d pixels wide" " and tall. Okay?") if dlg.run(self.uiMaster()) == "no": self.enter() return endFrame = self.endFrame.get() if endFrame <= startFrame: self.enter() raise UserError("Start frame must be less" " than end frame") if startFrame < self.movie.startFrame \ or endFrame > self.movie.endFrame: self.enter() raise UserError("Start or end frame outside" " of trajectory") prefs[RMSD_MIN] = self.minRmsd.get() prefs[RMSD_MAX] = self.maxRmsd.get() prefs[RMSD_AUTOCOLOR] = self.recolor.get() RmsdMapDialog(self.movie, startFrame, self.stride.get(), endFrame, self.useSel.get(), prefs[RMSD_MIN], prefs[RMSD_MAX], self.ignoreBulk.get(), self.ignoreHyds.get(), prefs[RMSD_AUTOCOLOR])