def fillInUI(self, parent): self.info = [ ("Helix", HELIX_COLOR, 'isHelix'), ("Strand", SHEET_COLOR, 'isSheet'), ("Other", OTHER_COLOR, None) ] header = Tkinter.Frame(parent) header.grid(row=0, column=0, sticky="nsew") parent.rowconfigure(0, weight=1) for i in range(len(self.info)): parent.columnconfigure(i, weight=1) from chimera.widgets import MoleculeScrolledListBox self.molListBox = MoleculeScrolledListBox(header, selectioncommand=lambda: self.configure( models=self.molListBox.getvalue()), listbox_selectmode="extended", labelpos="nw", label_text="Models") self.molListBox.grid(row=0, column=0, rowspan=len(self.info), sticky="nsew") for i in range(3): header.rowconfigure(i, weight=1) header.columnconfigure(0, weight=1) self.colorRibVar = Tkinter.IntVar(parent) self.colorRibVar.set(True) self.colorAtomVar = Tkinter.IntVar(parent) self.colorAtomVar.set(False) self.colorSurfVar = Tkinter.IntVar(parent) self.colorSurfVar.set(False) varFrame = Tkinter.Frame(parent) varFrame.grid(row=1, column=0) for i, info in enumerate([(self.colorRibVar, "Color ribbons"), (self.colorAtomVar, "Color atoms"), (self.colorSurfVar, "Color surfaces")]): var, text = info but = Tkinter.Checkbutton(varFrame, variable=var, text=text) but.grid(row=i, column=0, sticky='w') self.wells = [] self.actVars = [] from CGLtk.color.ColorWell import ColorWell from chimera.colorTable import getColorByName for row, ssInfo in enumerate(self.info): ssType, prefName, attrName = ssInfo rgba = prefs[prefName] if isinstance(rgba, basestring): rgba = getColorByName(rgba).rgba() well = ColorWell(header, color=rgba, noneOkay=True) self.wells.append(well) well.grid(row=row, column=2) actVar = Tkinter.IntVar(parent) actVar.set(True) self.actVars.append(actVar) Tkinter.Checkbutton(header, variable=actVar, text=ssType).grid(row=row, column=1, sticky='w')
class mmmdDialog(ModelessDialog): name = "Minimize Structure" help = "ContributedSoftware/minimize/minimize.html" buttons = ("Minimize", "Close") keepShown = "Minimize" def fillInUI(self, parent): import Tkinter from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(parent, listbox_selectmode="extended") self.molList.pack(expand=True, fill="both") self.minimizeOptions = MinimizeOptions(parent) self.minimizeOptions.pack(expand=False, fill="both") def Apply(self): molecules = self.molList.getvalue() if not molecules: from chimera import UserError raise UserError("Please select a molecule to minimize") import base base.Minimizer(molecules, callback=self.run) def run(self, minimizer): self.minimizeOptions.setOptions(minimizer) minimizer.run() def Dynamics(self): raise chimera.LimitationError("MD is unimplemented")
def fillInUI(self, parent): self.parent = parent Tkinter.Label(parent, text="Change color every:").grid( row=0, rowspan=3, column=0, sticky='w') self.colorChangeVar = Tkinter.StringVar(parent) self.colorChangeVar.set("residues") Tkinter.Radiobutton(parent, text='residue', value='residues', variable=self.colorChangeVar).grid( row=0, column=1, sticky='w') Tkinter.Radiobutton(parent, text='chain', value='chains', variable=self.colorChangeVar).grid( row=1, column=1, sticky='w') Tkinter.Radiobutton(parent, text='model', value='models', variable=self.colorChangeVar).grid( row=2, column=1, sticky='w') group = Pmw.Group(parent, tag_text='Color range') group.grid(row=3, column=0, columnspan=2) self.wells = [] for i, color in enumerate(self.prefs["colors"]): well = ColorWell(group.interior(), color=color, noneOkay=1) well.grid(row=0, column=i) self.wells.append(well) from chimera.widgets import MoleculeScrolledListBox self.molListBox = MoleculeScrolledListBox(parent, listbox_selectmode="extended", labelpos="n", label_text="Models") self.molListBox.grid(row=0, column=2, rowspan=4, sticky="news") parent.rowconfigure(0, weight=1) parent.columnconfigure(2, weight=1)
def fillInUI(self, parent): import Pmw, Tkinter from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox( parent, labelpos='w', label_text="Add hydrogens to:", listbox_selectmode='extended', selectioncommand=self._updateHisListing) if self.startModels: self.molList.setvalue(self.startModels) self.molList.grid(row=0, column=0, sticky="news") parent.columnconfigure(0, weight=1) parent.rowconfigure(0, weight=1) grp = Pmw.Group(parent, tag_text="Method", hull_padx=2) grp.grid(row=1, column=0, sticky="ew") self.useHBondsVar = Tkinter.IntVar(parent) self.useHBondsVar.set(self.startUseHBonds) Tkinter.Radiobutton(grp.interior(), variable=self.useHBondsVar, value=False, text="steric only").grid(row=0, sticky='w') Tkinter.Radiobutton(grp.interior(), variable=self.useHBondsVar, value=True, text="also consider H-bonds (slower)").grid( row=1, sticky='w') self.hisGroup = Pmw.Group(parent, hull_padx=2, tag_text="Histidine Protonation") self.hisGroup.grid(row=2, column=0, sticky="nsew") self.hisProtVar = Tkinter.StringVar(parent) self.hisProtVar.set("name") interior = self.hisGroup.interior() Tkinter.Radiobutton( interior, variable=self.hisProtVar, value="name", text="Residue-name-based\n" "(HIS/HID/HIE/HIP = unspecified/delta/epsilon/both)", command=self._switchHisList, justify="left").grid(row=0, 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=1, sticky='w') Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="default", command=self._switchHisList, text="Unspecified (determined by method)").grid( row=3, sticky='w')
def fillInUI(self, parent): import Tkinter from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(parent, listbox_selectmode="extended") self.molList.pack(expand=True, fill="both") self.minimizeOptions = MinimizeOptions(parent) self.minimizeOptions.pack(expand=False, fill="both")
def fill_in_ui(self, parent): input_frame = tk.LabelFrame(self.canvas, text='Select a protein-ligand complex') self.ui_molecules = MoleculeScrolledListBox(input_frame) self.ui_molecules.filtFunc = lambda m: not m.name.startswith('PLIP-') self.ui_molecules.refresh() self.ui_molecules.pack(padx=5, pady=5, expand=True, fill='both') input_frame.pack(padx=5, pady=5, expand=True, fill='both')
class AddAttrDialog(OpenModeless): title = "Define Attribute" provideStatus = True name = "add/change attrs" help = "ContributedSoftware/defineattrib/defineattrib.html" def __init__(self): OpenModeless.__init__(self, clientPos='s', clientSticky='nsew', historyID="AddAttr") def Apply(self): mols = self.molListBox.getvalue() if not mols: self.enter() replyobj.error("No models chosen in dialog\n") return for path in self.getPaths(): setAttrs = addAttributes(path, models=mols, log=self.doLog.get(), raiseAttrDialog=self.openDialog.get()) if setAttrs == []: replyobj.error("No attributes were set from" " file %s\n" % path) def fillInUI(self, parent): OpenModeless.fillInUI(self, parent) from chimera.widgets import MoleculeScrolledListBox self.molListBox = MoleculeScrolledListBox(self.clientArea, listbox_selectmode="extended", labelpos="w", label_text="Restrict to models:") self.molListBox.grid(row=0, column=0, sticky="nsew") self.clientArea.rowconfigure(0, weight=1) self.clientArea.columnconfigure(0, weight=1) checkButtonFrame = Tkinter.Frame(self.clientArea) checkButtonFrame.grid(row=1, column=0) self.openDialog = Tkinter.IntVar(parent) self.openDialog.set(True) Tkinter.Checkbutton(checkButtonFrame, variable=self.openDialog, text="Open Render/Select by Attribute").grid( row=0, column=0, sticky='w') self.doLog = Tkinter.IntVar(parent) self.doLog.set(False) Tkinter.Checkbutton(checkButtonFrame, text="Send match info to Reply Log", variable=self.doLog).grid(row=1, column=0, sticky='w')
def fillInUI(self, parent): from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(parent, labelpos='w', listbox_selectmode="extended", label_text="Add ions : ") self.molList.grid(row=0, column=0, sticky="nsew") rcf1 = Tkinter.Frame(parent) rcf1.grid(row=2, column=0, sticky="nsew") from Addions import ValidIontypes self.iontype = "Cl-" self.iontypeOption = Pmw.OptionMenu(rcf1, label_text="Ion types:", labelpos='w', items=ValidIontypes, initialitem=self.iontype, command=self.changeIontype) self.iontypeOption.grid(row=0, column=0) rcf2 = Tkinter.Frame(parent) rcf2.grid(row=3, column=0) rcf2.columnconfigure(2, weight=1) self.numionOption = Pmw.RadioSelect(rcf2, buttontype='radiobutton', command=self.changeNumion, labelpos='w', label_text="# of ions:") self.numionOption.add("neutralize") self.numionOption.add("specific number:") self.numionOption.setvalue("neutralize") self.numionOption.grid(row=0, column=0) self.numion = "neutralize" self.numionValue = Hybrid.StringVariable(rcf2) self.numionEntry = Tkinter.Entry( rcf2, width=5, textvariable=self.numionValue.tk_variable, state='disabled') self.numionEntry.grid(row=0, column=1) parent.rowconfigure(0, weight=1) parent.columnconfigure(0, weight=1)
def fillInUI(self, parent): self.notebook = Pmw.NoteBook(parent) self.notebook.pack(fill="both", expand=True) page = self.notebook.add("Molecules") self.molChooser = MoleculeScrolledListBox(page, listbox_selectmode="extended", autoselect="single") self.molChooser.pack(fill="both", expand=True) page = self.notebook.add("Chains") self.chainChooser = MoleculeChainScrolledListBox(page, listbox_selectmode="extended", autoselect="single") self.chainChooser.pack(fill="both", expand=True) titles = self.Servers.keys() titles.sort() self.serverChooser = Pmw.OptionMenu(parent, labelpos="w", label_text="Compute:", items=titles, command=self._changeServer) self.serverChooser.pack(fill="x", expand=False) self.paramHolder = Tkinter.Frame(parent, padx=10, pady=2) self.paramHolder.pack(fill="x", expand=False) self.paramFrames = {} for name, val in self.Servers.iteritems(): self.paramFrames[name] = val[2](self, self.paramHolder) self.propertyName = Pmw.EntryField(parent, labelpos="w", label_text="As attribute:", value=self.Servers[titles[0]][0], validate=self._validatePropName) self.propertyName.pack(fill="x", expand=False) self.outputOptions = Pmw.RadioSelect(parent, pady=0, buttontype="checkbutton", orient="vertical") self.outputOptions.pack(fill="x", expand=False) self.outputOptions.add("rba", text="Open Render/Select by Attribute") self.outputOptions.add("save", text="Save server output to file") self.outputOptions.add("show", text="Show server output in browser") self.outputOptions.setvalue(["rba"]) self._changeServer(titles[0])
def fill_in_ui(self, parent): note_frame = tk.LabelFrame(self.canvas, text='How to run PoPMuSiC') tk.Label(note_frame, text="PoPMuSiC is a web service!\nYou must register " "and run the jobs from:").pack(padx=5, pady=5) self.ui_web_btn = tk.Button( note_frame, text="PoPMuSiC web interface", command=lambda *a: web.open_new(r"http://soft.dezyme.com/")) self.ui_web_btn.pack(padx=5, pady=5) input_frame = tk.LabelFrame( self.canvas, text='Select molecule and PoPMuSiC output files') input_frame.rowconfigure(0, weight=1) input_frame.columnconfigure(1, weight=1) self.ui_molecules = MoleculeScrolledListBox(input_frame) self.ui_molecules.grid(row=0, columnspan=3, padx=5, pady=5, sticky='news') entries = [('popfile', 'POP file', '.pop'), ('popsfile', 'POPS file', '.pops')] for i, (var, label, ext) in enumerate(entries): # Label tk.Label(input_frame, text=label).grid(row=i + 1, column=0, padx=3, pady=3, sticky='e') # Field entry stringvar = getattr(self, '_' + var) entry = tk.Entry(input_frame, textvariable=stringvar) entry.grid(row=i + 1, column=1, padx=3, pady=3, sticky='news') setattr(self, 'ui_' + var + '_entry', entry) # Button button = tk.Button( input_frame, text='...', command=lambda v=stringvar, e=ext: self._browse_cb(v, e)) button.grid(row=i + 1, column=2, padx=3, pady=3) setattr(self, 'ui_' + var + '_button', button) note_frame.pack(fill='x', padx=5, pady=5) input_frame.pack(expand=True, fill='both', padx=5, pady=5)
def fillInUI(self, parent): from chimera.widgets import MoleculeScrolledListBox self.molListBox = MoleculeScrolledListBox(parent, listbox_selectmode='extended', labelpos='w', label_text="Molecules to combine/copy:") if self.initModels: self.molListBox.setvalue(self.initModels) self.molListBox.grid(row=0, column=0, columnspan=2, sticky="nsew") parent.rowconfigure(0, weight=1) parent.columnconfigure(1, weight=1) from chimera.tkoptions import StringOption, IntOption self.molNameEntry = StringOption(parent, 1, "New model's" " name", "combination", None) curIDs = set([i1 for i1, i2 in openModels.listIds()]) mid = 0 while mid in curIDs: mid += 1 self.modelID = IntOption(parent, 2, "New model's ID", mid, None) from chimera.widgets import MoleculeOptionMenu self.refMolMenu = MoleculeOptionMenu(parent, labelpos='w', label_text="Coordinate system of:", initialitem=self.initModels[0]) self.refMolMenu.grid(row=3, column=0, columnspan=2, sticky='w') import Pmw chb = self.chainHandlingButtons = Pmw.RadioSelect(parent, buttontype="radiobutton", labelpos='w', label_text="If original molecules have duplicate\n" "single-letter chain IDs, then:", orient="vertical") self.buttonTexts = ["rename them uniquely", "retain them (residues may be renumbered)"] for bt in self.buttonTexts: chb.add(bt) chb.setvalue(self.buttonTexts[0]) chb.grid(row=4, column=0, columnspan=2) import Tkinter self.closeModelsVar = Tkinter.IntVar(parent) self.closeModelsVar.set(False) Tkinter.Checkbutton(parent, text="Close source models", variable=self.closeModelsVar).grid( row=5, column=0, columnspan=2)
def fillInUI(self, parent): from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(parent, labelpos='w', listbox_selectmode="extended", label_text='Add charges to:') if self.startModels: self.molList.setvalue(self.startModels) self.molList.grid(row=0, column=0, sticky="nsew") parent.rowconfigure(0, weight=1) parent.columnconfigure(0, weight=1) import Pmw from AddCharge import knownChargeModels, defaultChargeModel self.chargeModel = Pmw.OptionMenu(parent, labelpos='w', label_text="Standard residues:", items=knownChargeModels, initialitem=self.initialChargeModel) self.chargeModel.grid(row=1, column=0) self.chargeMethod = ChargeMethodOption(parent, label="Other residues:") self.chargeMethod.grid(row=2, column=0) import Tkinter labelFrame = Tkinter.Frame(parent) labelFrame.grid(row=3, column=0) Tkinter.Label(labelFrame, text="Add labels showing charges" " to atoms in:").grid(row=0, column=0, rowspan=2) self.labelNonstandardVar = Tkinter.IntVar(parent) self.labelNonstandardVar.set(False) Tkinter.Checkbutton(labelFrame, text="nonstandard residues", variable=self.labelNonstandardVar).grid(row=0, column=1, sticky='w') self.labelStandardVar = Tkinter.IntVar(parent) self.labelStandardVar.set(False) Tkinter.Checkbutton(labelFrame, text="standard residues", variable=self.labelStandardVar).grid(row=1, column=1, sticky='w')
class AttrFrame(Tkinter.Frame): def __init__(self, master, **kw): Tkinter.Frame.__init__(self, master, **kw) self.rgbaOpt = RGBAOption(self, 1, 'Color', prefs[COLOR], None, noneOkay=False) self.associateVar = Tkinter.IntVar(self) self.associateVar.set(0) Tkinter.Checkbutton(self, command=self.modelsActivity, text="Associate with...", variable=self.associateVar).grid(row=2, column=0, sticky='e') self.moleculeList = MoleculeScrolledListBox(self, autoselect='single', listbox_state='disabled') self.moleculeList.grid(row=2, column=1, sticky='w') def modelsActivity(self): if self.associateVar.get(): self.moleculeList.component('listbox').config(state='normal') else: self.moleculeList.component('listbox').config(state='disabled')
def fillInUI(self, parent): from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(parent, labelpos='w', listbox_selectmode="extended", label_text="Solvate: ") self.molList.grid(row=0, column=0, sticky="nsew") self.solvateMethod = Pmw.RadioSelect(parent, buttontype='radiobutton', command=self.changeMethod, labelpos='w', label_text="Solvate method:") self.solvateMethod.add("Box") self.solvateMethod.add("Cap") self.solvateMethod.add("Oct") self.solvateMethod.add("Shell") self.solvateMethod.setvalue("Box") self.solvateMethod.grid(row=1, column=0, sticky="nsew") self.method = "Box" rcf1 = Tkinter.Frame(parent) rcf1.grid(row=2, column=0, sticky="nsew") self.solvent = prefs[SOLVENT_MODEL] from Solvate import ValidSolventModels self.solventModel = Pmw.OptionMenu(rcf1, label_text= "Solvent Model:", labelpos = 'w', items=ValidSolventModels, initialitem=self.solvent, command=self.changeSolvent) self.solventModel.grid(row=0, column=0) rcf2 = Tkinter.Frame(rcf1) rcf2.grid(row=0, column=1) rcf1.columnconfigure(1, weight=1) self.extentLabel = Tkinter.Label(rcf2, text="Box size:" ) self.extentLabel.grid(row=0, column=0) self.extentValue = Hybrid.StringVariable(rcf2) ev = Tkinter.Entry( rcf2, width=5, textvariable=self.extentValue.tk_variable) ev.grid( row=0, column=1 ) rcf3 = Tkinter.Frame(parent) rcf3.grid(row=3, column=0) self.centerLabel = Tkinter.Label(rcf3, text="Cap center (in ambmask):", state='disabled' ) self.centerLabel.grid(row=0, column=0) self.centerValue = Hybrid.StringVariable(rcf3) self.centerEntry = Tkinter.Entry( rcf3, width=5, textvariable=self.centerValue.tk_variable, state='disabled') self.centerEntry.grid( row=0, column=1 ) self.removeExisting = Hybrid.Checkbutton(parent, "Remove existing ions/solvent", True) self.removeExisting.button.grid(row=4, column=0) parent.rowconfigure(0, weight=1) parent.columnconfigure(0, weight=1)
def __init__(self, master, **kw): Tkinter.Frame.__init__(self, master, **kw) self.rgbaOpt = RGBAOption(self, 1, 'Color', prefs[COLOR], None, noneOkay=False) self.associateVar = Tkinter.IntVar(self) self.associateVar.set(0) Tkinter.Checkbutton(self, command=self.modelsActivity, text="Associate with...", variable=self.associateVar ).grid(row=2, column=0, sticky='e') self.moleculeList = MoleculeScrolledListBox(self, autoselect='single', listbox_state='disabled') self.moleculeList.grid(row=2, column=1, sticky='w')
def fillInUI(self, parent): OpenModeless.fillInUI(self, parent) from chimera.widgets import MoleculeScrolledListBox self.molListBox = MoleculeScrolledListBox(self.clientArea, listbox_selectmode="extended", labelpos="w", label_text="Restrict to models:") self.molListBox.grid(row=0, column=0, sticky="nsew") self.clientArea.rowconfigure(0, weight=1) self.clientArea.columnconfigure(0, weight=1) checkButtonFrame = Tkinter.Frame(self.clientArea) checkButtonFrame.grid(row=1, column=0) self.openDialog = Tkinter.IntVar(parent) self.openDialog.set(True) Tkinter.Checkbutton(checkButtonFrame, variable=self.openDialog, text="Open Render/Select by Attribute").grid( row=0, column=0, sticky='w') self.doLog = Tkinter.IntVar(parent) self.doLog.set(False) Tkinter.Checkbutton(checkButtonFrame, text="Send match info to Reply Log", variable=self.doLog).grid(row=1, column=0, sticky='w')
class PLIPInputDialog(TangramBaseDialog): buttons = ('Run', 'Close') def __init__(self, *args, **kwargs): # GUI init self.title = 'Tangram PLIP' self.controller = None # Fire up super(PLIPInputDialog, self).__init__(*args, **kwargs) def fill_in_ui(self, parent): input_frame = tk.LabelFrame(self.canvas, text='Select a protein-ligand complex') self.ui_molecules = MoleculeScrolledListBox(input_frame) self.ui_molecules.filtFunc = lambda m: not m.name.startswith('PLIP-') self.ui_molecules.refresh() self.ui_molecules.pack(padx=5, pady=5, expand=True, fill='both') input_frame.pack(padx=5, pady=5, expand=True, fill='both') def Apply(self): pass def Run(self): self.Apply() self.Close() def Close(self): global ui ui = None super(PLIPInputDialog, self).Close() def load_controller(self): pass
def fillInUI(self, parent): import Pmw, Tkinter from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(parent, labelpos='w', label_text="Add hydrogens to:", listbox_selectmode='extended', selectioncommand=self._updateHisListing) if self.startModels: self.molList.setvalue(self.startModels) self.molList.grid(row=0, column=0, sticky="news") parent.columnconfigure(0, weight=1) parent.rowconfigure(0, weight=1) grp = Pmw.Group(parent, tag_text="Method", hull_padx=2) grp.grid(row=1, column=0, sticky="ew") self.useHBondsVar = Tkinter.IntVar(parent) self.useHBondsVar.set(self.startUseHBonds) Tkinter.Radiobutton(grp.interior(), variable=self.useHBondsVar, value=False, text="steric only" ).grid(row=0, sticky='w') Tkinter.Radiobutton(grp.interior(), variable=self.useHBondsVar, value=True, text="also consider H-bonds (slower)" ).grid(row=1, sticky='w') self.hisGroup = Pmw.Group(parent, hull_padx=2, tag_text="Histidine Protonation") self.hisGroup.grid(row=2, column=0, sticky="nsew") self.hisProtVar = Tkinter.StringVar(parent) self.hisProtVar.set("name") interior = self.hisGroup.interior() Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="name", text="Residue-name-based\n" "(HIS/HID/HIE/HIP = unspecified/delta/epsilon/both)", command=self._switchHisList, justify="left").grid( row=0, 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=1, sticky='w') Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="default", command=self._switchHisList, text="Unspecified (determined by method)" ).grid(row=3, sticky='w')
def fillInUI(self, parent): from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(parent, labelpos='w', listbox_selectmode="extended", label_text="Add ions : ") self.molList.grid(row=0, column=0, sticky="nsew") rcf1 = Tkinter.Frame(parent) rcf1.grid(row=2, column=0, sticky="nsew") from Addions import ValidIontypes self.iontype = "Cl-" self.iontypeOption = Pmw.OptionMenu(rcf1, label_text= "Ion types:", labelpos = 'w', items=ValidIontypes, initialitem=self.iontype, command=self.changeIontype) self.iontypeOption.grid(row=0, column=0) rcf2 = Tkinter.Frame(parent) rcf2.grid(row=3, column=0) rcf2.columnconfigure(2, weight=1) self.numionOption = Pmw.RadioSelect(rcf2, buttontype='radiobutton', command=self.changeNumion, labelpos='w', label_text="# of ions:") self.numionOption.add("neutralize") self.numionOption.add("specific number:") self.numionOption.setvalue( "neutralize" ) self.numionOption.grid( row=0, column=0) self.numion = "neutralize" self.numionValue = Hybrid.StringVariable(rcf2) self.numionEntry = Tkinter.Entry(rcf2, width=5, textvariable=self.numionValue.tk_variable, state='disabled') self.numionEntry.grid( row=0, column=1 ) parent.rowconfigure(0, weight=1) parent.columnconfigure(0, weight=1)
class AddChargesDialog(ModelessDialog): name = "add charges" title = "Add Charges" help = "ContributedSoftware/addcharge/addcharge.html" default = 'OK' def __init__(self, process=None, models=None, chargeModel=None, cb=None, **kw): if process: self.title = "Assign Charges for %s" % process.title() else: from AddCharge import process self.process = process self.cb = cb self.startModels = models if not chargeModel: from AddCharge import defaultChargeModel chargeModel = defaultChargeModel self.initialChargeModel = chargeModel ModelessDialog.__init__(self, **kw) def fillInUI(self, parent): from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(parent, labelpos='w', listbox_selectmode="extended", label_text='Add charges to:') if self.startModels: self.molList.setvalue(self.startModels) self.molList.grid(row=0, column=0, sticky="nsew") parent.rowconfigure(0, weight=1) parent.columnconfigure(0, weight=1) import Pmw from AddCharge import knownChargeModels, defaultChargeModel self.chargeModel = Pmw.OptionMenu(parent, labelpos='w', label_text="Standard residues:", items=knownChargeModels, initialitem=self.initialChargeModel) self.chargeModel.grid(row=1, column=0) self.chargeMethod = ChargeMethodOption(parent, label="Other residues:") self.chargeMethod.grid(row=2, column=0) import Tkinter labelFrame = Tkinter.Frame(parent) labelFrame.grid(row=3, column=0) Tkinter.Label(labelFrame, text="Add labels showing charges" " to atoms in:").grid(row=0, column=0, rowspan=2) self.labelNonstandardVar = Tkinter.IntVar(parent) self.labelNonstandardVar.set(False) Tkinter.Checkbutton(labelFrame, text="nonstandard residues", variable=self.labelNonstandardVar).grid(row=0, column=1, sticky='w') self.labelStandardVar = Tkinter.IntVar(parent) self.labelStandardVar.set(False) Tkinter.Checkbutton(labelFrame, text="standard residues", variable=self.labelStandardVar).grid(row=1, column=1, sticky='w') def Apply(self): from AddCharge import initiateAddCharges from AddH.gui import checkNoHyds mols = self.molList.getvalue() chargeModel = self.chargeModel.getvalue() chargeMethod = self.chargeMethod.getvalue() checkNoHyds(mols, lambda mols=mols: initiateAddCharges( cb=self.cb, models=mols, chargeModel=chargeModel, method=chargeMethod, status=chimera.replyobj.status, labelStandard=self.labelStandardVar.get(), labelNonstandard=self.labelNonstandardVar.get()), self.process)
class DockPrepDialog(ModelessDialog): name = "dock prep dialog" title = "Dock Prep" buttons = ('OK', 'Cancel') default = 'OK' help = "ContributedSoftware/dockprep/dockprep.html" def fillInUI(self, parent): import Tkinter, Pmw row=0 from chimera.widgets import MoleculeScrolledListBox self.molListBox = MoleculeScrolledListBox(parent, labelpos="nw", label_text="Molecules to prep:", listbox_selectmode="extended") self.molListBox.grid(row=row, sticky='ew') row += 1 Tkinter.Label(parent, text="\nFor chosen molecules," " do the following:").grid(row=row, sticky='w') row += 1 self.delSolventVar = Tkinter.IntVar(parent) self.delSolventVar.set(True) Tkinter.Checkbutton(parent, variable=self.delSolventVar, text= "Delete solvent").grid(row=row, sticky='w') row += 1 self.delIonsVar = Tkinter.IntVar(parent) self.delIonsVar.set(False) Tkinter.Checkbutton(parent, variable=self.delIonsVar, text= "Delete non-complexed ions").grid(row=row, sticky='w') row += 1 self.delAltLocsVar = Tkinter.IntVar(parent) self.delAltLocsVar.set(True) Tkinter.Checkbutton(parent, variable=self.delAltLocsVar, text= "If alternate locations, keep only highest occupancy", ).grid(row=row, sticky='w') row += 1 f = Tkinter.Frame(parent) f.grid(row=row, sticky='w') Tkinter.Label(f, text="Change:").grid( row=0, column=0, rowspan=4) self.mutMseVar = Tkinter.IntVar(parent) self.mutMseVar.set(True) Tkinter.Checkbutton(f, variable=self.mutMseVar, text= "selenomethionine (MSE) to methionine (MET)" ).grid(row=0, column=1, sticky='w') self.mut5buVar = Tkinter.IntVar(parent) self.mut5buVar.set(True) Tkinter.Checkbutton(f, variable=self.mut5buVar, text= "bromo-UMP (5BU) to UMP (U)" ).grid(row=1, column=1, sticky='w') self.mutUmsVar = Tkinter.IntVar(parent) self.mutUmsVar.set(True) Tkinter.Checkbutton(f, variable=self.mutUmsVar, text= "methylselenyl-dUMP (UMS) to UMP (U)" ).grid(row=2, column=1, sticky='w') self.mutCslVar = Tkinter.IntVar(parent) self.mutCslVar.set(True) Tkinter.Checkbutton(f, variable=self.mutCslVar, text= "methylselenyl-dCMP (CSL) to CMP (C)" ).grid(row=3, column=1, sticky='w') row += 1 self.incompleteVar = Tkinter.IntVar(parent) self.incompleteVar.set(True) f = Tkinter.Frame(parent) Tkinter.Checkbutton(f, variable=self.incompleteVar, text="Incomplete side chains:", command=self._incompleteCB).grid(row=0, column=0) from Rotamers import libraries libraries.sort(lambda a, b: cmp(a.displayName, b.displayName)) from chimera.tkoptions import SymbolicEnumOption labels = ["Replace using %s rotamer library" % lib.displayName for lib in libraries] labels.append("Mutate residues to ALA (if CB present) or GLY") values = libraries + ["gly/ala"] class IncompleteSCOption(SymbolicEnumOption): pass IncompleteSCOption.labels = labels IncompleteSCOption.values = values for possibleDefault in (prefs[INCOMPLETE_SC], defaults[INCOMPLETE_SC]): for val in IncompleteSCOption.values: if type(val) == str: if val == possibleDefault: default = possibleDefault break elif val.importName == possibleDefault: default = val break else: continue break self.incompleteOpt = IncompleteSCOption(f, 0, "", default, self._incompleteCB) f.grid(row=row, sticky='w') row += 1 self.addHydVar = Tkinter.IntVar(parent) self.addHydVar.set(True) Tkinter.Checkbutton(parent, variable=self.addHydVar, text="Add hydrogens").grid(row=row, sticky='w') row += 1 self.addChargesVar = Tkinter.IntVar(parent) self.addChargesVar.set(True) Tkinter.Checkbutton(parent, variable=self.addChargesVar, text="Add charges").grid(row=row, sticky='w') row += 1 self.writeMol2Var = Tkinter.IntVar(parent) self.writeMol2Var.set(True) Tkinter.Checkbutton(parent, variable=self.writeMol2Var, text="Write Mol2 file").grid(row=row, sticky='w') row += 1 self.applyKeywords = {} self.citationWidgets = {} self.citationRow = row self._incompleteCB() def Apply(self): from DockPrep import prep if self.addHydVar.get(): import AddH addHFunc = AddH.hbondAddHydrogens else: addHFunc = None kw = self.applyKeywords self.applyKeywords = {} rotamerLib = rotamerPreserve = None if self.incompleteVar.get(): incompleteVal = self.incompleteOpt.get() if type(incompleteVal) != str: rotamerLib = incompleteVal.importName rotamerPreserve = True incompleteVal = "rotamers" prefs[INCOMPLETE_SC] = incompleteVal else: incompleteVal = None prep(self.molListBox.getvalue(), addHFunc=addHFunc, addCharges=self.addChargesVar.get(), runSaveMol2Dialog=self.writeMol2Var.get(), mutateMSE=self.mutMseVar.get(), mutate5BU=self.mut5buVar.get(), mutateUMS=self.mutUmsVar.get(), mutateCSL=self.mutCslVar.get(), delSolvent=self.delSolventVar.get(), delIons=self.delIonsVar.get(), delAltLocs=self.delAltLocsVar.get(), incompleteSideChains=incompleteVal, rotamerLib=rotamerLib, rotamerPreserve=rotamerPreserve, **kw) def _incompleteCB(self, *args): if 'showing' in self.citationWidgets: self.citationWidgets['showing'].grid_forget() del self.citationWidgets['showing'] if not self.incompleteVar.get(): return lib = self.incompleteOpt.get() if type(lib) == str: return if lib not in self.citationWidgets: if lib.citation: from CGLtk.Citation import Citation citationWidget = Citation(self.uiMaster(), lib.citation, prefix="Publications" " using %s rotamers should cite:" % lib.citeName) else: citationWidget = None self.citationWidgets[lib] = citationWidget else: citationWidget = self.citationWidgets[lib] if citationWidget: citationWidget.grid(row=self.citationRow, column=0) self.citationWidgets['showing'] = citationWidget
def fillInUI(self, parent): import Tkinter, Pmw row = 0 from chimera.widgets import MoleculeScrolledListBox self.molListBox = MoleculeScrolledListBox( parent, labelpos="nw", label_text="Molecules to prep:", listbox_selectmode="extended") self.molListBox.grid(row=row, sticky='ew') row += 1 Tkinter.Label(parent, text="\nFor chosen molecules," " do the following:").grid(row=row, sticky='w') row += 1 self.delSolventVar = Tkinter.IntVar(parent) self.delSolventVar.set(True) Tkinter.Checkbutton(parent, variable=self.delSolventVar, text="Delete solvent").grid(row=row, sticky='w') row += 1 self.delIonsVar = Tkinter.IntVar(parent) self.delIonsVar.set(False) Tkinter.Checkbutton(parent, variable=self.delIonsVar, text="Delete non-complexed ions").grid(row=row, sticky='w') row += 1 self.delAltLocsVar = Tkinter.IntVar(parent) self.delAltLocsVar.set(True) Tkinter.Checkbutton( parent, variable=self.delAltLocsVar, text="If alternate locations, keep only highest occupancy", ).grid(row=row, sticky='w') row += 1 f = Tkinter.Frame(parent) f.grid(row=row, sticky='w') Tkinter.Label(f, text="Change:").grid(row=0, column=0, rowspan=4) self.mutMseVar = Tkinter.IntVar(parent) self.mutMseVar.set(True) Tkinter.Checkbutton( f, variable=self.mutMseVar, text="selenomethionine (MSE) to methionine (MET)").grid(row=0, column=1, sticky='w') self.mut5buVar = Tkinter.IntVar(parent) self.mut5buVar.set(True) Tkinter.Checkbutton(f, variable=self.mut5buVar, text="bromo-UMP (5BU) to UMP (U)").grid(row=1, column=1, sticky='w') self.mutUmsVar = Tkinter.IntVar(parent) self.mutUmsVar.set(True) Tkinter.Checkbutton(f, variable=self.mutUmsVar, text="methylselenyl-dUMP (UMS) to UMP (U)").grid( row=2, column=1, sticky='w') self.mutCslVar = Tkinter.IntVar(parent) self.mutCslVar.set(True) Tkinter.Checkbutton(f, variable=self.mutCslVar, text="methylselenyl-dCMP (CSL) to CMP (C)").grid( row=3, column=1, sticky='w') row += 1 self.incompleteVar = Tkinter.IntVar(parent) self.incompleteVar.set(True) f = Tkinter.Frame(parent) Tkinter.Checkbutton(f, variable=self.incompleteVar, text="Incomplete side chains:", command=self._incompleteCB).grid(row=0, column=0) from Rotamers import libraries libraries.sort(lambda a, b: cmp(a.displayName, b.displayName)) from chimera.tkoptions import SymbolicEnumOption labels = [ "Replace using %s rotamer library" % lib.displayName for lib in libraries ] labels.append("Mutate residues to ALA (if CB present) or GLY") values = libraries + ["gly/ala"] class IncompleteSCOption(SymbolicEnumOption): pass IncompleteSCOption.labels = labels IncompleteSCOption.values = values for possibleDefault in (prefs[INCOMPLETE_SC], defaults[INCOMPLETE_SC]): for val in IncompleteSCOption.values: if type(val) == str: if val == possibleDefault: default = possibleDefault break elif val.importName == possibleDefault: default = val break else: continue break self.incompleteOpt = IncompleteSCOption(f, 0, "", default, self._incompleteCB) f.grid(row=row, sticky='w') row += 1 self.addHydVar = Tkinter.IntVar(parent) self.addHydVar.set(True) Tkinter.Checkbutton(parent, variable=self.addHydVar, text="Add hydrogens").grid(row=row, sticky='w') row += 1 self.addChargesVar = Tkinter.IntVar(parent) self.addChargesVar.set(True) Tkinter.Checkbutton(parent, variable=self.addChargesVar, text="Add charges").grid(row=row, sticky='w') row += 1 self.writeMol2Var = Tkinter.IntVar(parent) self.writeMol2Var.set(True) Tkinter.Checkbutton(parent, variable=self.writeMol2Var, text="Write Mol2 file").grid(row=row, sticky='w') row += 1 self.applyKeywords = {} self.citationWidgets = {} self.citationRow = row self._incompleteCB()
def fillInUI(self, parent): import Pmw, Tkinter SaveModeless.fillInUI(self, parent) row = 0 from chimera.widgets import MoleculeScrolledListBox, \ ModelOptionMenu self.modelList = MoleculeScrolledListBox(self.clientArea, labelpos='w', label_text="Save models:", listbox_selectmode='extended', selectioncommand=lambda: self.configure( self.modelList.getvalue(), refreshList=False)) self.modelList.grid(row=row, column=0, sticky='nsew') self.clientArea.rowconfigure(row, weight=1) self.clientArea.columnconfigure(0, weight=1) row += 1 from chimera import dialogs self.labelMap = { "individual": "a single file [individual @MOLECULE sections]", "combined": "a single file [combined @MOLECULE section]", "multiple": "multiple files [appending model number]" } preferred = self.labelMap[self.prefs["multiSaveMol2"]] self.multiSaveMenu = Pmw.OptionMenu(self.clientArea, labelpos='w', label_text="Save multiple models in", initialitem=preferred, items=self.labelMap.values()) # not always shown; remember row number self._msmRow = row row += 1 self.saveRelativeVar = Tkinter.IntVar(self.clientArea) self.saveRelativeVar.set(False) self.relativeFrame = f = Tkinter.Frame(self.clientArea) Tkinter.Checkbutton(f, variable=self.saveRelativeVar, text="Save relative to model:").grid(row=0, column=0, sticky='e') self.relModelMenu = ModelOptionMenu(f) self.relModelMenu.grid(row=0, column=1, sticky='w') self.saveUntransformedVar = Tkinter.IntVar(parent) self.saveUntransformedVar.set(True) self.untransformedButton = Tkinter.Checkbutton(self.clientArea, variable=self.saveUntransformedVar, text="Use untransformed coordinates") self._rfRow = row row += 1 self.sybylHydNamesVar = Tkinter.IntVar(self.clientArea) self.sybylHydNamesVar.set( self.prefs["hydrogen naming"] == "sybyl") Tkinter.Checkbutton(self.clientArea, variable=self.sybylHydNamesVar, text="Use Sybyl-style hydrogen naming (e.g. HE12" " rather than 2HE1)").grid(row=row, column=0, sticky="w") row += 1 self.resNumsVar = Tkinter.IntVar(self.clientArea) self.resNumsVar.set(self.prefs["residue numbers"]) Tkinter.Checkbutton(self.clientArea, variable=self.resNumsVar, text="Include residue sequence numbers in substructure" " names").grid(row=row, column=0, sticky='w') row += 1 self.writeGaffVar = Tkinter.IntVar(self.clientArea) self.resNumsVar.set(False) Tkinter.Checkbutton(self.clientArea, variable=self.writeGaffVar, text="Write Amber/GAFF atom types instead of Sybyl atom types" ).grid(row=row, column=0, sticky='w') row += 1 self.rigidVar = Tkinter.IntVar(self.clientArea) self.rigidVar.set(False) Tkinter.Checkbutton(self.clientArea, variable=self.rigidVar, text="Write current selection to @SETS section of file" ).grid(row=row, column=0, sticky="w") row += 1
class NCIPlotDialog(TangramBaseDialog): buttons = ('Run', 'Save', 'Load', 'Close') configure_dialog = None help = "https://github.com/insilichem/tangram_nciplot" VERSION = '0.0.1' VERSION_URL = "https://api.github.com/repos/insilichem/tangram_nciplot/releases/latest" def __init__(self, *args, **kwargs): # GUI init self.title = 'Tangram NCIPlot' self._mouse_report_binding = None # Variables self.var_input_intermolecular_enabled = tk.IntVar() self.var_input_intermolecular = tk.IntVar() self.var_input_intermolecular.set(95) self.var_input_summary = tk.StringVar() self.var_input_summary.set('Please select your input.') self.var_input_choice = tk.StringVar() self.var_input_choice.set('molecules') self.var_settings_isovalue_1 = tk.StringVar() self.var_settings_isovalue_1.set('') self.var_settings_isovalue_2 = tk.StringVar() self.var_settings_isovalue_2.set('') self.var_settings_report = tk.IntVar() self.var_reported_value = tk.StringVar() # Fire up super(NCIPlotDialog, self).__init__(*args, **kwargs) def fill_in_ui(self, parent): # Select an input menu: Radio buttons self.ui_input_frame = tk.LabelFrame(self.canvas, text='Input mode') self.ui_input_frame.pack(expand=True, fill='x', padx=5, pady=5) self.ui_input_frame.columnconfigure(0, weight=1) self.ui_input_choice_frame = tk.Frame(self.ui_input_frame) self.ui_input_choice_frame.grid(row=0, sticky='we') self.ui_input_choice_molecules = tk.Radiobutton( self.ui_input_choice_frame, variable=self.var_input_choice, text='Molecules', value='molecules', command=self._input_choice_cb) self.ui_input_choice_selection = tk.Radiobutton( self.ui_input_choice_frame, variable=self.var_input_choice, text='Selection', value='selection', command=self._input_choice_cb) self.ui_input_choice_molecules.pack(side='left') self.ui_input_choice_selection.pack(side='left') self.ui_input_choice_molecules.select() # Mode A: Opened molecules self.ui_input_molecules_frame = tk.Frame(self.ui_input_frame) self.ui_input_molecules_frame.grid(row=1, sticky='news') self.ui_input_molecules_frame.columnconfigure(0, weight=1) self.ui_input_molecules = MoleculeScrolledListBox( self.ui_input_molecules_frame, selectioncommand=self._on_selection_changed, listbox_selectmode="extended") self.ui_input_molecules.pack(expand=True, fill='x', padx=5) # Mode B: Current selection items = ['Current selection'] + sorted( chimera.selection.savedSels.keys()) self.ui_input_named_selections = OptionMenu( self.ui_input_molecules_frame, command=None, items=items) self.input_new_named_atom_selection = None # Text field + 'Create button' # More options self.ui_input_intermolecular_frame = tk.Frame(self.ui_input_frame) self.ui_input_intermolecular_frame.grid(row=2) self.ui_input_intermolecular_check = tk.Checkbutton( self.ui_input_intermolecular_frame, text='Filter out % of intramolecular', variable=self.var_input_intermolecular_enabled, command=self._intermolecular_cb, state='disabled') self.ui_input_intermolecular_check.pack(side='left') self.ui_input_intermolecular_field = tk.Entry( self.ui_input_intermolecular_frame, textvariable=self.var_input_intermolecular, state='disabled', width=3) self.ui_input_intermolecular_field.pack(side='left') # Review input data self.ui_input_summary_label = tk.Label( self.ui_input_frame, textvariable=self.var_input_summary) self.ui_input_summary_label.grid(row=3) # NCIPlot launcher self.ui_nciplot_frame = tk.Frame(self.canvas) self.ui_nciplot_frame.pack() self.ui_config_btn = tk.Button(self.ui_nciplot_frame, text='Configure', command=self._configure_dialog) self.ui_config_btn.pack(side='left') # Configure Volume Viewer self.ui_settings_frame = tk.LabelFrame(self.canvas, text='Customize display', padx=5, pady=5) self.ui_levels_lbl = tk.Label(self.ui_settings_frame, text='Levels: ') self.ui_levels_lbl.grid(row=0, column=0) self.ui_settings_isovalue_1 = tk.Entry( self.ui_settings_frame, textvariable=self.var_settings_isovalue_1, width=10) self.ui_settings_isovalue_1.grid(row=0, column=1, sticky='ew') self.ui_settings_isovalue_2 = tk.Entry( self.ui_settings_frame, textvariable=self.var_settings_isovalue_2, width=10) self.ui_settings_isovalue_2.grid(row=0, column=2, sticky='ew') self.ui_settings_update_btn = tk.Button(self.ui_settings_frame, text='Update', command=self._update_surface) self.ui_settings_update_btn.grid(row=0, column=3, rowspan=2, sticky='news') self.ui_settings_color_palette = OptionMenu( self.ui_settings_frame, initialitem=3, label_text='Colors: ', labelpos='w', items=sorted(standard_color_palettes.keys())) self.ui_settings_color_palette.grid(row=1, column=0, columnspan=3, sticky='we') self.ui_report_btn = tk.Checkbutton( self.ui_settings_frame, text=u'Report \u03BB\u2082\u22C5\u03C1\u22C5100 value at cursor', command=self._report_values_cb, variable=self.var_settings_report) self.ui_report_btn.grid(row=2, column=0, columnspan=3) self.ui_reported_value = tk.Entry(self.ui_settings_frame, textvariable=self.var_reported_value, state='readonly', width=8) self.ui_reported_value.grid(row=2, column=3, sticky='we') # Plot figure self.ui_plot_frame = tk.LabelFrame( self.canvas, text=u'Plot RDG vs density (\u03BB\u2082\u22C5\u03C1)', padx=5, pady=5) self.ui_plot_button = tk.Button(self.ui_plot_frame, text='Plot', command=self._plot) self.ui_plot_button.grid(row=0) self.ui_plot_figure = Figure(figsize=(5, 5), dpi=100, facecolor='#D9D9D9') self.ui_plot_subplot = self.ui_plot_figure.add_subplot(111) self.ui_plot_widget_frame = tk.Frame(self.ui_plot_frame) self.ui_plot_widget_frame.grid(row=1) self.ui_plot_widget = FigureCanvasTkAgg( self.ui_plot_figure, master=self.ui_plot_widget_frame) # self.plot_cursor = Cursor(self.plot_subplot, useblit=True, color='black', linewidth=1) # self.plot_figure.canvas.mpl_connect('button_press_event', self._on_plot_click) # Register and map triggers, callbacks... chimera.triggers.addHandler('selection changed', self._on_selection_changed, None) self.nciplot_run = self.buttonWidgets['Run'] self.buttonWidgets['Save']['state'] = 'disabled' def load_controller(self): binary, dat = prefs.get_preferences() return Controller(gui=self, nciplot_binary=binary, nciplot_dat=dat) def input_options(self): d = {} if self.var_input_intermolecular_enabled.get(): d['intermolecular'] = self.var_input_intermolecular.get() / 100.0 return d # All the callbacks def _input_choice_cb(self): """ Change input mode """ if self.var_input_choice.get() == 'molecules': self.ui_input_molecules.pack(expand=True, fill='x', padx=5) self.ui_input_named_selections.pack_forget() elif self.var_input_choice.get() == 'selection': self.ui_input_molecules.pack_forget() self.ui_input_named_selections.pack(expand=True, fill='x', padx=5) self._on_selection_changed() def _intermolecular_cb(self): if self.var_input_intermolecular_enabled.get(): self.ui_input_intermolecular_field.config(state='normal') else: self.ui_input_intermolecular_field.config(state='disabled') def _validate_input_data(self, *args): atoms = self._on_selection_changed() return atoms def _configure_dialog(self, *args): if self.configure_dialog is None: self.configure_dialog = NCIPlotConfigureDialog(self.canvas) self.configure_dialog.enter() def Run(self, *args): """ Called at clicking 'Run' button. """ self._run_nciplot_clear_cb() atoms = self._validate_input_data() if atoms: attr_getter = attrgetter('molecule') groups = [ list(group) for k, group in groupby(atoms, key=attr_getter) ] options = self.input_options() self.controller = self.load_controller() self.controller.run(groups=groups, **options) self.nciplot_run.configure(state='disabled', text='Running...') self.ui_settings_frame.pack_forget() def Save(self, *args): try: grad = self.controller.data['grad_cube'] dens = self.controller.data['dens_cube'] xy = self.controller.data['xy_data'] except KeyError: raise chimera.UserError("NCIPlot has not run yet!") path = tkFileDialog.asksaveasfilename( title='Choose destination (.cube)', filetypes=[('Gaussian cube', '*.cube'), ('All', '*')], defaultextension='.cube') if not path: return data = self.controller.data.copy() basename, ext = os.path.splitext(path) data['grad_cube'] = newgradpath = '{fn}.grad{ext}'.format(fn=basename, ext=ext) shutil.copyfile(grad, newgradpath) data['dens_cube'] = newdenspath = '{fn}.dens{ext}'.format(fn=basename, ext=ext) shutil.copyfile(dens, newdenspath) data['xy_data'] = newdatpath = '{fn}.dat'.format(fn=basename, ext=ext) shutil.copyfile(xy, newdatpath) with open('{}.json'.format(basename), 'w') as f: json.dump(data, f) self.status('Saved at {}!'.format(os.path.dirname(path)), color='blue', blankAfter=4) def Load(self, *args): path = tkFileDialog.askopenfilename(title='Choose state file (*.json)', filetypes=[('JSON file', '*.json'), ('All', '*')]) if not path: return with open(path) as f: data = json.load(f) self._run_nciplot_clear_cb() self.controller = self.load_controller() self.controller._after_cb(data) self._run_nciplot_cb() def Close(self): # Singleton mode global ui ui = None super(NCIPlotDialog, self).Close() def _run_nciplot_cb(self): """ Called after NCIPlot has successfully run """ self.nciplot_run.configure(state='normal', text='Run') self.var_settings_isovalue_1.set( self.controller.surface.surface_levels[0]) self.var_settings_isovalue_2.set( self.controller.surface.surface_levels[1]) self.ui_settings_frame.pack() self.ui_plot_frame.pack(expand=True, fill='both') self.buttonWidgets['Save']['state'] = 'normal' def _run_nciplot_clear_cb(self): """ Housecleaning method. Resets everything to original state """ self.nciplot_run.configure(state='normal', text='Run') self.ui_plot_button.configure(state='normal') self.ui_settings_frame.pack_forget() self.var_settings_isovalue_1.set('') self.var_settings_isovalue_2.set('') self.ui_plot_frame.pack_forget() self.ui_plot_widget.get_tk_widget().pack_forget() self.controller = None self.buttonWidgets['Save']['state'] = 'disabled' def _update_surface(self): """ Gets GUI options, sets them and updates the surface """ # Levels isovalue_1 = float(self.var_settings_isovalue_1.get()) isovalue_2 = float(self.var_settings_isovalue_2.get()) self.controller.isosurface(level_1=isovalue_1, level_2=isovalue_2) # Update view self.controller.update_surface() # Colors palette = self.ui_settings_color_palette.getvalue() self.controller.colorize_by_volume(palette=palette) # Update view self.controller.update_surface() def _plot(self): """ Draw density vs rdg with a hexbin """ self.controller.plot(self.ui_plot_subplot) self.ui_plot_widget.get_tk_widget().pack(expand=True, fill='both') self.ui_plot_widget.show() self.ui_plot_button.configure(state='disabled') def _report_values_cb(self): """ Binds mouse mouse callbacks to mouse movement events """ if self.var_settings_report.get( ) and self._mouse_report_binding is None: self._mouse_report_binding = chimera.tkgui.app.graphics.bind( '<Any-Motion>', self._report_values_event, add=True) def _report_values_event(self, event): """ Report value of isosurface at cursor point """ if self.var_settings_report.get() and self.isVisible(): vpn = surface_value_at_window_position(event.x, event.y) if vpn is None: self.var_reported_value.set('') else: value, position, name = vpn self.var_reported_value.set('{:8.5g}'.format(float(value))) chimera.replyobj.status('{} at cursor: {:8.5g}'.format( name, float(value))) def _on_plot_click(self, event): """ Callback that sets isosurface values from plot X axis data. Left click sets isovalue 1, right click sets isovalue 2 """ if event.button == 1: self.var_settings_isovalue_1.set(round(event.xdata, 2)) elif event.button == 3: self.var_settings_isovalue_2.set(round(event.xdata, 2)) def _on_selection_changed(self, *args): """ Test if current selection is valid for running a new calculation, reports number of atoms """ atoms = [] if self.var_input_choice.get() == 'selection': atoms = chimera.selection.currentAtoms() molecules = chimera.selection.currentMolecules() elif self.var_input_choice.get() == 'molecules': molecules = self.ui_input_molecules.getvalue() atoms = [a for m in molecules for a in m.atoms] color, state = ('black', 'normal') if atoms else ('red', 'disabled') self.nciplot_run.configure(state=state) self.ui_input_summary_label.configure(foreground=color) self.var_input_summary.set('{} selected atoms'.format(len(atoms))) if len(molecules) > 1: self.ui_input_intermolecular_check.config(state='normal') self.ui_input_intermolecular_check.select() else: self.ui_input_intermolecular_check.config(state='disabled') self.ui_input_intermolecular_check.deselect() self._intermolecular_cb() return atoms
def fillInUI(self, parent): self.notebook = Pmw.NoteBook(parent) self.notebook.pack(fill="both", expand=True) page = self.notebook.add("Molecules") self.molChooser = MoleculeScrolledListBox(page, listbox_selectmode="extended", autoselect="single") self.molChooser.pack(fill="both", expand=True) page = self.notebook.add("Chains") self.chainChooser = MoleculeChainScrolledListBox(page, listbox_selectmode="extended", autoselect="single") self.chainChooser.pack(fill="both", expand=True) self.outputOptions = Pmw.RadioSelect(parent, pady=0, buttontype="checkbutton", orient="vertical") self.outputOptions.pack(fill="x", expand=False) self.outputOptions.add("solid", text="Solid surface (rather than mesh)") self.outputOptions.add("track", text="Reuse last surface (if any)") self.outputOptions.add("atoms", text="Select interface atoms") self.outputOptions.add("prune", text="Residue centroid distance pruning") self.outputOptions.setvalue(["solid", "track"]) self.pruneDistance = Pmw.EntryField(parent, labelpos="w", label_text="Prune distance:", value="30.0", validate=self._validatePruneDistance) self.pruneDistance.pack(fill="x", expand=False) self.moleculeBias = Pmw.Counter(parent, labelpos="w", label_text="Molecule bias:", datatype="real", increment = 0.1, entryfield_value="0.5", entryfield_validate={'validator' : 'real', 'min' : '0.0', 'max' : '1.0', 'separator' : '.'}) self.moleculeBias.pack(fill="x", expand=False) histKw = { 'minlabel': True, 'maxlabel': True, 'scaling': 'linear', } self.histogram = MarkedHistogram(parent, **histKw) self.histogramMarkers = self.histogram.addmarkers(activate=True, coordtype='relative') self.histogramMarkers.extend([ ((1.0, 0.0), (0.0, 0.0, 0.33, 1.0)), ((0.0, 0.0), (1.0, 0.0, 0.0, 1.0))]) self.histogram.pack(expand=True, fill="both") self._trackedPiece = None self._trackedModel = None self.models = {} chimera.openModels.addRemoveHandler(self._removeModel, None) import SimpleSession chimera.triggers.addHandler(SimpleSession.SAVE_SESSION, self.saveSession, None) chimera.triggers.addHandler("Molecule", self._moleculeChanged, None)
def fillInUI(self, parent): SaveModeless.fillInUI(self, parent) row = 0 from chimera.widgets import MoleculeScrolledListBox, \ ModelOptionMenu self.modelList = MoleculeScrolledListBox(self.clientArea, labelpos='w', label_text="Save models:", listbox_selectmode='extended', selectioncommand=lambda: self.configure( self.modelList.getvalue(), refreshList=False)) self.modelList.grid(row=row, column=0, sticky='nsew') self.clientArea.rowconfigure(row, weight=1) self.clientArea.columnconfigure(0, weight=1) row += 1 import Tkinter, Pmw self.dispOnlyVar = Tkinter.IntVar(parent) self.dispOnlyVar.set(False) Tkinter.Checkbutton(self.clientArea, variable=self.dispOnlyVar, text="Save displayed atoms only").grid(row=row, column=0, sticky='w') row += 1 self.selOnlyVar = Tkinter.IntVar(parent) self.selOnlyVar.set(False) Tkinter.Checkbutton(self.clientArea, variable=self.selOnlyVar, text="Save selected atoms only").grid(row=row, column=0, sticky='w') row += 1 self.saveRelativeVar = Tkinter.IntVar(parent) self.saveRelativeVar.set(False) self.relativeFrame = f = Tkinter.Frame(self.clientArea) Tkinter.Checkbutton(f, variable=self.saveRelativeVar, text="Save relative to model:" ).grid(row=0, column=0, sticky='e') self.relModelMenu = ModelOptionMenu(f) self.relModelMenu.grid(row=0, column=1, sticky='w') self.saveUntransformedVar = Tkinter.IntVar(parent) self.saveUntransformedVar.set(True) self.untransformedButton = Tkinter.Checkbutton(self.clientArea, variable=self.saveUntransformedVar, text="Use untransformed coordinates") self._rfRow = row row += 1 self.frameSave = Pmw.OptionMenu(self.clientArea, labelpos='w', label_text="Save", initialitem="current frame", items=["current frame", "all frames"]) # not always shown; remember row number self._fsRow = row row += 1 from chimera import dialogs self.labelMap = { "single": "a single file", "multiple": "multiple files [appending model number]" } preferred = self.labelMap[self.prefs["multiSavePDB"]] self.multiSaveMenu = Pmw.OptionMenu(self.clientArea, labelpos='w', label_text="Save multiple models in", initialitem=preferred, items=self.labelMap.values()) # not always shown; remember row number self._msmRow = row row += 1
class AddionsDialog(ModelessDialog): name = "addions" title = "Addions" #help = "ContributedSoftware/addcharge/addcharge.html" def fillInUI(self, parent): from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(parent, labelpos='w', listbox_selectmode="extended", label_text="Add ions : ") self.molList.grid(row=0, column=0, sticky="nsew") rcf1 = Tkinter.Frame(parent) rcf1.grid(row=2, column=0, sticky="nsew") from Addions import ValidIontypes self.iontype = "Cl-" self.iontypeOption = Pmw.OptionMenu(rcf1, label_text= "Ion types:", labelpos = 'w', items=ValidIontypes, initialitem=self.iontype, command=self.changeIontype) self.iontypeOption.grid(row=0, column=0) rcf2 = Tkinter.Frame(parent) rcf2.grid(row=3, column=0) rcf2.columnconfigure(2, weight=1) self.numionOption = Pmw.RadioSelect(rcf2, buttontype='radiobutton', command=self.changeNumion, labelpos='w', label_text="# of ions:") self.numionOption.add("neutralize") self.numionOption.add("specific number:") self.numionOption.setvalue( "neutralize" ) self.numionOption.grid( row=0, column=0) self.numion = "neutralize" self.numionValue = Hybrid.StringVariable(rcf2) self.numionEntry = Tkinter.Entry(rcf2, width=5, textvariable=self.numionValue.tk_variable, state='disabled') self.numionEntry.grid( row=0, column=1 ) parent.rowconfigure(0, weight=1) parent.columnconfigure(0, weight=1) def changeIontype(self, state): self.iontype= state def changeNumion(self, state): if state=="neutralize": self.numion = "neutralize" self.numionEntry.config( state="disabled" ) else: self.numion = "specific" self.numionEntry.config( state="normal" ) def Apply(self): from chimera import UserError, replyobj if self.iontype=="": self.enter() raise UserError("No ion type chosen.") if self.numion =="specific": self.numion = self.numionValue.get() if self.numion=="": self.enter() raise UserError(" number of ion is not given." ) else: assert self.numion=="neutralize" from Addions import initiateAddions mols = self.molList.getvalue() from AddCharge.gui import checkNoCharges checkNoCharges(mols, lambda ur, ua, mols=mols: initiateAddions( mols, self.iontype, self.numion, replyobj.status), "ion addition")
def fillInUI(self, parent): self.refMolList = MoleculeScrolledListBox( parent, autoselect="single", labelpos="nw", label_text="Reference structure:") self.refChainList = MoleculeChainScrolledListBox( parent, labelpos="nw", label_text="Reference chain:", listbox_selectmode='extended') self.matchMolList = MoleculeScrolledListBox( parent, labelpos="nw", label_text="Structure(s) to match:", listbox_selectmode='extended') self.matchChainList = ChainMenus(parent) def doSync(): if self.chainMatchVar.get() != CP_SPECIFIC_SPECIFIC: return self.matchChainList.syncUp(self.refChainList) self.refChainList.configure(selectioncommand=doSync) parent.rowconfigure(0, weight=1) parent.columnconfigure(0, weight=1) parent.columnconfigure(1, weight=1) seqFrame = Tkinter.Frame(parent) seqFrame.grid(row=1, column=0, columnspan=2, sticky="nsew") seqFrame.columnconfigure(0, weight=1) seqFrame.columnconfigure(1, weight=1) pairingGroup = Pmw.Group(seqFrame, tag_text="Chain pairing") pairingGroup.grid(row=0, column=0, columnspan=2, sticky="w", padx=2) pairingGroup.interior().columnconfigure(0, weight=1) self.chainMatchVar = Tkinter.StringVar(parent) self.chainMatchVar.set(prefs[CHAIN_PAIRING]) radiobuttonInfo = [ (CP_BEST, "Best-aligning pair of chains\n\tbetween reference and match structure" ), (CP_SPECIFIC_BEST, "Specific chain in reference structure\n\twith best-aligning chain in match structure" ), (CP_SPECIFIC_SPECIFIC, "Specific chain(s) in reference structure\n\twith specific chain(s) in match structure" ), ] for i in range(len(radiobuttonInfo)): val, text = radiobuttonInfo[i] radio = Tkinter.Radiobutton(pairingGroup.interior(), command=self._chainMatchCB, text=text, justify='left', value=val, variable=self.chainMatchVar) radio.grid(row=i, column=0, sticky='w') self._chainMatchCB() self.seqAlgorithmMenu = Pmw.OptionMenu( seqFrame, initialitem=prefs[SEQUENCE_ALGORITHM], labelpos='w', label_text="Alignment algorithm:", items=[SA_NEEDLEMAN_WUNSCH, SA_SMITH_WATERMAN]) self.seqAlgorithmMenu.grid(row=1, column=0, sticky='w') matrixNames = SmithWaterman.matrices.keys() matrixNames.sort() if prefs[MATRIX] in SmithWaterman.matrices: initialMatrix = prefs[MATRIX] else: if defaults[MATRIX] in SmithWaterman.matrices: initialMatrix = defaults[MATRIX] else: initialMatrix = matrixNames[0] prefs[MATRIX] = initialMatrix self.matrixMenu = Pmw.OptionMenu(seqFrame, initialitem=initialMatrix, labelpos='w', label_text="Matrix:", items=matrixNames) self.matrixMenu.grid(row=1, column=1, sticky='w') gapFrame = Tkinter.Frame(seqFrame) gapFrame.grid(row=2, column=0, columnspan=2, sticky='ew') gapFrame.columnconfigure(0, weight=1) gapFrame.columnconfigure(1, weight=1) self.gapOpenEntry = Pmw.EntryField(gapFrame, labelpos='w', label_text="Gap opening penalty", validate='real', entry_width=2, entry_justify='right', value="%g" % (prefs[GAP_OPEN])) self.gapOpenEntry.grid(row=0, column=0) self.gapExtendEntry = Pmw.EntryField( gapFrame, labelpos='w', label_text="Gap extension penalty", validate='real', entry_width=2, entry_justify='right', value="%g" % (prefs[GAP_EXTEND])) self.gapExtendEntry.grid(row=0, column=1) self._entries = [self.gapOpenEntry, self.gapExtendEntry] self.ssParams = SSParams(seqFrame, prefs, useSSCB=self._useSSCB) self.ssParams.grid(row=3, column=0, columnspan=2, sticky='ew') self.computeSSVar = Tkinter.IntVar(parent) self.computeSSVar.set(prefs[COMPUTE_SS]) self._computeSSButton = Tkinter.Checkbutton( seqFrame, text="Compute secondary structure assignments", variable=self.computeSSVar) self._computeSSGridArgs = {'row': 4, 'sticky': 'w', 'columnspan': 2} if self.ssParams.useSSVar.get(): self._computeSSButton.grid(**self._computeSSGridArgs) self.showSeqVar = Tkinter.IntVar(parent) self.showSeqVar.set(prefs[SHOW_SEQUENCE]) Tkinter.Checkbutton(seqFrame, text="Show pairwise alignment(s)", variable=self.showSeqVar).grid(row=5, column=0, sticky='w', columnspan=2) matchGroup = Pmw.Group(parent, tag_text="Matching") matchGroup.grid(row=2, column=0, columnspan=2, sticky="nsew", padx=2) matchGroup.interior().columnconfigure(0, weight=1) self.iterVar = Tkinter.IntVar(parent) self.iterVar.set(prefs[ITERATE]) Tkinter.Checkbutton(matchGroup.interior(), justify="left", text="Iterate by pruning long atom pairs" " until no pair exceeds:", variable=self.iterVar).grid(row=0, column=0, sticky='w') self.iterEntry = Pmw.EntryField(matchGroup.interior(), validate='real', entry_width=3, entry_justify="right", value="%.1f" % prefs[ITER_CUTOFF], labelpos='e', label_text="angstroms") self.iterEntry.grid(row=1, column=0) self._entries.append(self.iterEntry) self.structSeqVar = Tkinter.IntVar(parent) self.structSeqVar.set(False) Tkinter.Checkbutton(parent, text="After superposition, compute" " structure-based multiple sequence alignment", variable=self.structSeqVar).grid(row=3, sticky='w', columnspan=2) f = Tkinter.Frame(parent) f.grid(row=4, column=0, columnspan=2, sticky='ew') 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) # set up state of gap-open entry self._useSSCB()
class SolvateDialog(ModelessDialog): name = "solvate" title = "Solvate" #help = "ContributedSoftware/addcharge/addcharge.html" def fillInUI(self, parent): from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(parent, labelpos='w', listbox_selectmode="extended", label_text="Solvate: ") self.molList.grid(row=0, column=0, sticky="nsew") self.solvateMethod = Pmw.RadioSelect(parent, buttontype='radiobutton', command=self.changeMethod, labelpos='w', label_text="Solvate method:") self.solvateMethod.add("Box") self.solvateMethod.add("Cap") self.solvateMethod.add("Oct") self.solvateMethod.add("Shell") self.solvateMethod.setvalue("Box") self.solvateMethod.grid(row=1, column=0, sticky="nsew") self.method = "Box" rcf1 = Tkinter.Frame(parent) rcf1.grid(row=2, column=0, sticky="nsew") self.solvent = prefs[SOLVENT_MODEL] from Solvate import ValidSolventModels self.solventModel = Pmw.OptionMenu(rcf1, label_text= "Solvent Model:", labelpos = 'w', items=ValidSolventModels, initialitem=self.solvent, command=self.changeSolvent) self.solventModel.grid(row=0, column=0) rcf2 = Tkinter.Frame(rcf1) rcf2.grid(row=0, column=1) rcf1.columnconfigure(1, weight=1) self.extentLabel = Tkinter.Label(rcf2, text="Box size:" ) self.extentLabel.grid(row=0, column=0) self.extentValue = Hybrid.StringVariable(rcf2) ev = Tkinter.Entry( rcf2, width=5, textvariable=self.extentValue.tk_variable) ev.grid( row=0, column=1 ) rcf3 = Tkinter.Frame(parent) rcf3.grid(row=3, column=0) self.centerLabel = Tkinter.Label(rcf3, text="Cap center (in ambmask):", state='disabled' ) self.centerLabel.grid(row=0, column=0) self.centerValue = Hybrid.StringVariable(rcf3) self.centerEntry = Tkinter.Entry( rcf3, width=5, textvariable=self.centerValue.tk_variable, state='disabled') self.centerEntry.grid( row=0, column=1 ) self.removeExisting = Hybrid.Checkbutton(parent, "Remove existing ions/solvent", True) self.removeExisting.button.grid(row=4, column=0) parent.rowconfigure(0, weight=1) parent.columnconfigure(0, weight=1) def changeMethod(self, state): self.method = state if state=="Box": self.extentLabel.config( text="Box size: " ) self.centerLabel.config( state='disabled' ) self.centerEntry.config( state='disabled' ) elif state=="Cap": self.extentLabel.config( text="Cap Radius: " ) self.centerLabel.config( state='normal' ) self.centerEntry.config( state='normal' ) elif state=="Oct": self.extentLabel.config( text="Oct size: " ) self.centerLabel.config( state='disabled' ) self.centerEntry.config( state='disabled' ) else: assert state=="Shell" self.extentLabel.config( text="Shell extent: " ) self.centerLabel.config( state='disabled' ) self.centerEntry.config( state='disabled' ) def changeSolvent(self, solvent): self.solvent = solvent def Apply(self): from chimera import UserError if self.solvent=="": self.enter() raise UserError("No solvent model chosen.") if self.extentValue.get()=="": self.enter() raise UserError(self.method + " size is not given." ) if self.method=="Cap" and self.centerValue.get()=="": self.enter() raise UserError("Center of cap is not given.") prefs[SOLVENT_MODEL] = self.solvent from Solvate import initiateSolvate mols = self.molList.getvalue() if self.removeExisting.variable.get(): from Midas import deleteAtomsBonds deleteAtomsBonds(atoms=[a for m in mols for a in m.atoms if a.surfaceCategory in ["solvent", "ions"]]) # in case any models were _all_ solvent/ions... mols = [m for m in mols if not m.__destroyed__] noHyds = [] for mol in mols: for a in mol.atoms: if a.element.number == 1: break else: noHyds.append(mol) if noHyds: from chimera.baseDialog import AskYesNoDialog msg = "Hydrogens must be present for" \ " solvation to work correctly.\n" if len(mols) == len(noHyds): msg += "No models have hydrogens.\n" else: msg += "The following models have no" \ " hydrogens:\n" for nh in noHyds: msg += "\t%s (%s)\n" % (nh.name, nh.oslIdent()) msg += "You can add hydrogens using the AddH tool.\n" msg += "What would you like to do?" from AddH.gui import NoHydsDialog userChoice = NoHydsDialog(msg).run(chimera.tkgui.app) if userChoice == "cancel": return elif userChoice == "add hydrogens": from AddH.gui import AddHDialog AddHDialog(title="Add Hydrogens for Solvate", models=noHyds, useHBonds=True, oneshot=True, cb=lambda mols=mols: initiateSolvate(mols,self.method, self.solvent, self.extentValue.get(), self.centerValue.get(), chimera.replyobj.status)) return initiateSolvate(mols, self.method, self.solvent, self.extentValue.get(), self.centerValue.get(), chimera.replyobj.status)
def fillInUI(self, parent): # inter/intra-model; slop; colors; models; replace current; # label # for removing labels in subsequent passes... # (use a selection so I don't have to track model closures) self.labelSelection = ItemizedSelection() self.labelMap = {} self.callbacks = [] row = 0 cols = 3 self.bondColorOption = ColorOption(parent, row, 'H-bond color', prefs[BOND_COLOR], None, noneOkay=0) class HBLineWidthOption(LineWidthOption): name = "Line width" balloon = "Width of pseudobonds (in pixels)" default = prefs[LINE_WIDTH] self.lineWidth = HBLineWidthOption(parent, row+1, None, None, None, width=4, sticky='w') self.findMode = Pmw.RadioSelect(parent, buttontype='radiobutton', labelpos='n', pady=0, orient='vertical', label_text='Find these bonds:', hull_borderwidth=2, hull_relief='ridge') self.findMode.add('inter-model') self.findMode.add('intra-model') self.findMode.add('both') self.findMode.invoke('both') self.findMode.grid(row=row, column=2, rowspan=2) row += 2 self.relaxParams = RelaxParams(parent, prefs[RELAX_COLOR]) self.relaxParams.grid(row=row, columnspan=cols, sticky='nsew', padx=2) row += 1 self.restrictModels = Tkinter.IntVar(parent) self.restrictModels.set(0) self.modelFrame = Tkinter.Frame(parent) self.molTexts = ["Restrict to models...", "Restrict to models:"] self.restrictCheckBox = Tkinter.Checkbutton(self.modelFrame, variable=self.restrictModels, text=self.molTexts[0], command=self._restrictModelsCB) self.restrictCheckBox.grid(row=0, column=0) from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(self.modelFrame, listbox_selectmode="extended") self.modelFrame.rowconfigure(0, weight=1) self.modelFrame.grid(row=row, column=0, columnspan=cols, sticky="nsw") parent.rowconfigure(row, weight=1) row += 1 self.inSelection = Tkinter.IntVar(parent) self.inSelection.set(0) f = Tkinter.Frame(parent) f.grid(row=row, column=0, columnspan=cols, sticky="w") Tkinter.Checkbutton(f, variable=self.inSelection, text="Only find H-bonds with", command=self._useSelChange).grid( row=0, column=0, sticky="e") self.selType = Pmw.OptionMenu(f, items=["at least one end", "exactly one end", "both ends"], initialitem=0, menubutton_state="disabled", labelpos="e", label_text="selected") self.selType.grid(row=0, column=1, sticky="w") row += 1 self.revealEnds = Tkinter.IntVar(parent) self.revealEnds.set(0) Tkinter.Checkbutton(parent, variable=self.revealEnds, text="If endpoint atom hidden, show endpoint residue" ).grid(row=row, column=0, columnspan=cols, sticky="w") row += 1 self.retainCurrent = Tkinter.IntVar(parent) self.retainCurrent.set(0) Tkinter.Checkbutton(parent, variable=self.retainCurrent, text="Retain currently displayed H-bonds").grid( row=row, column=0, columnspan=cols, sticky="w") row += 1 self.interSubmodel = Tkinter.IntVar(parent) self.interSubmodel.set(0) # comment out the below since there seems to be no # situations where cross-submodel-same-model hbonds # are interesting. If reading pdbrun files occurs, this # may change. #Tkinter.Checkbutton(parent, variable=self.interSubmodel, # text="Find H-bonds between submodels\n" # "having same principal model number" # ).grid(row=row, column=0, columnspan=cols, sticky="w") #row += 1 self.writeFile = Tkinter.IntVar(parent) self.writeFile.set(0) Tkinter.Checkbutton(parent, variable=self.writeFile, text="Write information to file").grid(row=row, column=0, columnspan=cols, sticky="w") self.fileName = None row += 1 self.writeLog = Tkinter.IntVar(parent) self.writeLog.set(0) Tkinter.Checkbutton(parent, variable=self.writeLog, text="Write information to reply log").grid(row=row, column=0, columnspan=cols, sticky="w") row += 1
class ColorSSDialog(ModelessDialog): title = "Color Secondary Structure" buttons = ('OK', 'Apply', 'Defaults', 'Close') name = "color by SS" help = "ContributedSoftware/colorss/colorss.html" def __init__(self): ModelessDialog.__init__(self) def fillInUI(self, parent): self.info = [ ("Helix", HELIX_COLOR, 'isHelix'), ("Strand", SHEET_COLOR, 'isSheet'), ("Other", OTHER_COLOR, None) ] header = Tkinter.Frame(parent) header.grid(row=0, column=0, sticky="nsew") parent.rowconfigure(0, weight=1) for i in range(len(self.info)): parent.columnconfigure(i, weight=1) from chimera.widgets import MoleculeScrolledListBox self.molListBox = MoleculeScrolledListBox(header, selectioncommand=lambda: self.configure( models=self.molListBox.getvalue()), listbox_selectmode="extended", labelpos="nw", label_text="Models") self.molListBox.grid(row=0, column=0, rowspan=len(self.info), sticky="nsew") for i in range(3): header.rowconfigure(i, weight=1) header.columnconfigure(0, weight=1) self.colorRibVar = Tkinter.IntVar(parent) self.colorRibVar.set(True) self.colorAtomVar = Tkinter.IntVar(parent) self.colorAtomVar.set(False) self.colorSurfVar = Tkinter.IntVar(parent) self.colorSurfVar.set(False) varFrame = Tkinter.Frame(parent) varFrame.grid(row=1, column=0) for i, info in enumerate([(self.colorRibVar, "Color ribbons"), (self.colorAtomVar, "Color atoms"), (self.colorSurfVar, "Color surfaces")]): var, text = info but = Tkinter.Checkbutton(varFrame, variable=var, text=text) but.grid(row=i, column=0, sticky='w') self.wells = [] self.actVars = [] from CGLtk.color.ColorWell import ColorWell from chimera.colorTable import getColorByName for row, ssInfo in enumerate(self.info): ssType, prefName, attrName = ssInfo rgba = prefs[prefName] if isinstance(rgba, basestring): rgba = getColorByName(rgba).rgba() well = ColorWell(header, color=rgba, noneOkay=True) self.wells.append(well) well.grid(row=row, column=2) actVar = Tkinter.IntVar(parent) actVar.set(True) self.actVars.append(actVar) Tkinter.Checkbutton(header, variable=actVar, text=ssType).grid(row=row, column=1, sticky='w') def Apply(self): colors = {} for i, ssInfo in enumerate(self.info): ssType, prefName, attrName = ssInfo rgba = self.wells[i].rgba prefs[prefName] = rgba if not self.actVars[i].get(): continue if rgba is None: color = None else: color = chimera.MaterialColor(*rgba) colors[attrName] = color mols = self.molListBox.getvalue() # only the protein residues are relevant... protein = {} for m in mols: for r in m.residues: ratoms = r.atomsMap if 'CA' not in ratoms: continue if len(ratoms) == 1: # possible CA-only model if ratoms['CA'][0].element.number == 6: protein[r] = True continue if 'O' in ratoms \ and 'N' in ratoms \ and 'C' in ratoms: protein[r] = True atomAttrs = [] resAttrs = [] if self.colorRibVar.get(): resAttrs = ["ribbonColor"] if self.colorAtomVar.get(): atomAttrs.append("color") if self.colorSurfVar.get(): atomAttrs.append("surfaceColor") from chimera.actions import changeSurfsFromCustom changeSurfsFromCustom(mols) if atomAttrs: def colorAttrs(item, res, attrs): for attrName, color in colors.items(): if attrName is None: if not (res.isHelix or res.isSheet): break elif getattr(res, attrName): break else: return for attr in attrs: setattr(item, attr, color) for m in mols: for a in m.atoms: res = a.residue if res not in protein: continue colorAttrs(a, res, atomAttrs) if resAttrs: for m in mols: for res in m.residues: if res not in protein: continue for attrName, color in colors.items(): if attrName is None: if not (res.isHelix or res.isSheet): break elif getattr(res, attrName): break else: continue for attr in resAttrs: setattr(res, attr, color) def configure(self, models=None): if models is not None: self.molListBox.setvalue(models) def Defaults(self): from prefs import defaultColors for i, ssInfo in enumerate(self.info): ssType, prefName, attrName = ssInfo self.wells[i].showColor(color=defaultColors[prefName])
class HBDialog(ModelessDialog): title = "H-Bond Parameters" buttons = ("OK", "Apply", "Close") default = 'OK' help = "ContributedSoftware/findhbond/findhbond.html" def fillInUI(self, parent): # inter/intra-model; slop; colors; models; replace current; # label # for removing labels in subsequent passes... # (use a selection so I don't have to track model closures) self.labelSelection = ItemizedSelection() self.labelMap = {} self.callbacks = [] row = 0 cols = 3 self.bondColorOption = ColorOption(parent, row, 'H-bond color', prefs[BOND_COLOR], None, noneOkay=0) class HBLineWidthOption(LineWidthOption): name = "Line width" balloon = "Width of pseudobonds (in pixels)" default = prefs[LINE_WIDTH] self.lineWidth = HBLineWidthOption(parent, row + 1, None, None, None, width=4, sticky='w') self.findMode = Pmw.RadioSelect(parent, buttontype='radiobutton', labelpos='n', pady=0, orient='vertical', label_text='Find these bonds:', hull_borderwidth=2, hull_relief='ridge') self.findMode.add('inter-model') self.findMode.add('intra-model') self.findMode.add('both') self.findMode.invoke('both') self.findMode.grid(row=row, column=2, rowspan=2) row += 2 self.relaxParams = RelaxParams(parent, prefs[RELAX_COLOR]) self.relaxParams.grid(row=row, columnspan=cols, sticky='nsew', padx=2) row += 1 self.restrictModels = Tkinter.IntVar(parent) self.restrictModels.set(0) self.modelFrame = Tkinter.Frame(parent) self.molTexts = ["Restrict to models...", "Restrict to models:"] self.restrictCheckBox = Tkinter.Checkbutton( self.modelFrame, variable=self.restrictModels, text=self.molTexts[0], command=self._restrictModelsCB) self.restrictCheckBox.grid(row=0, column=0) from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(self.modelFrame, listbox_selectmode="extended") self.modelFrame.rowconfigure(0, weight=1) self.modelFrame.grid(row=row, column=0, columnspan=cols, sticky="nsw") parent.rowconfigure(row, weight=1) row += 1 self.inSelection = Tkinter.IntVar(parent) self.inSelection.set(0) f = Tkinter.Frame(parent) f.grid(row=row, column=0, columnspan=cols, sticky="w") Tkinter.Checkbutton(f, variable=self.inSelection, text="Only find H-bonds with", command=self._useSelChange).grid(row=0, column=0, sticky="e") self.selType = Pmw.OptionMenu( f, items=["at least one end", "exactly one end", "both ends"], initialitem=0, menubutton_state="disabled", labelpos="e", label_text="selected") self.selType.grid(row=0, column=1, sticky="w") row += 1 self.revealEnds = Tkinter.IntVar(parent) self.revealEnds.set(0) Tkinter.Checkbutton( parent, variable=self.revealEnds, text="If endpoint atom hidden, show endpoint residue").grid( row=row, column=0, columnspan=cols, sticky="w") row += 1 self.retainCurrent = Tkinter.IntVar(parent) self.retainCurrent.set(0) Tkinter.Checkbutton(parent, variable=self.retainCurrent, text="Retain currently displayed H-bonds").grid( row=row, column=0, columnspan=cols, sticky="w") row += 1 self.interSubmodel = Tkinter.IntVar(parent) self.interSubmodel.set(0) # comment out the below since there seems to be no # situations where cross-submodel-same-model hbonds # are interesting. If reading pdbrun files occurs, this # may change. #Tkinter.Checkbutton(parent, variable=self.interSubmodel, # text="Find H-bonds between submodels\n" # "having same principal model number" # ).grid(row=row, column=0, columnspan=cols, sticky="w") #row += 1 self.writeFile = Tkinter.IntVar(parent) self.writeFile.set(0) Tkinter.Checkbutton(parent, variable=self.writeFile, text="Write information to file").grid( row=row, column=0, columnspan=cols, sticky="w") self.fileName = None row += 1 self.writeLog = Tkinter.IntVar(parent) self.writeLog.set(0) Tkinter.Checkbutton(parent, variable=self.writeLog, text="Write information to reply log").grid( row=row, column=0, columnspan=cols, sticky="w") row += 1 def addCallback(self, callback): self.callbacks.append(callback) def Apply(self): states = {} for but in self.buttonWidgets.values(): states[but] = but.cget('state') but.config(state='disabled') try: self._Apply() finally: for but, state in states.items(): but.config(state=state) for cb in self.callbacks: try: cb() except: replyobj.reportException("H-bond callback function") self.callbacks = [] def _Apply(self): intramodel = intermodel = 1 cursel = self.findMode.getcurselection() if cursel == 'inter-model': intramodel = 0 elif cursel == 'intra-model': intermodel = 0 distSlop = 0.0 angleSlop = 0.0 twoColors = False relax = self.relaxParams.relaxConstraints rc = self.relaxParams.relaxColor if relax: distSlop = self.relaxParams.relaxDist angleSlop = self.relaxParams.relaxAngle if self.relaxParams.useRelaxColor: twoColors = True prefs[RELAX_COLOR] = rc.rgba if self.inSelection.get(): selRestrict = ["any", "cross", "both"][self.selType.index(Pmw.SELECT)] else: selRestrict = None lineWidth = self.lineWidth.get() prefs[LINE_WIDTH] = lineWidth bc = self.bondColorOption.get() prefs[BOND_COLOR] = bc.rgba if self.writeFile.get(): saveFile = '-' else: saveFile = None if self.restrictModels.get(): models = self.molList.getvalue() if not models: raise ValueError, "No restriction models chosen" else: models = None from base import createHBonds createHBonds(models=models, intramodel=intramodel, intermodel=intermodel, relax=relax, distSlop=distSlop, angleSlop=angleSlop, twoColors=twoColors, selRestrict=selRestrict, lineWidth=lineWidth, saveFile=saveFile, log=self.writeLog.get(), retainCurrent=self.retainCurrent.get(), reveal=self.revealEnds.get(), color=bc, slopColor=rc) def Close(self): self.callbacks = [] ModelessDialog.Close(self) def _restrictModelsCB(self): restrict = self.restrictModels.get() self.restrictCheckBox.config(text=self.molTexts[restrict]) if restrict: self.molList.grid(row=0, column=1, sticky="ns") else: self.molList.grid_forget() def _useSelChange(self): if self.inSelection.get(): self.selType.component("menubutton").config(state="normal") else: self.selType.component("menubutton").config(state="disabled")
class Interface(ModelessDialog): title = "Compute Surface Area and Volume" help = "ContributedSoftware/surfvol/surfvol.html" def fillInUI(self, parent): self.notebook = Pmw.NoteBook(parent) self.notebook.pack(fill="both", expand=True) page = self.notebook.add("Molecules") self.molChooser = MoleculeScrolledListBox(page, listbox_selectmode="extended", autoselect="single") self.molChooser.pack(fill="both", expand=True) page = self.notebook.add("Chains") self.chainChooser = MoleculeChainScrolledListBox(page, listbox_selectmode="extended", autoselect="single") self.chainChooser.pack(fill="both", expand=True) titles = self.Servers.keys() titles.sort() self.serverChooser = Pmw.OptionMenu(parent, labelpos="w", label_text="Compute:", items=titles, command=self._changeServer) self.serverChooser.pack(fill="x", expand=False) self.paramHolder = Tkinter.Frame(parent, padx=10, pady=2) self.paramHolder.pack(fill="x", expand=False) self.paramFrames = {} for name, val in self.Servers.iteritems(): self.paramFrames[name] = val[2](self, self.paramHolder) self.propertyName = Pmw.EntryField(parent, labelpos="w", label_text="As attribute:", value=self.Servers[titles[0]][0], validate=self._validatePropName) self.propertyName.pack(fill="x", expand=False) self.outputOptions = Pmw.RadioSelect(parent, pady=0, buttontype="checkbutton", orient="vertical") self.outputOptions.pack(fill="x", expand=False) self.outputOptions.add("rba", text="Open Render/Select by Attribute") self.outputOptions.add("save", text="Save server output to file") self.outputOptions.add("show", text="Show server output in browser") self.outputOptions.setvalue(["rba"]) self._changeServer(titles[0]) def _changeServer(self, name): self.propertyName.setvalue(self.Servers[name][0]) for n, (frame, parts) in self.paramFrames.iteritems(): if n == name: frame.pack(fill="x", expand=True) else: frame.forget() def _validatePropName(self, text): if len(text) == 0: return Pmw.PARTIAL if text[0] not in NameFirstChar: return Pmw.ERROR for c in text[1:]: if c not in NameChar: return Pmw.ERROR return Pmw.OK def Apply(self): if not self.propertyName.valid(): raise chimera.UserError( "Please enter valid attribute name") propName = self.propertyName.getvalue() pageName = self.notebook.getcurselection() if pageName == "Molecules": target = self.molChooser.getvalue() elif pageName == "Chains": target = self.chainChooser.getvalue() if not target: raise chimera.UserError( "Please select molecule or chain") opts = self.outputOptions.getvalue() rba = "rba" in opts save = "save" in opts show = "show" in opts serverName = self.serverChooser.getcurselection() f = self.Servers[serverName][1] parts = self.paramFrames[serverName][1] opts = self.Servers[serverName][3](self, parts) output = f(target, opts, propName, rba) if save: _save(output, show) elif show: # create temporary file and invoke browser from OpenSave import osTemporaryFile filename = osTemporaryFile(suffix=".html") f = open(filename, "w") f.write(output) f.close() import urllib from chimera import help help.display("file:" + urllib.pathname2url(filename)) _paramMsmsParams = [ ( "Surface probe size:", "msms_probe", ( ( "1.3", "1.3" ), ( "1.4", "1.4" ), ( "1.5", "1.5" ), ( "1.6", "1.6" ) ), "1.5" ), ( "Atoms to use:", "msms_atoms", ( ( "No Hetatms", "HETATM" ), ( "Atoms + Hetatms", "ZZZZZZ" ), ( "All atoms except waters", "HOH" ) ), "No Hetatms" ), ] _paramGersteinSurfaceParams = [ ( "Surface probe size:", "surf_Gerstein_probe", ( ( "1.3", "1.3" ), ( "1.4", "1.4" ), ( "1.5", "1.5" ), ( "1.6", "1.6" ) ), "1.4" ), ( "Atoms to use:", "surf_Gerstein_atoms", ( ( "No Hetatms", "HETATM" ), ( "Atoms + Hetatms", "ZZZZZZ" ), ( "All atoms except waters", "HOH" ) ), "All atoms except waters" ), ] _paramGersteinVolumeParams = [ ( "Method:", "vol_Gerstein_method", ( ( "Normal Voronoi", "1" ), ( "Method B", "2" ), ( "Radical Plane", "3" ), ( "Modified Method B", "4" ) ), "Method B" ), ( "Radii:", "vol_Gerstein_radii", ( ( "Chothia Radii", "" ), ( "Richards Radii", "-RichardsRadii" ) ), "Chothia Radii" ), ( "Atoms to use:", "vol_Gerstein_atoms", ( ( "No Hetatms", "HETATM" ), ( "Atoms + Hetatms", "ZZZZZZ" ), ( "All atoms except waters", "HOH" ) ), "No Hetatms" ), ] def _paramMakeMsms(self, group): return self._paramMake(group, self._paramMsmsParams) def _paramGetMsms(self, parts): return self._paramGet(parts, self._paramMsmsParams) def _paramMakeGersteinSurface(self, group): return self._paramMake(group, self._paramGersteinSurfaceParams) def _paramGetGersteinSurface(self, parts): return self._paramGet(parts, self._paramGersteinSurfaceParams) def _paramMakeGersteinVolume(self, group): return self._paramMake(group, self._paramGersteinVolumeParams) def _paramGetGersteinVolume(self, parts): return self._paramGet(parts, self._paramGersteinVolumeParams) def _paramMake(self, parent, params): g = Pmw.Group(parent, tag_text="Parameters") parts = [] for label, cgiTag, items, default in params: m = Pmw.OptionMenu(g.interior(), labelpos="w", label_text=label, items=[ item[0] for item in items ]) m.setvalue(default) m.pack(fill="x", expand=False) parts.append(m) Pmw.alignlabels(parts) return g, parts def _paramGet(self, parts, params): args = [] for i, m in enumerate(parts): sel = m.getvalue() label, cgiTag, items, default = params[i] for name, value in items: if name == sel: args.append((cgiTag, None, value)) break else: raise ChimeraError("unexpected option value") return args Servers = { "Surface Area (MSMS)": ( "msmsArea", StrucTools.msms, _paramMakeMsms, _paramGetMsms, ), "Accessible Surface (Gerstein)": ( "accessibleSurface", StrucTools.surface, _paramMakeGersteinSurface, _paramGetGersteinSurface, ), "Voronoi Volume (Gerstein)": ( "voronoiVolume", StrucTools.volume, _paramMakeGersteinVolume, _paramGetGersteinVolume, ), }
def fillInUI(self, parent): # inter/intra-model; slop; colors; models; replace current; # label # for removing labels in subsequent passes... # (use a selection so I don't have to track model closures) self.labelSelection = ItemizedSelection() self.labelMap = {} self.callbacks = [] row = 0 cols = 3 self.bondColorOption = ColorOption(parent, row, 'H-bond color', prefs[BOND_COLOR], None, noneOkay=0) class HBLineWidthOption(LineWidthOption): name = "Line width" balloon = "Width of pseudobonds (in pixels)" default = prefs[LINE_WIDTH] self.lineWidth = HBLineWidthOption(parent, row + 1, None, None, None, width=4, sticky='w') self.findMode = Pmw.RadioSelect(parent, buttontype='radiobutton', labelpos='n', pady=0, orient='vertical', label_text='Find these bonds:', hull_borderwidth=2, hull_relief='ridge') self.findMode.add('inter-model') self.findMode.add('intra-model') self.findMode.add('both') self.findMode.invoke('both') self.findMode.grid(row=row, column=2, rowspan=2) row += 2 self.relaxParams = RelaxParams(parent, prefs[RELAX_COLOR]) self.relaxParams.grid(row=row, columnspan=cols, sticky='nsew', padx=2) row += 1 self.restrictModels = Tkinter.IntVar(parent) self.restrictModels.set(0) self.modelFrame = Tkinter.Frame(parent) self.molTexts = ["Restrict to models...", "Restrict to models:"] self.restrictCheckBox = Tkinter.Checkbutton( self.modelFrame, variable=self.restrictModels, text=self.molTexts[0], command=self._restrictModelsCB) self.restrictCheckBox.grid(row=0, column=0) from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(self.modelFrame, listbox_selectmode="extended") self.modelFrame.rowconfigure(0, weight=1) self.modelFrame.grid(row=row, column=0, columnspan=cols, sticky="nsw") parent.rowconfigure(row, weight=1) row += 1 self.inSelection = Tkinter.IntVar(parent) self.inSelection.set(0) f = Tkinter.Frame(parent) f.grid(row=row, column=0, columnspan=cols, sticky="w") Tkinter.Checkbutton(f, variable=self.inSelection, text="Only find H-bonds with", command=self._useSelChange).grid(row=0, column=0, sticky="e") self.selType = Pmw.OptionMenu( f, items=["at least one end", "exactly one end", "both ends"], initialitem=0, menubutton_state="disabled", labelpos="e", label_text="selected") self.selType.grid(row=0, column=1, sticky="w") row += 1 self.revealEnds = Tkinter.IntVar(parent) self.revealEnds.set(0) Tkinter.Checkbutton( parent, variable=self.revealEnds, text="If endpoint atom hidden, show endpoint residue").grid( row=row, column=0, columnspan=cols, sticky="w") row += 1 self.retainCurrent = Tkinter.IntVar(parent) self.retainCurrent.set(0) Tkinter.Checkbutton(parent, variable=self.retainCurrent, text="Retain currently displayed H-bonds").grid( row=row, column=0, columnspan=cols, sticky="w") row += 1 self.interSubmodel = Tkinter.IntVar(parent) self.interSubmodel.set(0) # comment out the below since there seems to be no # situations where cross-submodel-same-model hbonds # are interesting. If reading pdbrun files occurs, this # may change. #Tkinter.Checkbutton(parent, variable=self.interSubmodel, # text="Find H-bonds between submodels\n" # "having same principal model number" # ).grid(row=row, column=0, columnspan=cols, sticky="w") #row += 1 self.writeFile = Tkinter.IntVar(parent) self.writeFile.set(0) Tkinter.Checkbutton(parent, variable=self.writeFile, text="Write information to file").grid( row=row, column=0, columnspan=cols, sticky="w") self.fileName = None row += 1 self.writeLog = Tkinter.IntVar(parent) self.writeLog.set(0) Tkinter.Checkbutton(parent, variable=self.writeLog, text="Write information to reply log").grid( row=row, column=0, columnspan=cols, sticky="w") row += 1
class WritePDBdialog(SaveModeless): keepShown = SaveModeless.default help = "UsersGuide/savemodel.html" name = "write PDB" def __init__(self): self.prefs = preferences.addCategory("write PDB dialog", preferences.HiddenCategory, optDict={"multiSavePDB": "multiple"}) self.haveTraj = False SaveModeless.__init__(self, clientPos='s', clientSticky='ewns', filters=[("PDB", "*.pdb", ".pdb")]) openModels.addAddHandler(self._modelsChange, None), openModels.addRemoveHandler(self._modelsChange, None) self._modelsChange() def configure(self, models=None, refreshList=True, selOnly=None): if models is not None: if len(models) > 1: name = "Multiple Models " elif models: name = models[0].name + " " else: name = "" self._toplevel.title("Save %sas PDB File" % name) if refreshList: self.modelList.setvalue(models) self._trajCheck() if len(models) > 1: self.multiSaveMenu.grid(row=self._msmRow, column=0, sticky='w') else: self.multiSaveMenu.grid_forget() if selOnly is not None: self.selOnlyVar.set(selOnly) def fillInUI(self, parent): SaveModeless.fillInUI(self, parent) row = 0 from chimera.widgets import MoleculeScrolledListBox, \ ModelOptionMenu self.modelList = MoleculeScrolledListBox(self.clientArea, labelpos='w', label_text="Save models:", listbox_selectmode='extended', selectioncommand=lambda: self.configure( self.modelList.getvalue(), refreshList=False)) self.modelList.grid(row=row, column=0, sticky='nsew') self.clientArea.rowconfigure(row, weight=1) self.clientArea.columnconfigure(0, weight=1) row += 1 import Tkinter, Pmw self.dispOnlyVar = Tkinter.IntVar(parent) self.dispOnlyVar.set(False) Tkinter.Checkbutton(self.clientArea, variable=self.dispOnlyVar, text="Save displayed atoms only").grid(row=row, column=0, sticky='w') row += 1 self.selOnlyVar = Tkinter.IntVar(parent) self.selOnlyVar.set(False) Tkinter.Checkbutton(self.clientArea, variable=self.selOnlyVar, text="Save selected atoms only").grid(row=row, column=0, sticky='w') row += 1 self.saveRelativeVar = Tkinter.IntVar(parent) self.saveRelativeVar.set(False) self.relativeFrame = f = Tkinter.Frame(self.clientArea) Tkinter.Checkbutton(f, variable=self.saveRelativeVar, text="Save relative to model:" ).grid(row=0, column=0, sticky='e') self.relModelMenu = ModelOptionMenu(f) self.relModelMenu.grid(row=0, column=1, sticky='w') self.saveUntransformedVar = Tkinter.IntVar(parent) self.saveUntransformedVar.set(True) self.untransformedButton = Tkinter.Checkbutton(self.clientArea, variable=self.saveUntransformedVar, text="Use untransformed coordinates") self._rfRow = row row += 1 self.frameSave = Pmw.OptionMenu(self.clientArea, labelpos='w', label_text="Save", initialitem="current frame", items=["current frame", "all frames"]) # not always shown; remember row number self._fsRow = row row += 1 from chimera import dialogs self.labelMap = { "single": "a single file", "multiple": "multiple files [appending model number]" } preferred = self.labelMap[self.prefs["multiSavePDB"]] self.multiSaveMenu = Pmw.OptionMenu(self.clientArea, labelpos='w', label_text="Save multiple models in", initialitem=preferred, items=self.labelMap.values()) # not always shown; remember row number self._msmRow = row row += 1 def map(self, *args): self.handler = triggers.addHandler("CoordSet", self._trajCheck, None) self._trajCheck() def unmap(self, *args): triggers.deleteHandler("CoordSet", self.handler) self.handler = None def Apply(self): from chimera import dialogs selOnly = self.selOnlyVar.get() paths = self.getPaths() if not paths: replyobj.error('No save location chosen.\n') return path = paths[0] models = self.modelList.getvalue() if not models: replyobj.error("No models chosen to save.\n") return if len(openModels.listIds()) > 1: if self.saveRelativeVar.get(): relModel = self.relModelMenu.getvalue() else: relModel = None else: if self.saveUntransformedVar.get(): relModel = models[0] else: relModel = None if self.haveTraj and self.frameSave.getvalue() == "all frames": allFrames=True else: allFrames=False import Midas if len(models) < 2: replyobj.status("Writing %s to %s\n" % (models[0].name, path)) Midas.write(models, relModel, path, allFrames=allFrames, dispOnly=self.dispOnlyVar.get(), selOnly=selOnly) replyobj.status("Wrote %s to %s\n" % (models[0].name, path)) return saveOpt = self.multiSaveMenu.getvalue() for key, value in self.labelMap.items(): if saveOpt == value: break self.prefs["multiSavePDB"] = key # write multiple models to multiple files if key == "multiple": if path.endswith(".pdb"): start, end = path[:-4], ".pdb" else: start, end = path, "" for m in models: modelPath = start + m.oslIdent()[1:] + end replyobj.status("Writing %s (%s) to %s\n" % (m.name, m.oslIdent(), modelPath)) Midas.write(m, relModel, modelPath, allFrames=allFrames, dispOnly=self.dispOnlyVar.get(), selOnly=selOnly) replyobj.status("Wrote %s (%s) to %s\n" % (m.name, m.oslIdent(), modelPath)) return # write multiple models to single file replyobj.status("Writing multiple models to %s\n" % path) Midas.write(models, relModel, path, allFrames=allFrames, dispOnly=self.dispOnlyVar.get(), selOnly=selOnly) replyobj.status("Wrote multiple models to %s\n" % path) def _modelsChange(self, *args): # can't query listbox, since it hangs off of same trigger if len(openModels.listIds()) > 1: self.untransformedButton.grid_forget() self.relativeFrame.grid(row=self._rfRow, column=0, sticky='w') else: self.relativeFrame.grid_forget() self.untransformedButton.grid(row=self._rfRow, column=0, sticky='w') def _trajCheck(self, *args): haveTraj = False for m in self.modelList.getvalue(): if len(m.coordSets) > 1: haveTraj = True break if haveTraj == self.haveTraj: return self.haveTraj = haveTraj if self.haveTraj: self.frameSave.grid(row=self._fsRow, column=0, sticky='w') else: self.frameSave.grid_forget()
class CombineDialog(ModelessDialog): title = "Copy/Combine Molecular Models" help = "UsersGuide/modelpanel.html#combine" def __init__(self, models=None): self.initModels = models ModelessDialog.__init__(self) def fillInUI(self, parent): from chimera.widgets import MoleculeScrolledListBox self.molListBox = MoleculeScrolledListBox(parent, listbox_selectmode='extended', labelpos='w', label_text="Molecules to combine/copy:") if self.initModels: self.molListBox.setvalue(self.initModels) self.molListBox.grid(row=0, column=0, columnspan=2, sticky="nsew") parent.rowconfigure(0, weight=1) parent.columnconfigure(1, weight=1) from chimera.tkoptions import StringOption, IntOption self.molNameEntry = StringOption(parent, 1, "New model's" " name", "combination", None) curIDs = set([i1 for i1, i2 in openModels.listIds()]) mid = 0 while mid in curIDs: mid += 1 self.modelID = IntOption(parent, 2, "New model's ID", mid, None) from chimera.widgets import MoleculeOptionMenu self.refMolMenu = MoleculeOptionMenu(parent, labelpos='w', label_text="Coordinate system of:", initialitem=self.initModels[0]) self.refMolMenu.grid(row=3, column=0, columnspan=2, sticky='w') import Pmw chb = self.chainHandlingButtons = Pmw.RadioSelect(parent, buttontype="radiobutton", labelpos='w', label_text="If original molecules have duplicate\n" "single-letter chain IDs, then:", orient="vertical") self.buttonTexts = ["rename them uniquely", "retain them (residues may be renumbered)"] for bt in self.buttonTexts: chb.add(bt) chb.setvalue(self.buttonTexts[0]) chb.grid(row=4, column=0, columnspan=2) import Tkinter self.closeModelsVar = Tkinter.IntVar(parent) self.closeModelsVar.set(False) Tkinter.Checkbutton(parent, text="Close source models", variable=self.closeModelsVar).grid( row=5, column=0, columnspan=2) def Apply(self): mols = self.molListBox.getvalue() from chimera import UserError if not mols: self.enter() raise UserError("Must specify at least one molecular" " model to combine/copy") from chimera import suppressNewMoleculeProcessing, \ restoreNewMoleculeProcessing suppressNewMoleculeProcessing() newChainIDs = (self.chainHandlingButtons.getvalue() == self.buttonTexts[0]) refMol = self.refMolMenu.getvalue() from Combine import combine, CombineError try: m = combine(mols, refMol, newChainIDs=newChainIDs, log=True) except CombineError, v: restoreNewMoleculeProcessing() self.enter() raise UserError(v) m.name = self.molNameEntry.get() openModels.add([m], baseId=self.modelID.get(), shareXform=False) m.openState.xform = refMol.openState.xform restoreNewMoleculeProcessing() if self.closeModelsVar.get(): openModels.close(mols)
class FitOpt_Dialog(ModelessDialog): # Title of FitOpt plugin title = 'FitOpt Flexible Fitting' # Name of FitOpt plugin name = 'FitOpt' # Buttons of FitOpt GUI buttons = ('Fit', 'Results', 'Close') # Path of help guide of FitOpt plugin help = ('fitopt.html', FitOpt) # Name of the folder where FitOpt plugin is located plugin_folder = 'FitOpt/' # Path of the process of FitOpt fitopt = plugin_folder + 'fitopt' # Variable to keep the workspace cwd = None # Name of the fitted pdb generated after FitOpt process fitted_molecule = "fitopt_fitted.pdb" # Name of the trajectory movie imovie = plugin_folder + "fitopt_movie.pdb" # --------------------------- # FitOpt Chimera Commands # FitOpt in Chimera indicator fitopt_chimera_opt = "--chimera" # More PDBs fitopt_chimera_morepdbs = "--morepdbs" # PDB Reference fitopt_chimera_pdb_ref = "--pdb_ref" fitopt_chimera_pdb_ref_val = None # Trajectory (movie) fitopt_chimera_t = "-t" # Fixing diagonalization fitopt_chimera_r = "-r" fitopt_chimera_r_val = "0" # Rediagonalization fitopt_chimera_re = "--rediag" fitopt_chimera_re_val = "0" # Coarse-grained model fitopt_chimera_m = "-m" fitopt_chimera_m_val = "2" # Modes range fitopt_chimera_n = "-n" fitopt_chimera_n_val = "0.05" # Advanced commands fitopt_chimera_adv_commands = [] import tkFont arialF = tkFont.Font(family='Arial', size=8) arialBondF = tkFont.Font(family='Arial', size=7, weight=tkFont.BOLD) # ------------------------------------------------- # Master function for dialog contents # def fillInUI(self, parent): t = parent.winfo_toplevel() self.toplevel_widget = t t.withdraw() parent.columnconfigure(0, weight=1) row = 0 import Tkinter from CGLtk import Hybrid from VolumeViewer import Volume_Menu ff = Tkinter.Frame(parent) ff.grid(row=row, column=0, sticky='w') row = row + 1 # Map selection (only Volumes) fm = Volume_Menu(ff, 'Map: ') fm.frame.grid(row=0, column=0, sticky='w') self.map_menu = fm # Resolution rs = Hybrid.Entry(ff, 'Resolution ', 5) rs.frame.grid(row=0, column=1, sticky='w') self.resolution = rs.variable # Cut-off co = Hybrid.Entry(ff, 'Cut-off level ', 10) co.frame.grid(row=0, column=2, sticky='w') self.cutoff = co.variable self.save_button = Tkinter.Button(ff, text="From Volume Viewer", font=self.arialBondF, height=1, command=self.get_cutoff) self.save_button.grid(row=0, column=3, sticky='w') hf = Tkinter.Frame(parent) hf.grid(row=row, column=0, sticky='w') row += 1 # Space msg = Tkinter.Label(hf, anchor='w', justify='left') msg.grid(row=2, column=0, sticky='ew') row = row + 1 self.message_label = msg # PDB's panel self.pdbs = Tkinter.Frame(parent) self.pdbs.grid(row=3, column=0, sticky='ew') self.pdbs.columnconfigure(1, weight=1) from chimera.widgets import MoleculeScrolledListBox, \ ModelOptionMenu self.modelList = MoleculeScrolledListBox( self.pdbs, labelpos='nw', label_text="Target PDBs to be fitted:", listbox_selectmode='extended', listbox_height=11) self.modelList.grid(row=row, column=0, sticky='nsew') self.pdbs.rowconfigure(row, weight=1) self.pdbs.columnconfigure(0, weight=1) self.modelList1 = MoleculeScrolledListBox( self.pdbs, labelpos='nw', label_text="Target PDBs to be fixed:", listbox_selectmode='extended', listbox_height=11) self.modelList1.grid(row=row, column=1, sticky='nsew') self.pdbs.rowconfigure(row, weight=1) self.pdbs.columnconfigure(0, weight=1) row += 1 # Disable Results panel at first self.results_button = self.buttonWidgets['Results'] self.results_button['state'] = 'disabled' # --------------------------------------------------------------------------- # Shows a message in FitOpt Plugin # def message(self, text): self.message_label['text'] = text self.message_label.update_idletasks() # --------------------------------------------------------------------------- # Map chosen to fit into base map. # def fit_map(self): m = self.object_menu.getvalue() from VolumeViewer import Volume if isinstance(m, Volume): return m return None # --------------------------------------------------------------------------- # Atoms chosen in dialog for fitting. # def fit_atoms(self): m = self.object_menu.getvalue() if m == 'selected atoms': from chimera import selection atoms = selection.currentAtoms() return atoms from chimera import Molecule if isinstance(m, Molecule): return m.atoms return [] # --------------------------------------------------------------------------- # Gets the parameter values introduced by the user # def get_options_chimera(self): # Model type if 'atom' in self.model_type.get(): self.fitopt_chimera_m_val = "2" elif '3BB2R' in self.model_type.get(): self.fitopt_chimera_m_val = "1" else: self.fitopt_chimera_m_val = "0" # Number of models if len(self.number_models.get()) > 0: if self.mode_percentage.get() == 1: mode = float(self.number_models.get()) / 100 if mode >= 0 and mode <= 1: self.fitopt_chimera_n_val = str(mode) else: self.fitopt_chimera_n_val = str(self.number_models.get()) # Fix DoF if '50' in self.fixing.variable.get(): self.fitopt_chimera_r_val = "0.5" elif '75' in self.fixing.variable.get(): self.fitopt_chimera_r_val = "0.75" elif '90' in self.fixing.variable.get(): self.fitopt_chimera_r_val = "0.9" # Rediagonalization if '0.1' in self.rediag.variable.get(): self.fitopt_chimera_re_val = "0.1" elif '0.5' in self.rediag.variable.get(): self.fitopt_chimera_re_val = "0.5" elif '1' in self.rediag.variable.get(): self.fitopt_chimera_re_val = "0.9" # Advanced commands if len(self.adv_commands.get()) > 0: self.fitopt_chimera_adv_commands = self.adv_commands.get().split() # --------------------------------------------------------------------------- # Performs the FitOpt process # def Fit(self): from chimera.replyobj import info models = self.modelList.getvalue() models1 = self.modelList1.getvalue() if not models or not models1: info('\n') replyobj.error("No models chosen to save.\n") return else: info('\n') info('PDBs seleccionados a ajustar') for m in models: info('\n') info(' - ' + m.name) info('\n') info('\n') info('PDBs seleccionados a fijar') for m in models1: info('\n') info(' - ' + m.name) info('\n') # # If a fitting is performed when Results panel is active, close it # for widget in self.mmf.winfo_children(): # widget.destroy() # self.results_panel.set(False) # # # Validation of the parameters introduced by the user # if self.check_models() is False: # return # # # Disable Fit, and Close buttons when FitOpt process is performed # self.disable_process_buttons() # # # Retrieve the full plugin path # self.plugin_path = __file__[:__file__.index(self.plugin_folder)] # # # ----------------------- # # Calling FitOpt process # # ----------------------- # from subprocess import STDOUT, PIPE, Popen # import os, sys # # # Get the full path of FitOpt process # command = self.plugin_path + self.fitopt # # Set the workspace # self.cwd = self.plugin_path + self.plugin_folder # # # PDB selected in the menu # pdbSelected = self.object_menu.getvalue() # # Map selected in the menu # mapSelected = self.map_menu.volume() # # # Get options values # self.get_options_chimera() # # # Retrieve the full command to perform the fitting: fitopt + arguments # cmd = [command, pdbSelected.openedAs[0], mapSelected.openedAs[0], self.resolution.get(), self.cutoff.get(), # self.fitopt_chimera_m, self.fitopt_chimera_m_val, # self.fitopt_chimera_t, # self.fitopt_chimera_r, self.fitopt_chimera_r_val, # self.fitopt_chimera_re, self.fitopt_chimera_re_val, # self.fitopt_chimera_morepdbs, # self.fitopt_chimera_n, self.fitopt_chimera_n_val] + self.fitopt_chimera_adv_commands # # # Execute the command with the respective arguments creating pipes between the process and Chimera # # Pipes will be associated to the standard output and standard error required to show the process log # # in the window # from chimera.replyobj import info # info('\n') # info('Executing the FitOpt command:') # info('\n') # info(' '.join(cmd)) # fitopt_process = Popen(cmd, stdout=PIPE, stderr=PIPE, cwd=self.cwd, universal_newlines=True) # # # Text widget for process log that will showthe standard output of the process # from Tkinter import * # root = Tk() # root.wm_title("FitOpt Process Log") # S = Scrollbar(root) # T = Text(root, height=30, width=85) # S.pack(side=RIGHT, fill=Y) # T.pack(side=LEFT, fill=Y) # S.config(command=T.yview) # T.config(yscrollcommand=S.set) # # # Read first line # line = fitopt_process.stdout.readline() # # Variables to check the process status and show its output in a friendly format to the user # iter = False # model_iter = False # index_before_last_print = None # first_ite_sec = True # # # Continue reading the standard output until FitOpt is finished # # If the current line is an iteration for a model, replace in the widget the last showed # # If it is a new model or is part of the FitOpt process, inserts the line at the end of the widget # while line: # if len(line.strip()) == 0: # line = fitopt_process.stdout.readline() # continue # if iter is False or (iter is True and 'NMA' in line): # T.insert(END, line) # model_iter = True # elif iter is True and 'sec' in line: # if first_ite_sec is True: # T.insert(END, line) # model_iter = True # else: # T.delete(index_before_last_print + "-1c linestart", index_before_last_print) # T.insert(END, line) # first_ite_sec = False # elif model_iter is True: # index_before_last_print = T.index(END) # T.insert(END, line) # model_iter = False # elif iter is True and 'sec' not in line: # T.delete(index_before_last_print + "-1c linestart", index_before_last_print) # T.insert(END, line) # T.update() # T.yview(END) # line = fitopt_process.stdout.readline() # if ('NMA_time' in line and 'Score' in line): # iter = True # if 'sec' in line and iter is True: # first_ite_sec = True # model_iter = True # if index_before_last_print is not None: # T.delete(index_before_last_print + "-1c linestart", index_before_last_print) # index_before_last_print = T.index(END) # if 'Convergence' in line: # iter = False # # T.insert(END, "\n\n --> FitOpt Process has finished. Check 'Results' button to visualize solution. <--\n") # T.update() # T.yview(END) # # # When FitOpt process is finished, the results are set into the Results panel... # self.fill_results() # # and the plugin buttons are enabled again # self.enable_process_buttons() # --------------------------------------------------------------------------- # Fill the Results panel with the corresponding components # def fill_results(self): # Button to switch between the original molecule and the fitted one with FitOpt import Tkinter self.save_button = Tkinter.Button(self.mmf, text="Show fitted molecule", command=self.switch_original_fitted) self.save_button.grid(row=0, column=0, sticky='w') # Button to copy to the Model Panel the fitted molecule self.save_fitted = Tkinter.Button(self.mmf, text="Copy fitted molecule", command=self.save_fitted_molecule) self.save_fitted.grid(row=0, column=1, sticky='w') self.save_fitted['state'] = 'disabled' # Button to open the MD Movie created by iMODTFIT with the model trajectories self.open_md_movie = Tkinter.Button(self.mmf, text="Open movie", command=self.open_movie) self.open_md_movie.grid(row=1, column=0, sticky='w') # --------------------------------------------------------------------------- # Switchs between the original molecule and the fitted one with FitOpt # def switch_original_fitted(self): if self.save_button["text"] == "Show fitted molecule": # Show fitted molecule self.show_fitted_molecule(True) self.save_button["text"] = "Show original molecule" self.save_fitted['state'] = 'normal' else: # Show original molecule self.show_fitted_molecule(False) self.save_button["text"] = "Show fitted molecule" self.save_fitted['state'] = 'disabled' # --------------------------------------------------------------------------- # Reads the coordinates of the fitted molecule and updates the original # molecule position to show the fitting made by FitOpt # def show_fitted_molecule(self, pdb_name): from chimera.replyobj import info info('\n') info('Showing fitted ' + pdb_name + ' molecule') # --------------------------------------------------------------------------- # Makes a copy to the Model Panel of the fitted molecule # def save_fitted_molecule(self): # Get opened molecule (the one selected in the menu) m = self.object_menu.getvalue() # Make copy using the copy_molecule native functionality from Chimera from Molecule import copy_molecule mc = copy_molecule(m) # Set copy name mc.name = m.name.split('.')[0] + '_fitopt.pdb' # Add copy to list of open models chimera.openModels.add([mc]) # --------------------------------------------------------------------------- # Opens the MD movie created by iMODTFIT with the model trajectories # def open_movie(self): # Import the native dialog MovieDialog from Chimera from Movie.gui import MovieDialog # import the loadEnsemble native functionality from Chimera to load the movie from Trajectory.formats.Pdb import loadEnsemble # Load the movie created by FitOpt movie = self.plugin_path + self.imovie loadEnsemble(("single", movie), None, None, MovieDialog) # --------------------------------------------------------------------------- # Disables the the FitOpt GUI Fit, Close and Results buttons # def disable_process_buttons(self): self.fit_button = self.buttonWidgets['Fit'] self.fit_button['state'] = 'disabled' self.options_button['state'] = 'disabled' self.close_ch_button = self.buttonWidgets['Close'] self.close_ch_button['state'] = 'disabled' self.results_button['state'] = 'disabled' # --------------------------------------------------------------------------- # Enables the the FitOpt GUI Fit, Close and Results buttons # def enable_process_buttons(self): self.fit_button = self.buttonWidgets['Fit'] self.fit_button['state'] = 'normal' self.options_button['state'] = 'normal' self.close_ch_button = self.buttonWidgets['Close'] self.close_ch_button['state'] = 'normal' self.results_button['state'] = 'normal' # --------------------------------------------------------------------------- # Results button is pressed # def Results(self): self.results_panel.set(not self.results_panel.get()) # ----------------------------------------------------------------------------- # Gets the cut-off level value from the Volume Viewer dialog # Useful when the user does not know an appropiate resolution and plays # with the map density in this dialog. # def get_cutoff(self): # validate if the map is loaded/choosed bmap = self.map_menu.data_region() if bmap is None: self.message('Choose map.') return # Import the native dialog Volume Viewer from Chimera from chimera import dialogs vdlg = dialogs.find("volume viewer") # Get the cut-off level from the Volume Viewer dialog cutoff_panel = vdlg.thresholds_panel.threshold.get() # Set the cut-off value in FitOpt with the previous value self.cutoff.set(cutoff_panel) self.message("") # ----------------------------------------------------------------------------- # Validates the values of the parameteres introduced by the users. # Moreover, check if molecule and maps are loaded # def check_models(self): fatoms = self.fit_atoms() fmap = self.fit_map() bmap = self.map_menu.data_region() if (len(fatoms) == 0 and fmap is None) or bmap is None: self.message('Choose model and map.') return False if fmap == bmap: self.message('Chosen maps are the same.') return False if len(self.cutoff.get()) == 0: self.message('Cutoff must be defined.') return False if len(self.resolution.get()) == 0: self.message('Resolution must be defined.') return False if float(self.resolution.get()) < 0 or float( self.resolution.get()) >= 60: self.message('Resolution must be less than 100.') return False self.message("") return True # ---------------------------------------------- # Validates if a string represents an integer # def representsInt(self, number): try: int(number) return True except ValueError: return False # ---------------------------------------------- # Validates if a string represents an integer # def representsFloat(self, number): try: float(number) return True except ValueError: return False
class AddHDialog(ModelessDialog): name = "add hydrogens" help = "ContributedSoftware/addh/addh.html" buttons = ('OK', 'Close') default = 'OK' def __init__(self, title="Add Hydrogens", models=None, useHBonds=None, cb=None, **kw): self.title = title self.cb = cb self.startModels = models if useHBonds is None: self.startUseHBonds = prefs[HBOND_GUIDED] else: self.startUseHBonds = useHBonds ModelessDialog.__init__(self, **kw) def fillInUI(self, parent): import Pmw, Tkinter from chimera.widgets import MoleculeScrolledListBox self.molList = MoleculeScrolledListBox(parent, labelpos='w', label_text="Add hydrogens to:", listbox_selectmode='extended', selectioncommand=self._updateHisListing) if self.startModels: self.molList.setvalue(self.startModels) self.molList.grid(row=0, column=0, sticky="news") parent.columnconfigure(0, weight=1) parent.rowconfigure(0, weight=1) grp = Pmw.Group(parent, tag_text="Method", hull_padx=2) grp.grid(row=1, column=0, sticky="ew") self.useHBondsVar = Tkinter.IntVar(parent) self.useHBondsVar.set(self.startUseHBonds) Tkinter.Radiobutton(grp.interior(), variable=self.useHBondsVar, value=False, text="steric only" ).grid(row=0, sticky='w') Tkinter.Radiobutton(grp.interior(), variable=self.useHBondsVar, value=True, text="also consider H-bonds (slower)" ).grid(row=1, sticky='w') self.hisGroup = Pmw.Group(parent, hull_padx=2, tag_text="Histidine Protonation") self.hisGroup.grid(row=2, column=0, sticky="nsew") self.hisProtVar = Tkinter.StringVar(parent) self.hisProtVar.set("name") interior = self.hisGroup.interior() Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="name", text="Residue-name-based\n" "(HIS/HID/HIE/HIP = unspecified/delta/epsilon/both)", command=self._switchHisList, justify="left").grid( row=0, 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=1, sticky='w') Tkinter.Radiobutton(interior, variable=self.hisProtVar, value="default", command=self._switchHisList, text="Unspecified (determined by method)" ).grid(row=3, sticky='w') def _clearAll(self): for v, cmd in self._vars: if v.get(): v.set(0) cmd() def _selectAll(self): for v, cmd in self._vars: if not v.get(): v.set(1) cmd() def _switchHisList(self): if not hasattr(self, 'hisListing'): if self.hisProtVar.get() != "pick": return self.hisListingData = {} import Tix, Tkinter self.hisFrame = Tkinter.Frame(self.hisGroup.interior()) Tkinter.Label(self.hisFrame, text="If neither delta" " nor epsilon is selected\nthen chosen method" " determines protonation").grid(row=0, column=0, columnspan=2) 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=1, column=0, columnspan=2, 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="Select All", pady=0, highlightthickness=0, command=self._selectAll).grid(row=2, column=0) Tkinter.Button(self.hisFrame, text="Clear All", pady=0, highlightthickness=0, command=self._clearAll).grid(row=2, column=1) if self.hisProtVar.get() == "pick": self._pickText.set("Individually chosen:") self.hisFrame.grid(row=2, sticky="nsew") interior = self.hisGroup.interior() interior.columnconfigure(0, weight=1) interior.rowconfigure(2, weight=1) self.uiMaster().rowconfigure(2, weight=4) else: self._pickText.set("Individually chosen...") self.hisFrame.grid_forget() interior = self.hisGroup.interior() interior.columnconfigure(0, weight=0) interior.rowconfigure(2, weight=0) self.uiMaster().rowconfigure(2, weight=0) def _toggleDelta(self, res): 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): 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 self.molList.getvalue(): for r in m.residues: if r.type not in ["HIS", "HIE", "HIP", "HID"]: continue try: hisType = self.hisListingData[r] except KeyError: self.hisListingData[r] = hisType = "HIS" 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.append((var, cmd)) 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.append((var, cmd)) 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 = {} for m in self.molList.getvalue(): for r in m.residues: if r.type not in ["HIS", "HIE", "HIP", "HID"]: continue try: newData[r] = self.hisListingData[r] except KeyError: newData[r] = r.type self.hisListingData = newData def Apply(self): from chimera import openModels, Molecule from AddH import simpleAddHydrogens, hbondAddHydrogens from unknownsGUI import initiateAddHyd prefs[HBOND_GUIDED] = self.useHBondsVar.get() method = [simpleAddHydrogens, hbondAddHydrogens][ prefs[HBOND_GUIDED]] if self.hisProtVar.get() == "name": hisScheme = None elif self.hisProtVar.get() == "pick": hisScheme = self.hisListingData else: hisScheme = {} initiateAddHyd(self.molList.getvalue(), addFunc=method, hisScheme=hisScheme, okCB=self.cb)
def fillInUI(self, parent): t = parent.winfo_toplevel() self.toplevel_widget = t t.withdraw() parent.columnconfigure(0, weight=1) row = 0 import Tkinter from CGLtk import Hybrid from VolumeViewer import Volume_Menu ff = Tkinter.Frame(parent) ff.grid(row=row, column=0, sticky='w') row = row + 1 # Map selection (only Volumes) fm = Volume_Menu(ff, 'Map: ') fm.frame.grid(row=0, column=0, sticky='w') self.map_menu = fm # Resolution rs = Hybrid.Entry(ff, 'Resolution ', 5) rs.frame.grid(row=0, column=1, sticky='w') self.resolution = rs.variable # Cut-off co = Hybrid.Entry(ff, 'Cut-off level ', 10) co.frame.grid(row=0, column=2, sticky='w') self.cutoff = co.variable self.save_button = Tkinter.Button(ff, text="From Volume Viewer", font=self.arialBondF, height=1, command=self.get_cutoff) self.save_button.grid(row=0, column=3, sticky='w') hf = Tkinter.Frame(parent) hf.grid(row=row, column=0, sticky='w') row += 1 # Space msg = Tkinter.Label(hf, anchor='w', justify='left') msg.grid(row=2, column=0, sticky='ew') row = row + 1 self.message_label = msg # PDB's panel self.pdbs = Tkinter.Frame(parent) self.pdbs.grid(row=3, column=0, sticky='ew') self.pdbs.columnconfigure(1, weight=1) from chimera.widgets import MoleculeScrolledListBox, \ ModelOptionMenu self.modelList = MoleculeScrolledListBox( self.pdbs, labelpos='nw', label_text="Target PDBs to be fitted:", listbox_selectmode='extended', listbox_height=11) self.modelList.grid(row=row, column=0, sticky='nsew') self.pdbs.rowconfigure(row, weight=1) self.pdbs.columnconfigure(0, weight=1) self.modelList1 = MoleculeScrolledListBox( self.pdbs, labelpos='nw', label_text="Target PDBs to be fixed:", listbox_selectmode='extended', listbox_height=11) self.modelList1.grid(row=row, column=1, sticky='nsew') self.pdbs.rowconfigure(row, weight=1) self.pdbs.columnconfigure(0, weight=1) row += 1 # Disable Results panel at first self.results_button = self.buttonWidgets['Results'] self.results_button['state'] = 'disabled'
class Interface(ModelessDialog): title = "Compute Interface Surface" help = "ContributedSoftware/intersurf/intersurf.html" def fillInUI(self, parent): self.notebook = Pmw.NoteBook(parent) self.notebook.pack(fill="both", expand=True) page = self.notebook.add("Molecules") self.molChooser = MoleculeScrolledListBox(page, listbox_selectmode="extended", autoselect="single") self.molChooser.pack(fill="both", expand=True) page = self.notebook.add("Chains") self.chainChooser = MoleculeChainScrolledListBox(page, listbox_selectmode="extended", autoselect="single") self.chainChooser.pack(fill="both", expand=True) self.outputOptions = Pmw.RadioSelect(parent, pady=0, buttontype="checkbutton", orient="vertical") self.outputOptions.pack(fill="x", expand=False) self.outputOptions.add("solid", text="Solid surface (rather than mesh)") self.outputOptions.add("track", text="Reuse last surface (if any)") self.outputOptions.add("atoms", text="Select interface atoms") self.outputOptions.add("prune", text="Residue centroid distance pruning") self.outputOptions.setvalue(["solid", "track"]) self.pruneDistance = Pmw.EntryField(parent, labelpos="w", label_text="Prune distance:", value="30.0", validate=self._validatePruneDistance) self.pruneDistance.pack(fill="x", expand=False) self.moleculeBias = Pmw.Counter(parent, labelpos="w", label_text="Molecule bias:", datatype="real", increment = 0.1, entryfield_value="0.5", entryfield_validate={'validator' : 'real', 'min' : '0.0', 'max' : '1.0', 'separator' : '.'}) self.moleculeBias.pack(fill="x", expand=False) histKw = { 'minlabel': True, 'maxlabel': True, 'scaling': 'linear', } self.histogram = MarkedHistogram(parent, **histKw) self.histogramMarkers = self.histogram.addmarkers(activate=True, coordtype='relative') self.histogramMarkers.extend([ ((1.0, 0.0), (0.0, 0.0, 0.33, 1.0)), ((0.0, 0.0), (1.0, 0.0, 0.0, 1.0))]) self.histogram.pack(expand=True, fill="both") self._trackedPiece = None self._trackedModel = None self.models = {} chimera.openModels.addRemoveHandler(self._removeModel, None) import SimpleSession chimera.triggers.addHandler(SimpleSession.SAVE_SESSION, self.saveSession, None) chimera.triggers.addHandler("Molecule", self._moleculeChanged, None) def _validatePruneDistance(self, text): if len(text) == 0: return Pmw.PARTIAL try: float(text) except: return Pmw.ERROR return Pmw.OK def _show_geometry(self, vertices, triangles, vertex_colors, solid=0, track=0): import numpy varray = numpy.array(vertices, numpy.float32) tarray = numpy.array(triangles, numpy.int32) carray = numpy.array(vertex_colors, numpy.float32) import chimera if track and self._trackedPiece: sm = self._trackedModel g = self._trackedPiece g.geometry = varray, tarray g.vertexColors = carray if solid: g.displayStyle = g.Solid else: g.displayStyle = g.Mesh else: import _surface sm = _surface.SurfaceModel() g = sm.addPiece(varray, tarray, (1, 1, 1, 1)) g.vertexColors = carray if solid: g.displayStyle = g.Solid else: g.displayStyle = g.Mesh sm.name = "Interface Surface" chimera.openModels.add([sm]) self._trackedPiece = g self._trackedModel = sm sm.openState.xform = chimera.Xform.identity() self.models[sm] = (vertices, triangles, vertex_colors, solid) return sm, g def Apply(self): pageName = self.notebook.getcurselection() if pageName == "Molecules": target = self.molChooser.getvalue() elif pageName == "Chains": target = self.chainChooser.getvalue() if not target: raise chimera.UserError("Please select two molecules/chains") if len(target) != 2: raise chimera.UserError("Please select exactly two molecules/chains") opts = self.outputOptions.getvalue() solid = "solid" in opts prune = "prune" in opts track = "track" in opts selAtoms = "atoms" in opts if not self.moleculeBias.valid(): raise chimera.UserError("Please enter a valid bias toward the second molecule") bias = float(self.moleculeBias.getvalue()) if prune: if not self.pruneDistance.valid(): raise chimera.UserError("Please enter a valid prune distance") pruneDistance = float(self.pruneDistance.getvalue()) else: pruneDistance = 0 self.doApply(target, solid, track, selAtoms, bias, prune, pruneDistance) def doApply(self, target, solid, track, selAtoms, bias, prune, pruneDistance): m1, m2 = target if prune: m1_list = SurfMaker.GetAtomList(m1, m2, pruneDistance) m2_list = SurfMaker.GetAtomList(m2, m1, pruneDistance) else: m1_list = SurfMaker.GetAtomList(m1) m2_list = SurfMaker.GetAtomList(m2) if not m1_list or not m2_list: raise chimera.UserError("No interface surface found") p = SurfMaker.UnpackIntersurfData(m1_list, m2_list) tetras = SurfMaker.ComputeTetrahedralization(p) surfPoints, surfTriangles, surfAtoms = SurfMaker.ComputeSurface(p, tetras, bias) surfMetric = [ getDistance(x[0], x[1]) for x in surfAtoms ] lo = min(surfMetric) hi = max(surfMetric) scale = hi - lo markers = [ (lo + m['xy'][0] * scale, m['rgba']) for m in self.histogramMarkers ] surfColors = [ getHistogramColor(x, markers) for x in surfMetric ] self.histogramData = (lo, hi, surfMetric) def myMakeBars(numBins, data=self.histogramData): return makeBars(numBins, data) self.histogram["datasource"] = (lo, hi, myMakeBars) self._show_geometry(surfPoints, surfTriangles, surfColors, solid, track) if selAtoms: from chimera import selection atomSet = set([]) for a1, a2 in surfAtoms: atomSet.add(a1) atomSet.add(a2) sel = selection.ItemizedSelection() sel.add(atomSet) sel.addImplied(vertices=False) selection.setCurrent(sel) def _removeModel(self, trigger, data, models): for m in models: if self._trackedModel is m: self._trackedModel = None self._trackedPiece = None try: del self.models[m] except KeyError: pass def _moleculeChanged(self, trigger, data, models): if 'activeCoordSet changed' not in models.reasons: return pageName = self.notebook.getcurselection() if pageName == "Molecules": target = self.molChooser.getvalue() elif pageName == "Chains": target = [ c.molecule for c in self.chainChooser.getvalue() ] else: return for m in models.modified: if m in target: break else: return self.Apply() def saveSession(self, trigger, data, file): isMapped = self.uiMaster().winfo_ismapped() if not isMapped and not self.models: # Not visible and no displayed surfaces return from SessionUtil import stateclasses, objecttree restoring_code = \ """ def restoreIntersurfSession(state): import SimpleSession from Intersurf import Intersurf SimpleSession.registerAfterModelsCB(Intersurf.restoreSession, state) risArgs = (%s) try: restoreIntersurfSession(risArgs) except: reportRestoreError("Error restoring Intersurf extension") """ pageName = self.notebook.getcurselection() chosenMolecules = self.molChooser.getcurselection() chosenChains = self.chainChooser.getcurselection() opts = self.outputOptions.getvalue() pruneDistance = self.pruneDistance.getvalue() bias = self.moleculeBias.getvalue() if isinstance(self.histogram["datasource"], basestring): histogramData = self.histogram["datasource"] else: histogramData = self.histogramData markerValues = [] markers, selectedMarker = self.histogram.currentmarkerinfo() if markers: for m in markers: markerValues.append((m["xy"], m["rgba"])) ms = stateclasses.Model_State() modelData = [] trackedIndex = -1 n = 0 for m, v in self.models.iteritems(): if self._trackedModel is m: trackedIndex = n ms.state_from_model(m) bt = objecttree.instance_tree_to_basic_tree(ms) modelData.append((v, bt)) n += 1 state = (pageName, chosenMolecules, chosenChains, opts, pruneDistance, bias, histogramData, markerValues, modelData, trackedIndex, isMapped) file.write(restoring_code % repr(state)) def restoreSession(self, state): from SessionUtil import stateclasses, objecttree if len(state) == 10: (pageName, chosenMolecules, chosenChains, opts, pruneDistance, bias, dataSource, markerValues, modelData, trackedIndex) = state if modelData: isMapped = True else: isMapped = False else: (pageName, chosenMolecules, chosenChains, opts, pruneDistance, bias, histogramData, markerValues, modelData, trackedIndex, isMapped) = state # Call get method to make sure items are updated self.molChooser.get() self.molChooser.setvalue(chosenMolecules) self.chainChooser.get() self.chainChooser.setvalue(chosenChains) self.notebook.selectpage(pageName) self.outputOptions.setvalue(list(opts)) self.pruneDistance.setvalue(pruneDistance) self.moleculeBias.setvalue(bias) if isinstance(histogramData, basestring): dataSource = histogramData else: lo, hi, surfMetric = histogramData self.histogramData = (lo, hi, surfMetric) def myMakeBars(numBins, data=self.histogramData): return makeBars(numBins, data) dataSource = (lo, hi, myMakeBars) self.histogram["datasource"] = dataSource if markerValues: oldMarkers = self.histogram.currentmarkerinfo()[0] newMarkers = self.histogram.addmarkers() newMarkers.extend(markerValues) self.histogram.deletemarkers(oldMarkers) self.histogramMarkers = newMarkers trackedModel = None trackedPiece = None nameToClass = { "Model_State": stateclasses.Model_State, "Xform_State": stateclasses.Xform_State, } for n, mState in enumerate(modelData): if len(mState) == 2: v, bt = mState else: v = mState bt = None sm, g = self._show_geometry(*v) if trackedIndex == n: trackedModel = sm trackedPiece = g if bt is not None: ms = objecttree.basic_tree_to_instance_tree(bt, nameToClass) ms.restore_state(sm) if trackedModel: self._trackedModel = trackedModel self._trackedPiece = trackedPiece if not isMapped: self.Close()
class PoPMuSiCExtension(TangramBaseDialog): buttons = ('Run', 'Close') def __init__(self, *args, **kwargs): # GUI init self.title = 'Tangram PoPMuSiC input' self.controller = None # Variables self._popsfile = tk.StringVar() self._popfile = tk.StringVar() # Fire up super(PoPMuSiCExtension, self).__init__(*args, **kwargs) def fill_in_ui(self, parent): note_frame = tk.LabelFrame(self.canvas, text='How to run PoPMuSiC') tk.Label(note_frame, text="PoPMuSiC is a web service!\nYou must register " "and run the jobs from:").pack(padx=5, pady=5) self.ui_web_btn = tk.Button( note_frame, text="PoPMuSiC web interface", command=lambda *a: web.open_new(r"http://soft.dezyme.com/")) self.ui_web_btn.pack(padx=5, pady=5) input_frame = tk.LabelFrame( self.canvas, text='Select molecule and PoPMuSiC output files') input_frame.rowconfigure(0, weight=1) input_frame.columnconfigure(1, weight=1) self.ui_molecules = MoleculeScrolledListBox(input_frame) self.ui_molecules.grid(row=0, columnspan=3, padx=5, pady=5, sticky='news') entries = [('popfile', 'POP file', '.pop'), ('popsfile', 'POPS file', '.pops')] for i, (var, label, ext) in enumerate(entries): # Label tk.Label(input_frame, text=label).grid(row=i + 1, column=0, padx=3, pady=3, sticky='e') # Field entry stringvar = getattr(self, '_' + var) entry = tk.Entry(input_frame, textvariable=stringvar) entry.grid(row=i + 1, column=1, padx=3, pady=3, sticky='news') setattr(self, 'ui_' + var + '_entry', entry) # Button button = tk.Button( input_frame, text='...', command=lambda v=stringvar, e=ext: self._browse_cb(v, e)) button.grid(row=i + 1, column=2, padx=3, pady=3) setattr(self, 'ui_' + var + '_button', button) note_frame.pack(fill='x', padx=5, pady=5) input_frame.pack(expand=True, fill='both', padx=5, pady=5) def Run(self): pass def Close(self): global ui ui = None super(PoPMuSiCExtension, self).Close() def _browse_cb(self, var, extension): path = askopenfilename() if os.path.isfile(path): var.set(path)
class WriteMol2Dialog(SaveModeless): keepShown = SaveModeless.default name = "write Mol2" help = "UsersGuide/savemodel.html#mol2" def __init__(self): self.prefs = preferences.addCategory("write Mol2 dialog", preferences.HiddenCategory, optDict={"multiSaveMol2": "multiple", "hydrogen naming": "sybyl", "residue numbers": True}) SaveModeless.__init__(self, clientPos='s', clientSticky='ewns', filters=[("Mol2", "*.mol2", ".mol2")]) openModels.addAddHandler(self._modelsChange, None) openModels.addRemoveHandler(self._modelsChange, None) self._modelsChange() def configure(self, models=None, refreshList=True, selOnly=None): if models is not None: if len(models) > 1: name = "Multiple Models " elif models: name = models[0].name + " " else: name = "" self._toplevel.title("Save %sas Mol2 File" % name) if refreshList: self.modelList.setvalue(models) if len(models) > 1: self.multiSaveMenu.grid(row=self._msmRow, column=0, sticky='w') else: self.multiSaveMenu.grid_forget() def fillInUI(self, parent): import Pmw, Tkinter SaveModeless.fillInUI(self, parent) row = 0 from chimera.widgets import MoleculeScrolledListBox, \ ModelOptionMenu self.modelList = MoleculeScrolledListBox(self.clientArea, labelpos='w', label_text="Save models:", listbox_selectmode='extended', selectioncommand=lambda: self.configure( self.modelList.getvalue(), refreshList=False)) self.modelList.grid(row=row, column=0, sticky='nsew') self.clientArea.rowconfigure(row, weight=1) self.clientArea.columnconfigure(0, weight=1) row += 1 from chimera import dialogs self.labelMap = { "individual": "a single file [individual @MOLECULE sections]", "combined": "a single file [combined @MOLECULE section]", "multiple": "multiple files [appending model number]" } preferred = self.labelMap[self.prefs["multiSaveMol2"]] self.multiSaveMenu = Pmw.OptionMenu(self.clientArea, labelpos='w', label_text="Save multiple models in", initialitem=preferred, items=self.labelMap.values()) # not always shown; remember row number self._msmRow = row row += 1 self.saveRelativeVar = Tkinter.IntVar(self.clientArea) self.saveRelativeVar.set(False) self.relativeFrame = f = Tkinter.Frame(self.clientArea) Tkinter.Checkbutton(f, variable=self.saveRelativeVar, text="Save relative to model:").grid(row=0, column=0, sticky='e') self.relModelMenu = ModelOptionMenu(f) self.relModelMenu.grid(row=0, column=1, sticky='w') self.saveUntransformedVar = Tkinter.IntVar(parent) self.saveUntransformedVar.set(True) self.untransformedButton = Tkinter.Checkbutton(self.clientArea, variable=self.saveUntransformedVar, text="Use untransformed coordinates") self._rfRow = row row += 1 self.sybylHydNamesVar = Tkinter.IntVar(self.clientArea) self.sybylHydNamesVar.set( self.prefs["hydrogen naming"] == "sybyl") Tkinter.Checkbutton(self.clientArea, variable=self.sybylHydNamesVar, text="Use Sybyl-style hydrogen naming (e.g. HE12" " rather than 2HE1)").grid(row=row, column=0, sticky="w") row += 1 self.resNumsVar = Tkinter.IntVar(self.clientArea) self.resNumsVar.set(self.prefs["residue numbers"]) Tkinter.Checkbutton(self.clientArea, variable=self.resNumsVar, text="Include residue sequence numbers in substructure" " names").grid(row=row, column=0, sticky='w') row += 1 self.writeGaffVar = Tkinter.IntVar(self.clientArea) self.resNumsVar.set(False) Tkinter.Checkbutton(self.clientArea, variable=self.writeGaffVar, text="Write Amber/GAFF atom types instead of Sybyl atom types" ).grid(row=row, column=0, sticky='w') row += 1 self.rigidVar = Tkinter.IntVar(self.clientArea) self.rigidVar.set(False) Tkinter.Checkbutton(self.clientArea, variable=self.rigidVar, text="Write current selection to @SETS section of file" ).grid(row=row, column=0, sticky="w") row += 1 def Apply(self): from chimera import dialogs kw = {'status': replyobj.status} paths = self.getPaths() if not paths: replyobj.error('No save location chosen.\n') return path = paths[0] models = self.modelList.getvalue() if not models: replyobj.error("No models chosen to save.\n") return if float(self.modelList.size()) > 1.5: if self.saveRelativeVar.get(): kw['relModel'] = self.relModelMenu.getvalue() else: if self.saveUntransformedVar.get(): kw['relModel'] = models[0] if self.writeGaffVar.get(): kw['gaffType'] = True from chimera import UserError kw['gaffFailError'] = UserError if self.rigidVar.get(): sel = selection.copyCurrent() sel.addImplied() selAtoms = sel.atoms() selBonds = sel.bonds() if selAtoms and selBonds: kw['anchor'] = sel sybylHydNaming = self.sybylHydNamesVar.get() if sybylHydNaming: self.prefs["hydrogen naming"] = "sybyl" else: self.prefs["hydrogen naming"] = "pdb" kw['hydNamingStyle'] = self.prefs["hydrogen naming"] kw['resNum'] = self.resNumsVar.get() from WriteMol2 import writeMol2 if len(models) < 2: replyobj.status("Writing %s to %s\n" % (models[0].name, path)) writeMol2(models, path, **kw) replyobj.status("Wrote %s to %s\n" % (models[0].name, path)) return saveOpt = self.multiSaveMenu.getvalue() for key, value in self.labelMap.items(): if saveOpt == value: break self.prefs["multiSaveMol2"] = key # write multiple models to multiple files if key == "multiple": if path.endswith(".mol2"): start, end = path[:-4], ".mol2" else: start, end = path, "" for m in models: modelPath = start + m.oslIdent()[1:] + end replyobj.status("Writing %s (%s) to %s\n" % (m.name, m.oslIdent(), modelPath)) writeMol2(m, modelPath, **kw) replyobj.status("Wrote %s (%s) to %s\n" % (m.name, m.oslIdent(), modelPath)) return kw["multimodelHandling"] = key # write multiple models to single file replyobj.status("Writing multiple models to %s\n" % path) writeMol2(models, path, **kw) replyobj.status("Wrote multiple models to %s\n" % path) def _modelsChange(self, *args): if len(openModels.listIds()) > 1: self.untransformedButton.grid_forget() self.relativeFrame.grid(row=self._rfRow, column=0, sticky='w') else: self.relativeFrame.grid_forget() self.untransformedButton.grid(row=self._rfRow, column=0, sticky='w')
class RainbowDialog(ModelessDialog): title = 'Rainbow' buttons = ('OK', 'Apply', 'Defaults', 'Close',) default = 'OK' name = "rainbow models" help = "UsersGuide/modelpanel.html#rainbow" def __init__(self): self.prefs = preferences.addCategory("Rainbow models", preferences.HiddenCategory, optDict={ "colors": defaultColors }) ModelessDialog.__init__(self) def configure(self, models=[], target=None): self.molListBox.setvalue(models) if target: self.colorChangeVar.set(target) def fillInUI(self, parent): self.parent = parent Tkinter.Label(parent, text="Change color every:").grid( row=0, rowspan=3, column=0, sticky='w') self.colorChangeVar = Tkinter.StringVar(parent) self.colorChangeVar.set("residues") Tkinter.Radiobutton(parent, text='residue', value='residues', variable=self.colorChangeVar).grid( row=0, column=1, sticky='w') Tkinter.Radiobutton(parent, text='chain', value='chains', variable=self.colorChangeVar).grid( row=1, column=1, sticky='w') Tkinter.Radiobutton(parent, text='model', value='models', variable=self.colorChangeVar).grid( row=2, column=1, sticky='w') group = Pmw.Group(parent, tag_text='Color range') group.grid(row=3, column=0, columnspan=2) self.wells = [] for i, color in enumerate(self.prefs["colors"]): well = ColorWell(group.interior(), color=color, noneOkay=1) well.grid(row=0, column=i) self.wells.append(well) from chimera.widgets import MoleculeScrolledListBox self.molListBox = MoleculeScrolledListBox(parent, listbox_selectmode="extended", labelpos="n", label_text="Models") self.molListBox.grid(row=0, column=2, rowspan=4, sticky="news") parent.rowconfigure(0, weight=1) parent.columnconfigure(2, weight=1) def Apply(self): colors = [] allColors = [] for well in self.wells: color = well.rgba allColors.append(color) if color is None: continue colors.append(color) if not colors: replyobj.error("No colors for rainbow") return rainbowModels(self.molListBox.getvalue(), changeAt=self.colorChangeVar.get(), colors=colors) self.prefs["colors"] = allColors def Defaults(self): for i, color in enumerate(defaultColors): self.wells[i].showColor(color=color)
def fill_in_ui(self, parent): # Select an input menu: Radio buttons self.ui_input_frame = tk.LabelFrame(self.canvas, text='Input mode') self.ui_input_frame.pack(expand=True, fill='x', padx=5, pady=5) self.ui_input_frame.columnconfigure(0, weight=1) self.ui_input_choice_frame = tk.Frame(self.ui_input_frame) self.ui_input_choice_frame.grid(row=0, sticky='we') self.ui_input_choice_molecules = tk.Radiobutton( self.ui_input_choice_frame, variable=self.var_input_choice, text='Molecules', value='molecules', command=self._input_choice_cb) self.ui_input_choice_selection = tk.Radiobutton( self.ui_input_choice_frame, variable=self.var_input_choice, text='Selection', value='selection', command=self._input_choice_cb) self.ui_input_choice_molecules.pack(side='left') self.ui_input_choice_selection.pack(side='left') self.ui_input_choice_molecules.select() # Mode A: Opened molecules self.ui_input_molecules_frame = tk.Frame(self.ui_input_frame) self.ui_input_molecules_frame.grid(row=1, sticky='news') self.ui_input_molecules_frame.columnconfigure(0, weight=1) self.ui_input_molecules = MoleculeScrolledListBox( self.ui_input_molecules_frame, selectioncommand=self._on_selection_changed, listbox_selectmode="extended") self.ui_input_molecules.pack(expand=True, fill='x', padx=5) # Mode B: Current selection items = ['Current selection'] + sorted( chimera.selection.savedSels.keys()) self.ui_input_named_selections = OptionMenu( self.ui_input_molecules_frame, command=None, items=items) self.input_new_named_atom_selection = None # Text field + 'Create button' # More options self.ui_input_intermolecular_frame = tk.Frame(self.ui_input_frame) self.ui_input_intermolecular_frame.grid(row=2) self.ui_input_intermolecular_check = tk.Checkbutton( self.ui_input_intermolecular_frame, text='Filter out % of intramolecular', variable=self.var_input_intermolecular_enabled, command=self._intermolecular_cb, state='disabled') self.ui_input_intermolecular_check.pack(side='left') self.ui_input_intermolecular_field = tk.Entry( self.ui_input_intermolecular_frame, textvariable=self.var_input_intermolecular, state='disabled', width=3) self.ui_input_intermolecular_field.pack(side='left') # Review input data self.ui_input_summary_label = tk.Label( self.ui_input_frame, textvariable=self.var_input_summary) self.ui_input_summary_label.grid(row=3) # NCIPlot launcher self.ui_nciplot_frame = tk.Frame(self.canvas) self.ui_nciplot_frame.pack() self.ui_config_btn = tk.Button(self.ui_nciplot_frame, text='Configure', command=self._configure_dialog) self.ui_config_btn.pack(side='left') # Configure Volume Viewer self.ui_settings_frame = tk.LabelFrame(self.canvas, text='Customize display', padx=5, pady=5) self.ui_levels_lbl = tk.Label(self.ui_settings_frame, text='Levels: ') self.ui_levels_lbl.grid(row=0, column=0) self.ui_settings_isovalue_1 = tk.Entry( self.ui_settings_frame, textvariable=self.var_settings_isovalue_1, width=10) self.ui_settings_isovalue_1.grid(row=0, column=1, sticky='ew') self.ui_settings_isovalue_2 = tk.Entry( self.ui_settings_frame, textvariable=self.var_settings_isovalue_2, width=10) self.ui_settings_isovalue_2.grid(row=0, column=2, sticky='ew') self.ui_settings_update_btn = tk.Button(self.ui_settings_frame, text='Update', command=self._update_surface) self.ui_settings_update_btn.grid(row=0, column=3, rowspan=2, sticky='news') self.ui_settings_color_palette = OptionMenu( self.ui_settings_frame, initialitem=3, label_text='Colors: ', labelpos='w', items=sorted(standard_color_palettes.keys())) self.ui_settings_color_palette.grid(row=1, column=0, columnspan=3, sticky='we') self.ui_report_btn = tk.Checkbutton( self.ui_settings_frame, text=u'Report \u03BB\u2082\u22C5\u03C1\u22C5100 value at cursor', command=self._report_values_cb, variable=self.var_settings_report) self.ui_report_btn.grid(row=2, column=0, columnspan=3) self.ui_reported_value = tk.Entry(self.ui_settings_frame, textvariable=self.var_reported_value, state='readonly', width=8) self.ui_reported_value.grid(row=2, column=3, sticky='we') # Plot figure self.ui_plot_frame = tk.LabelFrame( self.canvas, text=u'Plot RDG vs density (\u03BB\u2082\u22C5\u03C1)', padx=5, pady=5) self.ui_plot_button = tk.Button(self.ui_plot_frame, text='Plot', command=self._plot) self.ui_plot_button.grid(row=0) self.ui_plot_figure = Figure(figsize=(5, 5), dpi=100, facecolor='#D9D9D9') self.ui_plot_subplot = self.ui_plot_figure.add_subplot(111) self.ui_plot_widget_frame = tk.Frame(self.ui_plot_frame) self.ui_plot_widget_frame.grid(row=1) self.ui_plot_widget = FigureCanvasTkAgg( self.ui_plot_figure, master=self.ui_plot_widget_frame) # self.plot_cursor = Cursor(self.plot_subplot, useblit=True, color='black', linewidth=1) # self.plot_figure.canvas.mpl_connect('button_press_event', self._on_plot_click) # Register and map triggers, callbacks... chimera.triggers.addHandler('selection changed', self._on_selection_changed, None) self.nciplot_run = self.buttonWidgets['Run'] self.buttonWidgets['Save']['state'] = 'disabled'
def fillInUI(self, parent): import Tkinter, Pmw row=0 from chimera.widgets import MoleculeScrolledListBox self.molListBox = MoleculeScrolledListBox(parent, labelpos="nw", label_text="Molecules to prep:", listbox_selectmode="extended") self.molListBox.grid(row=row, sticky='ew') row += 1 Tkinter.Label(parent, text="\nFor chosen molecules," " do the following:").grid(row=row, sticky='w') row += 1 self.delSolventVar = Tkinter.IntVar(parent) self.delSolventVar.set(True) Tkinter.Checkbutton(parent, variable=self.delSolventVar, text= "Delete solvent").grid(row=row, sticky='w') row += 1 self.delIonsVar = Tkinter.IntVar(parent) self.delIonsVar.set(False) Tkinter.Checkbutton(parent, variable=self.delIonsVar, text= "Delete non-complexed ions").grid(row=row, sticky='w') row += 1 self.delAltLocsVar = Tkinter.IntVar(parent) self.delAltLocsVar.set(True) Tkinter.Checkbutton(parent, variable=self.delAltLocsVar, text= "If alternate locations, keep only highest occupancy", ).grid(row=row, sticky='w') row += 1 f = Tkinter.Frame(parent) f.grid(row=row, sticky='w') Tkinter.Label(f, text="Change:").grid( row=0, column=0, rowspan=4) self.mutMseVar = Tkinter.IntVar(parent) self.mutMseVar.set(True) Tkinter.Checkbutton(f, variable=self.mutMseVar, text= "selenomethionine (MSE) to methionine (MET)" ).grid(row=0, column=1, sticky='w') self.mut5buVar = Tkinter.IntVar(parent) self.mut5buVar.set(True) Tkinter.Checkbutton(f, variable=self.mut5buVar, text= "bromo-UMP (5BU) to UMP (U)" ).grid(row=1, column=1, sticky='w') self.mutUmsVar = Tkinter.IntVar(parent) self.mutUmsVar.set(True) Tkinter.Checkbutton(f, variable=self.mutUmsVar, text= "methylselenyl-dUMP (UMS) to UMP (U)" ).grid(row=2, column=1, sticky='w') self.mutCslVar = Tkinter.IntVar(parent) self.mutCslVar.set(True) Tkinter.Checkbutton(f, variable=self.mutCslVar, text= "methylselenyl-dCMP (CSL) to CMP (C)" ).grid(row=3, column=1, sticky='w') row += 1 self.incompleteVar = Tkinter.IntVar(parent) self.incompleteVar.set(True) f = Tkinter.Frame(parent) Tkinter.Checkbutton(f, variable=self.incompleteVar, text="Incomplete side chains:", command=self._incompleteCB).grid(row=0, column=0) from Rotamers import libraries libraries.sort(lambda a, b: cmp(a.displayName, b.displayName)) from chimera.tkoptions import SymbolicEnumOption labels = ["Replace using %s rotamer library" % lib.displayName for lib in libraries] labels.append("Mutate residues to ALA (if CB present) or GLY") values = libraries + ["gly/ala"] class IncompleteSCOption(SymbolicEnumOption): pass IncompleteSCOption.labels = labels IncompleteSCOption.values = values for possibleDefault in (prefs[INCOMPLETE_SC], defaults[INCOMPLETE_SC]): for val in IncompleteSCOption.values: if type(val) == str: if val == possibleDefault: default = possibleDefault break elif val.importName == possibleDefault: default = val break else: continue break self.incompleteOpt = IncompleteSCOption(f, 0, "", default, self._incompleteCB) f.grid(row=row, sticky='w') row += 1 self.addHydVar = Tkinter.IntVar(parent) self.addHydVar.set(True) Tkinter.Checkbutton(parent, variable=self.addHydVar, text="Add hydrogens").grid(row=row, sticky='w') row += 1 self.addChargesVar = Tkinter.IntVar(parent) self.addChargesVar.set(True) Tkinter.Checkbutton(parent, variable=self.addChargesVar, text="Add charges").grid(row=row, sticky='w') row += 1 self.writeMol2Var = Tkinter.IntVar(parent) self.writeMol2Var.set(True) Tkinter.Checkbutton(parent, variable=self.writeMol2Var, text="Write Mol2 file").grid(row=row, sticky='w') row += 1 self.applyKeywords = {} self.citationWidgets = {} self.citationRow = row self._incompleteCB()