def topology(self): if self.gui.ui_input_note.index(self.gui.ui_input_note.select()): return self.gui.var_path.get() # else: model = self.gui.ui_chimera_models.getvalue() if model: sanitized_path = '{0[0]}{1}{0[1]}'.format( os.path.splitext(model.name), '_fixed') if os.path.isfile(sanitized_path): return sanitized_path else: output = getattr(model, 'openedAs', (model.name + '.pdb', ))[0] chimera.pdbWrite([model], chimera.Xform(), output) return output
def _duplicate_molecule(molecule): """ Export a PDB copy of the given molecule to a StringIO object and load it back. We use this instead of Molecule.copy_molecule because PLIP gets the very same PDB copy, and sometimes this results in different serial numbers """ stream = StringIO() chimera.pdbWrite([molecule], molecule.openState.xform, stream) stream.seek(0) pdb = chimera.PDBio() molcopy, _ = pdb.readPDBstream(stream, '{}.pdb'.format(molecule.name), 0) chimera.openModels.add(molcopy, sameAs=molecule) return molcopy[0], stream
def sanitize_model(self): # Each model in a single model #Getting molecule attributes model = self.ui_chimera_models.getvalue() modelfile_path = getattr(model, 'openedAs', (model.name, ))[0] basename, ext = os.path.splitext(modelfile_path) output_file = '{0}{1}{2}'.format(basename, '_fixed', ext or '.pdb') chimera.pdbWrite([model], chimera.Xform(), output_file) self.fix_pdb(output_file, out=output_file) m = chimera.openModels.open(output_file, sameAs=model)[0] m.name = model.name + ' - Fixed' self.ui_chimera_models.selection_clear() self.ui_chimera_models.selection_set( chimera.openModels.list().index(m)) model.display = False
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 _apply_pdbfix(molecule, pH=7.0, add_hydrogens=False): """ Run PDBFixer to ammend potential issues in PDB format. Parameters ---------- molecule : chimera.Molecule Chimera Molecule object to fix. pH : float, optional Target pH for adding missing hydrogens. add_hydrogens : bool, optional Whether to add missing hydrogens or not. Returns ------- memfile : StringIO An in-memory file with the modified PDB contents """ memfile = StringIO() chimera.pdbWrite([molecule], chimera.Xform(), memfile) chimera.openModels.close([molecule]) memfile.seek(0) fixer = PDBFixer(pdbfile=memfile) fixer.findMissingResidues() fixer.findNonstandardResidues() fixer.replaceNonstandardResidues() fixer.findMissingAtoms() fixer.addMissingAtoms() fixer.removeHeterogens(True) if add_hydrogens: fixer.addMissingHydrogens(pH) memfile.close() memfile = StringIO() PDBFile.writeFile(fixer.topology, fixer.positions, memfile) memfile.seek(0) molecule = chimera.openModels.open(memfile, type="PDB", identifyAs=molecule.name) chimera.openModels.remove(molecule) memfile.close() return molecule[0]
def prepare_protein_amber(protein, ph=7): """ Prepare molecule to contain correct residues, capping groups, and so on, using pdb4amber Parameters ========== molecule : chimera.Molecule Returns ======= pdb """ print('Preparing', protein.name, '...') inpdb = protein.basename + '.unfixed.pdb' chimera.pdbWrite([protein], protein.openState.xform, inpdb) pdb4amber.run(arg_pdbin=inpdb, arg_pdbout=protein.basename + '.pdb', arg_reduce=True) return protein.basename + '.pdb'
def write(self, path=None, name=None, absolute=None, combined_with=None, filetype='mol2'): """ Writes full mol2 to disk. .. todo:: It'd be preferable to get a string instead of a file """ if path and name: fullname = os.path.join( path, '{}_{}.{}'.format(name, self.name, filetype)) elif absolute: fullname = absolute else: fileobject, fullname = tempfile.mkstemp( prefix='gaudi', suffix='.{}'.format(filetype)) logger.warning("No output path provided. Using tempfile %s.", fullname) molecules = [self.compound.mol] if combined_with: molecules.extend(ind.compound.mol for ind in combined_with) if filetype == 'mol2': writeMol2(molecules, fullname, temporary=True, multimodelHandling='combined') elif filetype == 'pdb': chimera.pdbWrite(molecules, self.compound.mol.openState.xform, fullname) else: raise ValueError( 'Filetype {} not recognized. Try with mol2 or pdb'.format( filetype)) return fullname
def export_temporary_pdbstream(molecule): temp = StringIO() chimera.pdbWrite([molecule], molecule.openState.xform, temp) temp.seek(0) return temp
def parameterize(molecule, reduce=False, net_charge='auto', charge_method='bcc', atom_type='gaff'): """ Add charges to a molecule using Antechamber and Parmchk Parameters ---------- molecule : chimera.Molecule reduce : bool Add hydrogens to molecule before parameterization (in place) net_charge : int or 'auto' or None Total charge for the molecule. If 'auto' will try to guess, but can be wrong. If None, no charges will be computed (needed for metal ions) charge_method : str, default='bcc' Method used by -c option in antechamber. Available options: resp, bcc, cm2, esp, mul, gas Returns ------- A dict with keys: molecule : chimera.Molecule Copy of the original molecule with new attributes mol2 : str Contents of antechamber-generated mol2 file frcmod : str Contents of parmchk-generated frcmod file """ print('Preparing', molecule.name, '...') if net_charge is None: is_metal = True options = {} else: is_metal = False if net_charge == 'auto': net_charge = estimateNetCharge(molecule.atoms) options = {'net_charge': net_charge, 'charge_method': charge_method} for b in molecule.bonds: molecule.deleteBond(b) inpdb = molecule.basename + '.pdb' chimera.pdbWrite([molecule], molecule.openState.xform, inpdb) # Path element name column for metals if is_metal: with open(inpdb, 'r+') as f: lines = [] for line in f: if line.startswith('ATOM') or line.startswith('HETATM'): line = line.upper() lines.append(line) f.seek(0) f.write(''.join(lines)) antechamber = 'antechamber -fi pdb -fo mol2 -i INPUT -o OUTPUT -at {atom_type}'.format( atom_type=atom_type).split() if options: antechamber.extend( '-c {charge_method} -nc {net_charge}'.format(**options).split()) antechamber[6] = inpdb antechamber[8] = molecule.basename + '.mol2' print(' CMD:', ' '.join(antechamber)) with open('antechamber_{}.log'.format(molecule.basename), 'w') as f: try: check_call(antechamber, stdout=f, stderr=f) except OSError: raise KnownError(" !!! ERROR - antechamber could not be located. " "Have you installed ambertools?") except CalledProcessError: raise KnownError(' !!! ERROR - Check antechamber_{}.log'.format( molecule.basename)) if options: parmchk = 'parmchk2 -i INPUT -o OUTPUT -f mol2'.split() parmchk[2] = antechamber[8] parmchk[4] = os.path.splitext(inpdb)[0] + '.frcmod' print(' CMD:', ' '.join(parmchk)) with open('parmchk2_{}.log'.format(molecule.basename), 'w') as f: try: check_call(parmchk, stdout=f, stderr=f) except OSError: raise KnownError( " !!! ERROR - parmchk2 could not be located. " "Have you installed ambertools?") except CalledProcessError: raise KnownError(' !!! ERROR - Check parmchk2_{}.log'.format( molecule.basename)) result = {'pdb': antechamber[6], 'mol2': antechamber[8]} if is_metal: # fix charge and atom type in antechamber-generated mol2 with open(antechamber[8], 'r+') as f: lines = [] for line in f: if line.startswith('@<TRIPOS>ATOM'): lines.append(line) # add current one before skipping line = next(f) fields = line.split() if fields[5] != fields[ 1]: # fix atom type if it does not match resname line = line.replace(fields[5], fields[1]) line = line.replace(fields[-1], str(float( molecule.charge))) # replace charge lines.append(line) f.seek(0) f.write(''.join(lines)) else: result['frcmod'] = parmchk[4] return result
def get_structure_string(self): s = StringIO() chimera.pdbWrite(self.molecules, self.molecules[0].openState.xform, s) return s.getvalue()
def write_pdb(molecule, path=None): if path is None: path = osTemporaryFile(suffix='.pdb') chimera.pdbWrite([molecule], molecule.openState.xform, path) return path