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))
def align_best(reference, probe, transform=True, sanitize=True, ignore_warnings=False, maxIters=50, reflect=False, **kwargs): rdk_reference = _chimera_to_rdkit(reference, sanitize=sanitize) rdk_probe = _chimera_to_rdkit(probe, sanitize=sanitize) matches = rdk_reference.GetSubstructMatches(rdk_probe, uniquify=False) if not matches: raise chimera.UserError('Could not find any alignment.') if not ignore_warnings and len(matches) > 1e6: raise chimera.UserError( "Too many possible alignments found! This can be " "slow! Use `ignore_warnings true` to try.") maps = [list(enumerate(match)) for match in matches] best_rmsd, best_xform = 1000., None for atom_map in maps: rmsd, xform = GetAlignmentTransform(rdk_probe, rdk_reference, atomMap=atom_map, maxIters=maxIters, reflect=reflect) if rmsd < best_rmsd: best_rmsd = rmsd best_xform = xform if transform and best_xform is not None: _transform_molecule(probe, chimera_xform(best_xform[:3])) return best_rmsd
def process_atoms(self, state=None): if state is None: state = self.state gaussian_atoms = [] chimera_atoms = state['molecule'].atoms mapping = {} oniom, kw, layers_flex, frozen = False, {}, {}, {} if state['calculation'] == 'ONIOM': # we have layers to deal with! oniom = True layers_flex = state['layers_flex'] mm_types = state['mm_types'] if not layers_flex: raise chimera.UserError('ONIOM layers have not been defined!') if not mm_types: raise chimera.UserError('MM types have not been defined') if state['mm_residues']: self.patch_residue_names(state) for n, catom in enumerate(chimera_atoms): layer, frozen = layers_flex.get(catom, (None, 0)) kw = dict(oniom=oniom, layer=layer, frozen=int(frozen)) gatom = self.gaussian_atom(catom, n=n + 1, **kw) gaussian_atoms.append(gatom) mapping[catom] = gatom show_warning = False """ try: assign_bond_orders(state['molecule'], engine='openbabel') except: try: assign_bond_orders(state['molecule'], engine='rdkit') except: pass """ for catom, gatom in zip(chimera_atoms, gaussian_atoms): for cneighbor, bond in catom.bondsMap.items(): order = getattr(bond, 'order', None) if not order: order = 1.0 gatom.add_neighbor(mapping[cneighbor], order) if show_warning: errormsg = ( 'Some bonds did not specify bond order, so a default of 1.0 ' 'was used. If you want compute them or edit them manually, ' 'please use Tangram BondOrder extension.') d = NotifyDialog(errormsg, icon='warning') d.OK = d.Close d.enter() return gaussian_atoms
def Apply(self): if not self.attrName.valid(): raise chimera.UserError( "Please enter valid attribute name") name = self.attrName.getvalue() formula = self.formula.getvalue() try: tokenList = attrdef.Scanner().tokenize(formula) except ValueError, s: raise chimera.UserError( "Formula tokenizing error: %s" % str(s))
def Apply(self): modList = self.modListBox.getvalue() if len(modList) == 0: import chimera raise chimera.UserError("No models selected") ef = self.scale.component("entryfield") if not ef.valid(): import chimera raise chimera.UserError(ScaleErrorText) s = float(ef.getvalue()) import base base.tile(modList, s)
def __init__(self, refModels, altModels, subSelection, *args, **kw): # # Save the subselection (part of model to match) # as well as the model lists (ordered by subid) # self.subSelection = subSelection l = [(m.subid, m) for m in refModels] l.sort() self.refModels = [t[1] for t in l] l = [(m.subid, m) for m in altModels] l.sort() self.altModels = [t[1] for t in l] # # Grab the atomic coordinates that will be used # to compute RMSDs and check for errors # self.atomDict = {} counts = [] for ml in self.refModels, self.altModels: for m in ml: osl = '%s%s' % (m.oslIdent(), self.subSelection) s = selection.OSLSelection(osl) atoms = s.atoms() self.atomDict[m] = match._coordArray(atoms) counts.append(len(atoms)) if min(counts) != max(counts): raise chimera.UserError("Unequal number of atoms " "found in models") if counts[0] == 0: raise chimera.UserError("No atoms match atom specifier") # # Add handler to monitor change in display or active # status changes # self.trigger = chimera.triggers.addHandler('check for changes', self._statusCheck, None) # # Initialize dialog # ModelessDialog.__init__(self, *args, **kw) # # Register with extension manager # chimera.extension.manager.registerInstance(self)
def _add_column(self): from gaudiview.extensions.gaudiobj import GaudiObjectiveDialog keys = self.selected or self.gui.table.model.data if len(keys) > 50: raise chimera.UserError('Too many solutions requested! Max 50.') self._gaudi_obj_dialog = GaudiObjectiveDialog(callback=self._add_column_cb) self._gaudi_obj_dialog.enter()
def findSubseq(self): self.prefs[self.prefStyle] = self.SUBSEQUENCE try: probeSeq = self.ambMenu.text2pattern( self.seqEntry.component('entry').get().upper()) except AmbiguityMenu.PatternError, v: raise chimera.UserError(str(v))
def cluster(modelList, subSelection): "Assign a cluster id to each model in the list" if not modelList: import chimera raise chimera.UserError("No ensemble selected") d = EnsembleCluster(modelList, subSelection)
def _run_gaussian(self, **kwargs): path = self.gui.ui_gaussian_file_entry.get() if not os.path.exists(path): raise chimera.UserError("File {} not available".format(path)) self.vibrations = VibrationalMolecule.from_gaussian(path) self._molecules = self.vibrations.molecule return True
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 _readonlyCB(self, opt): prefFile = preferences.filename() if not prefFile: # If no file name, changes make no difference. return newState = opt.get() if ((newState and preferences.isReadonly()) or (not newState and not preferences.isReadonly())): # No change in state return if newState: # Make readonly. This is always okay. preferences.setReadonly(True) else: # Make not readonly. See if the file is # writable. If not, ask the user if he wants # to change permission. if not _canWrite(prefFile): from chimera.baseDialog import AskYesNoDialog d = AskYesNoDialog("File is not writable." " Try changing permissions?") answer = d.run(self._ui) if answer == "no": opt.ui().set(1) return try: sbuf = os.stat(prefFile) import stat mode = sbuf.st_mode | stat.S_IWRITE os.chmod(prefFile, mode) except os.error, s: opt.ui().set(1) raise chimera.UserError("cannot make %s " "writable: %s" % (prefFile, s)) preferences.setReadonly(False)
def open_in_chimera(self, web_files, pdb_ids, all_cmds): """'web_files' is a list of files that were dloaded from web, 'pdb_ids' is a list of pdb ids, 'mid_cmds' is a list of midas commands """ import chimera res = self.warnIfNeeded(web_files, all_cmds) if not res: self.cleanUpDloaded(web_files.values()) return for name, loc in web_files.items(): #print "OPENING (web) ", loc try: chimera.openModels.open("%s" % os.path.abspath(loc), identifyAs=name, noprefs=True) finally: self.cleanUpDloaded(os.path.abspath(loc)) for p in pdb_ids: #print "OPENING (pdb) ", p try: chimera.openModels.open("%s" % p, type="PDB", noprefs=True) except IOError, what: raise chimera.UserError( "Error while opening model with PDB id '%s': %s" % (p, what))
def __init__(self, bond, anchorSide=BIGGER, requestedID=None): try: self.bondRot = BondRot(bond) except (chimera.error, ValueError), v: if "cycle" in str(v): raise chimera.UserError("Cannot rotate a bond" " that is part of a closed cycle") raise
def untransformed_rmsd(reference, probe, sanitize=True, uniquify=False, reflect=True, method='sub', **kwargs): rdk_reference = _chimera_to_rdkit(reference, sanitize=sanitize) rdk_probe = _chimera_to_rdkit(probe, sanitize=sanitize) if method in ('sub', 'best'): matches = rdk_reference.GetSubstructMatches(rdk_probe, uniquify=uniquify) elif method == 'o3a': rdk_reference2 = _chimera_to_rdkit(reference, sanitize=sanitize) rdk_probe2 = _chimera_to_rdkit(probe, sanitize=sanitize) FastFindRings(rdk_reference) FastFindRings(rdk_probe) reference_params = MMFFGetMoleculeProperties(rdk_reference) probe_params = MMFFGetMoleculeProperties(rdk_probe) o3a = GetO3A(rdk_probe2, rdk_reference2, probe_params, reference_params, maxIters=0, reflect=reflect) matches = o3a.Matches() else: raise chimera.UserError('`method` must be sub, best or o3a') if not matches: raise chimera.UserError('Could not find any matches.') maps = [list(enumerate(match)) for match in matches] best_rmsd = 1000. for atom_map in maps: rmsd = AlignMol(rdk_probe, rdk_reference, -1, -1, atomMap=atom_map, maxIters=0, reflect=reflect) if rmsd < best_rmsd: best_rmsd = rmsd return best_rmsd
def color_key_cb(self, *args): if self.n < 2: raise chimera.UserError("At least two colors needed to create key") from Ilabel.gui import IlabelDialog from chimera import dialogs d = dialogs.display(IlabelDialog.name) d.keyConfigure([ (w.rgba, h.variable.get()) for w, h in zip(self.colorwells, self.entry_fields)[:self.n] ])
def Apply(self): sel = self.listbox.getcurselection() if len(sel) != 1: import chimera raise chimera.UserError(TileErrorText) n = self.itemList.index(sel[0]) id = self.ensembleList[n][0] subSelection = self.selectionField.get().strip() import base base.cluster(self.modelDict[id], subSelection)
def _after_cb(self, aborted): if aborted: self._clear_cb() return if self.subprocess.returncode: last = self.subprocess.stderr.readlines()[-1] msg = "OMMProtocol calculation failed! Reason: {}".format(last) self._clear_cb() raise chimera.UserError(msg) self.task.finished() chimera.statusline.show_message('Yay! MD Done!')
def process(cmdName, args): from Midas.midas_text import doExtensionFunc try: func, kwargs = _cmdTable[cmdName] except KeyError: # We only get here if the command was registered # in ChimeraExtension.py but is not in our command table. # Assume that registration is correct and that we # just haven't implemented the function yet. import chimera raise chimera.UserError("%s: unimplemented command" % cmdName) doExtensionFunc(func, args, **kwargs)
def _cmd_redundant_btn(self, *args): if self._modredundant_dialog is None: from gui import ModRedundantDialog molecule = self.gui.ui_molecules.getvalue() if molecule is None: raise chimera.UserError('No molecule selected!') self._modredundant_dialog = ModRedundantDialog( self.gui._restraints, molecule.atoms, master=self.gui.uiMaster(), callback=self._cb_after_modredundant) self._modredundant_dialog.enter()
def rotationForBond(self, bond, create=True, requestedID=None): for br in self.rotations.values(): if br.bond == bond: if requestedID != None and requestedID != br.id: raise chimera.UserError("Rotation" " already exists with different" " ID (%d) than requested (%d)" % (br.id, requestedID)) return br if create: return BondRotation(bond, requestedID=requestedID) return None
def Apply(self): ref = self.refListbox.getcurselection() alt = self.altListbox.getcurselection() if len(ref) != 1 or len(alt) != 1: import chimera raise chimera.UserError(MatchErrorText) n = self.itemList.index(ref[0]) refId = self.ensembleList[n][0] n = self.itemList.index(alt[0]) altId = self.ensembleList[n][0] subSelection = self.selectionField.get().strip() import base base.EnsembleMatch(self.modelDict[refId], self.modelDict[altId], subSelection)
class BondRotation(object): SMALLER, BIGGER = range(2) def __init__(self, bond, anchorSide=BIGGER, requestedID=None): try: self.bondRot = BondRot(bond) except (chimera.error, ValueError), v: if "cycle" in str(v): raise chimera.UserError("Cannot rotate a bond" " that is part of a closed cycle") raise for end in bond.atoms: if len(end.neighbors) == 1: self.bondRot.destroy() raise chimera.UserError("Bond rotation would" " have no effect (terminal bond)") self.bond = bond self.__anchorSide = self._sideToAtom(anchorSide) if requestedID is not None \ and requestedID in bondRotMgr.rotations: raise chimera.UserError("Requested bond-rotation ID already" " in use") bondRotMgr._newRot(self, requestedID)
def cmd_rmsd(reference_sel, probe_sel, method='best', reflect=False, sanitize=False, uniquify=False): references = reference_sel.molecules() probes = probe_sel.molecules() if not len(references) == 1: raise chimera.UserError("Reference must contain a single molecule.") if not len(probes): raise chimera.UserError("Select at least one probe.") reference = references[0] rmsds = [] for probe in probes: if reference.numAtoms < probe.numAtoms: raise chimera.UserError( "Reference model should be larger than probe.") rmsd = untransformed_rmsd(reference, probe, method=method, uniquify=uniquify, reflect=reflect, sanitize=sanitize) rmsds.append(rmsd) msg = "" if len(rmsds) == 1: msg = "RMSD is {}".format(rmsds[0]) elif len(rmsds) > 1: avg_rmsd = sum(rmsds) / len(rmsds) print(*rmsds) msg = "Average RMSD for {} molecules is {}".format( len(rmsds), avg_rmsd) chimera.statusline.show_message(msg, blankAfter=5) return rmsds
def _chimera_to_rdkit(molecule, sanitize=True): io = StringIO.StringIO() xform = molecule.openState.xform atoms = [ a for a in molecule.atoms if not a.element.isMetal and a.element.number > 1 ] if not atoms: raise chimera.UserError("Molecule does not contain meaningful atoms!") molecule_copy = molecule_from_atoms(molecule, atoms) chimera.pdbWrite([molecule_copy], xform, io) io.seek(0) rdkit_mol = MolFromPDBBlock(io.getvalue(), False, sanitize) io.close() molecule_copy.destroy() return rdkit_mol
def matchModel(self, model): n = self.matchVars[model].get() va, vd = self.modelVars[model] if n < 0: va.set(0) vd.set(0) self.activateModel(model, 0) self.displayModel(model, 0) return altOSL = '%s%s' % (model.oslIdent(), self.subSelection) ref = self.refModels[n] refOSL = '%s%s' % (ref.oslIdent(), self.subSelection) try: Midas.match(altOSL, refOSL) except Midas.MidasError, e: raise chimera.UserError(str(e))
def _x3dConvert(prog, filename): import chimera, os title = "" prog = os.path.join(os.environ["CHIMERA"], "bin", prog) try: from SubprocessMonitor import Popen, PIPE cmd = [prog, '-o', filename] proc = Popen(cmd, stdin=PIPE) chimera.viewer.x3dWrite(proc.stdin, 0, title) proc.stdin.close() returncode = proc.wait() if returncode == 1: raise chimera.NonChimeraError("Error writing %s" % (filename)) elif returncode != 0: raise RuntimeError("'%s' exited with error code %d" % (prog, returncode)) except chimera.error, v: raise chimera.UserError(v)
def create_lib(self, temp_path, res, i, output, output_name): # ambermini """ Creates a leaprc file. When we run that one in xleap, the program will create a file called met.lib where we'll have information about our metal center and 4 dummy atoms with connectivity missing. Parameters ---------- temp_path: str Temporary file location res: str Metal Residue name i: int Metal number output: str Desired Output Path output_name: str Desires output name """ # file_paths tleap_input = os.path.join(temp_path, "leaprc.metal") forcefield = os.path.join(self.amber_path, 'dat', 'leap', 'cmd', 'oldff', 'leaprc.ff99SB') pdbfile = os.path.join(temp_path, "dummymetal.pdb") output_lib = os.path.join(temp_path, "met%d.lib" % i) self.tleap_path = os.path.join(self.amber_path, 'bin', 'tleap') log_file = os.path.join(output, output_name + ".log") # tleap_input with open(tleap_input, 'w') as f: f.write("logFile leap.log\n" "source " + forcefield + "\n" + "{0}= loadpdb {1}\n".format(res, pdbfile) + "saveoff {0} {1}\n".format(res, output_lib) + "quit") # tleap launch command = [self.tleap_path, "-s", "-f", tleap_input] with open(log_file, 'w') as log: try: subprocess.call(command, stdout=log, stderr=log) except Exception as e: raise chimera.UserError('Command {} could not be finished due ' 'to exception {}'.format(command, e)) # save library file self.lib.append(output_lib)
def _run_prody(self, queue=None, threaded=True): self._molecules = self.gui.ui_molecules.getvalue() if not self._molecules: self.gui.buttonWidgets['Run']['state'] = 'normal' self.gui.buttonWidgets['Run']['text'] = 'Run' raise chimera.UserError("Please select at least one molecule") algorithm = ALGORITHMS[self.gui.ui_algorithms_menu.getvalue()] algorithm_param = int(self.gui.ui_algorithms_param.get()) n_modes = int(self.gui.ui_n_modes.get()) cutoff = float(self.gui.ui_cutoff.get()) gamma = float(self.gui.ui_gamma.get()) mw = 'Mass-Weighted' in self.gui.ui_extra_options_chk.getvalue() if threaded: thread = Thread(target=VibrationalMolecule.from_chimera, args=(self._molecules, ), kwargs=dict(algorithm=algorithm, n=algorithm_param, queue=queue, max_modes=n_modes, gamma=gamma, mass_weighted=mw, cutoff=cutoff)) thread.start() while thread.isAlive(): chimera.tkgui.app.update() self.vibrations = queue.get_nowait() else: self.vibrations = VibrationalMolecule.from_chimera( self._molecules, algorithm=algorithm, n=algorithm_param, queue=queue.task, max_modes=n_modes, gamma=gamma, mass_weighted=mw, cutoff=cutoff) return True
track = chimera.TrackChanges.get() track.clear() # execute optional scripts if script: sys.argv = [script] + args args = [script] return_value = 0 for a in args: try: try: chimera.openModels.open(a, prefixableType=1) except IOError, value: # so that we don't get bug reports when # people mistype file names raise chimera.UserError(value) except SystemExit, value: return value except: replyobj.reportException("Error while processing %s" % a) return_value = 1 if nogui: from chimera import triggers, APPQUIT, fileInfo if not script: if args: fileType = fileInfo.processName(args[-1])[0] else: fileType = None if fileInfo.category(fileType) != fileInfo.SCRIPT: extension.startup(["ReadStdin"])