19 import os, tempfile, ftplib, http.client
21 from ._ost_io
import *
22 from ost
import mol, geom, conop, seq
28 if conop.GetDefaultLib():
32 self[
'STRICT'] =
IOProfile(dialect=
'PDB', fault_tolerant=
False,
33 processor=processor.Copy())
34 self[
'SLOPPY'] =
IOProfile(dialect=
'PDB', fault_tolerant=
True,
35 processor=processor.Copy())
36 self[
'CHARMM'] =
IOProfile(dialect=
'CHARMM', fault_tolerant=
True,
37 processor=processor.Copy())
38 self[
'DEFAULT'] =
'STRICT'
41 return IOProfileRegistry.Instance().
Get(key)
44 if isinstance(value, str):
45 value=self[value].Copy()
46 IOProfileRegistry.Instance().Set(key, value)
47 self.
_dict_dict[key]=value
50 """ Getter which keeps compound library up to date
52 Keeps compound library for default profiles up to date. Reason for that is
53 that conop.SetDefaultLib() after importing io has no effect. Processors
54 (and the associated compound library) are set at import. Custom profiles,
55 i.e. profiles that are not defined in constructor of this class, are
56 returned as is without any update.
58 if key
not in [
'STRICT',
'SLOPPY',
'CHARMM',
'DEFAULT']:
59 return self[key].Copy()
60 prof = self[key].Copy()
61 if conop.GetDefaultLib():
65 prof.processor = processor
69 return len(self.
_dict_dict)
76 def _override(val1, val2):
82 def LoadPDB(filename, restrict_chains="", no_hetatms=None,
83 fault_tolerant=None, load_multi=False,
84 join_spread_atom_records=None, calpha_only=None,
85 profile='DEFAULT', remote=False, remote_repo='pdb',
86 dialect=None, seqres=False, bond_feasibility_check=None,
89 Load PDB file from disk and return one or more entities. Several options
90 allow to customize the exact behaviour of the PDB import. For more information
91 on these options, see :doc:`profile`.
93 Residues are flagged as ligand if they are mentioned in a HET record.
95 :param filename: File to be loaded
96 :type filename: :class:`str`
98 :param restrict_chains: If not an empty string, only chains listed in the
99 string will be imported.
100 :type restrict_chains: :class:`str`
102 :param no_hetatms: If set to True, HETATM records will be ignored. Overrides
103 the value of :attr:`IOProfile.no_hetatms`
104 :type no_hetatms: :class:`bool`
106 :param fault_tolerant: Enable/disable fault-tolerant import. If set, overrides
107 the value of :attr:`IOProfile.fault_tolerant`.
108 :type fault_tolerant: :class:`bool`
110 :param load_multi: If set to True, a list of entities will be returned instead
111 of only the first. This is useful when dealing with
113 :type load_multi: :class:`bool`
115 :param join_spread_atom_records: If set, overrides the value of
116 :attr:`IOProfile.join_spread_atom_records`.
117 :type join_spread_atom_records: :class:`bool`
119 :param calpha_only: When set to true, forces the importer to only load atoms
120 named CA. If set, overrides the value of
121 :attr:`IOProfile.calpha_only`.
122 :type calpha_only: :class:`bool`
124 :param profile: Aggregation of flags and algorithms to control import and
125 processing of molecular structures. Can either be a
126 :class:`str` specifying one of the default profiles
127 ['DEFAULT', 'SLOPPY', 'CHARMM', 'STRICT'] or an actual object
128 of type :class:`ost.io.IOProfile`. If a :class:`str` defines
129 a default profile, :attr:`IOProfile.processor` is set to
130 :class:`ost.conop.RuleBasedProcessor` with the currently
131 set :class:`ost.conop.CompoundLib` available as
132 :func:`ost.conop.GetDefaultLib()`. If no
133 :class:`ost.conop.CompoundLib` is available,
134 :class:`ost.conop.HeuristicProcessor` is used instead. See
135 :doc:`profile` for more info.
136 :type profile: :class:`str`/:class:`ost.io.IOProfile`
138 :param remote: If set to True, the method tries to load the pdb from the remote
139 repository given as *remote_repo*. The filename is then
140 interpreted as the entry id as further specified for the
141 *remote_repo* parameter.
142 :type remote: :class:`bool`
144 :param remote_repo: Remote repository to fetch structure if *remote* is True.
145 Must be one in ['pdb', 'smtl', 'pdb_redo']. In case of
146 'pdb' and 'pdb_redo', the entry must be given as lower
147 case pdb id, which loads the deposited assymetric unit
148 (e.g. '1ake'). In case of 'smtl', the entry must also
149 specify the desired biounit (e.g. '1ake.1').
150 :type remote_repo: :class:`str`
152 :param dialect: Specifies the particular dialect to use. If set, overrides
153 the value of :attr:`IOProfile.dialect`
154 :type dialect: :class:`str`
156 :param seqres: Whether to read SEQRES records. If set to True, the loaded
157 entity and seqres entry will be returned as a tuple.
158 If file doesnt contain SEQRES records, the returned
159 :class:`ost.seq.SequenceList` will be invalid.
160 :type seqres: :class:`bool`
162 :param bond_feasibility_check: Flag for :attr:`IOProfile.processor`. If
163 turned on, atoms are only connected by
164 bonds if they are within a reasonable distance
166 :func:`ost.conop.IsBondFeasible`).
167 If set, overrides the value of
168 :attr:`ost.conop.Processor.check_bond_feasibility`
169 :type bond_feasibility_check: :class:`bool`
170 :param read_conect: By default, OpenStructure doesn't read CONECT statements in
171 a pdb file. Reason is that they're often missing and we prefer
172 to rely on the chemical component dictionary from the PDB.
173 However, there may be cases where you really want these CONECT
174 statements. For example novel compounds with no entry in
175 the chemical component dictionary. Setting this to True has
176 two effects: 1) CONECT statements are read and blindly applied
177 2) The processor does not connect any pair of HETATOM atoms in
178 order to not interfer with the CONECT statements.
179 :type read_conect: :class:`bool`
181 :rtype: :class:`~ost.mol.EntityHandle` or a list thereof if `load_multi` is
184 :raises: :exc:`~ost.io.IOException` if the import fails due to an erroneous or
187 def _override(val1, val2):
192 if isinstance(profile, str):
193 prof=profiles.Get(profile)
194 elif isinstance(profile, IOProfile):
197 raise TypeError(
'profile must be of type string or IOProfile, '+\
198 'instead of %s'%type(profile))
199 if dialect
not in (
None,
'PDB',
'CHARMM',):
200 raise ValueError(
'dialect must be PDB or CHARMM')
201 prof.calpha_only=_override(prof.calpha_only, calpha_only)
202 prof.no_hetatms=_override(prof.no_hetatms, no_hetatms)
203 prof.dialect=_override(prof.dialect, dialect)
204 prof.read_conect=_override(prof.read_conect, read_conect)
206 prof.processor.check_bond_feasibility=_override(prof.processor.check_bond_feasibility,
207 bond_feasibility_check)
208 prof.processor.connect_hetatm=_override(prof.processor.connect_hetatm,
210 prof.fault_tolerant=_override(prof.fault_tolerant, fault_tolerant)
211 prof.join_spread_atom_records=_override(prof.join_spread_atom_records,
212 join_spread_atom_records)
216 if remote_repo
not in [
'pdb',
'smtl',
'pdb_redo']:
217 raise IOError(
"remote_repo must be in ['pdb', 'smtl', 'pdb_redo']")
219 tmp_file =
RemoteGet(filename, from_repo=remote_repo)
220 filename = tmp_file.name
222 conop_inst=conop.Conopology.Instance()
224 if prof.dialect==
'PDB':
225 prof.processor.dialect=conop.PDB_DIALECT
226 elif prof.dialect==
'CHARMM':
227 prof.processor.dialect=conop.CHARMM_DIALECT
229 reader.read_seqres=seqres
233 while reader.HasNext():
234 ent=mol.CreateEntity()
235 reader.Import(ent, restrict_chains)
237 prof.processor.Process(ent)
240 raise IOError(
"File '%s' doesn't contain any entities" % filename)
243 ent=mol.CreateEntity()
245 reader.Import(ent, restrict_chains)
247 prof.processor.Process(ent)
249 raise IOError(
"File '%s' doesn't contain any entities" % filename)
251 return ent, reader.seqres
256 def SavePDB(models, filename, dialect=None, pqr=False, profile='DEFAULT'):
258 Save entity or list of entities to disk. If a list of entities is supplied
259 the PDB file will be saved as a multi PDB file. Each of the entities is
260 wrapped into a MODEL/ENDMDL pair.
262 If the atom number exceeds 99999, '*****' is used.
264 :param models: The entity or list of entities (handles or views) to be saved
265 :param filename: The filename
266 :type filename: string
267 :raises: IOException if the restrictions of the PDB format are not satisfied
268 (with the exception of atom numbers, see above):
270 * Chain names with more than one character
271 * Atom positions with coordinates outside range [-999.99, 9999.99]
272 * Residue names longer than three characters
273 * Atom names longer than four characters
274 * Numeric part of :class:`ost.mol.ResNum` outside range [-999, 9999]
275 * Alternative atom indicators longer than one character
277 if not getattr(models,
'__len__',
None):
279 if isinstance(profile, str):
280 profile=profiles.Get(profile)
281 elif isinstance(profile, IOProfile):
282 profile = profile.Copy()
284 raise TypeError(
'profile must be of type string or IOProfile, '+\
285 'instead of %s'%type(profile))
286 profile.dialect=_override(profile.dialect, dialect)
290 writer.write_multi_model=
True
307 image_list.append(image)
310 LoadMapList=LoadImageList
313 lazy_load=False, stride=1,
314 dialect=None, detect_swap=True,swap_bytes=False):
316 Load CHARMM trajectory file.
318 :param crd: EntityHandle or filename of the (PDB) file containing the
319 structure. The structure must have the same number of atoms as the
321 :param dcd_file: The filename of the DCD file. If not set, and crd is a
322 string, the filename is set to the <crd>.dcd
323 :param layz_load: Whether the trajectory should be loaded on demand. Instead
324 of loading the complete trajectory into memory, the trajectory frames are
325 loaded from disk when requested.
326 :param stride: The spacing of the frames to load. When set to 2, for example,
327 every second frame is loaded from the trajectory. By default, every frame
329 :param dialect: The dialect for the PDB file to use. See :func:`LoadPDB`. If
330 set, overrides the value of the profile
331 :param profile: The IO profile to use for loading the PDB file. See
333 :param detect_swap: if True (the default), then automatic detection of endianess
334 is attempted, otherwise the swap_bytes parameter is used
335 :param swap_bytes: is detect_swap is False, this flag determines whether bytes
336 are swapped upon loading or not
340 dcd_file=
'%s.dcd' % os.path.splitext(crd)[0]
341 crd=
LoadPDB(crd, profile=profile, dialect=dialect)
345 raise ValueError(
"No DCD filename given")
346 return LoadCHARMMTraj_(crd, dcd_file, stride, lazy_load, detect_swap, swap_bytes)
348 def LoadMMCIF(filename, fault_tolerant=None, calpha_only=None,
349 profile='DEFAULT', remote=False, seqres=False, info=False):
351 Load a mmCIF file and return one or more entities. Several options allow to
352 customize the exact behaviour of the mmCIF import. For more information on
353 these options, see :doc:`profile`.
355 Residues are flagged as ligand if they are not waters nor covered by an
356 ``entity_poly`` record (ie. they are non-polymer entities in
357 ``pdbx_entity_nonpoly``). Note that all residues except waters will be
358 flagged as ligands if ``seqres=False`` (the default).
360 :param filename: File to be loaded
361 :type filename: :class:`str`
363 :param fault_tolerant: Enable/disable fault-tolerant import. If set, overrides
364 the value of :attr:`IOProfile.fault_tolerant`.
365 :type fault_tolerant: :class:`bool`
367 :param calpha_only: When set to true, forces the importer to only load atoms
368 named CA. If set, overrides the value of
369 :attr:`IOProfile.calpha_only`.
370 :type calpha_only: :class:`bool`
372 :param profile: Aggregation of flags and algorithms to control import and
373 processing of molecular structures. Can either be a
374 :class:`str` specifying one of the default profiles
375 ['DEFAULT', 'SLOPPY', 'CHARMM', 'STRICT'] or an actual object
376 of type :class:`ost.io.IOProfile`. If a :class:`str` defines
377 a default profile, :attr:`IOProfile.processor` is set to
378 :class:`ost.conop.RuleBasedProcessor` with the currently
379 set :class:`ost.conop.CompoundLib` available as
380 :func:`ost.conop.GetDefaultLib()`. If no
381 :class:`ost.conop.CompoundLib` is available,
382 :class:`ost.conop.HeuristicProcessor` is used instead. See
383 :doc:`profile` for more info.
384 :type profile: :class:`str`/:class:`ost.io.IOProfile`
386 :param remote: If set to True, the method tries to load the pdb from the
387 remote pdb repository www.pdb.org. The filename is then
388 interpreted as the pdb id.
389 :type remote: :class:`bool`
391 :param seqres: Whether to return SEQRES records. If True, a
392 :class:`~ost.seq.SequenceList` object is returned as the second
393 item. The sequences in the list are named according to the
395 This feature requires a default
396 :class:`compound library <ost.conop.CompoundLib>`
397 to be defined and accessible via
398 :func:`~ost.conop.GetDefaultLib`. One letter codes of non
399 standard compounds are set to X otherwise.
400 :type seqres: :class:`bool`
402 :param info: Whether to return an info container with the other output.
403 If True, a :class:`MMCifInfo` object is returned as last item.
404 :type info: :class:`bool`
406 :rtype: :class:`~ost.mol.EntityHandle` (or tuple if *seqres* or *info* are
409 :raises: :exc:`~ost.io.IOException` if the import fails due to an erroneous
410 or non-existent file.
412 def _override(val1, val2):
417 if isinstance(profile, str):
418 prof = profiles.Get(profile)
420 prof = profile.Copy()
422 prof.calpha_only=_override(prof.calpha_only, calpha_only)
423 prof.fault_tolerant=_override(prof.fault_tolerant, fault_tolerant)
427 tmp_file =
RemoteGet(filename, from_repo=
'cif')
428 filename = tmp_file.name
431 ent = mol.CreateEntity()
441 prof.processor.Process(ent)
445 return ent, reader.seqres, reader.info
447 return ent, reader.seqres
449 return ent, reader.info
455 def SaveMMCIF(ent, filename, compound_lib = conop.GetDefaultLib(),
456 data_name=
"OST_structure", mmcif_conform =
True,
457 entity_info = MMCifWriterEntityList()):
459 Save OpenStructure entity in mmCIF format
461 :param ent: OpenStructure Entity to be saved
462 :param filename: Filename - .gz suffix triggers gzip compression
463 :param compound_lib: Compound library required when writing, uses
464 :func:`ost.conop.GetDefaultLib` if not given
465 :param data_name: Name of data block that will be written to
466 mmCIF file. Typically, thats the PDB ID or some
468 :param mmcif_conform: Controls processing of structure, i.e. identification
469 of mmCIF entities etc. before writing. Detailed
470 description in :ref:`MMCif writing`. In short:
471 If *mmcif_conform* is set to True, Chains in *ent* are
472 expected to be valid mmCIF entities with residue numbers
473 set according to underlying SEQRES. That should be the
474 case when *ent* has been loaded with :func:`LoadMMCIF`.
475 If *mmcif_conform* is set to False, heuristics kick in
476 to identify and separate mmCIF entities based on
477 :class:`ost.mol.ChemClass` of the residues in a chain.
478 :type ent: :class:`ost.mol.EntityHandle`/:class:`ost.mol.EntityView`
479 :param entity_info: Advanced usage - description in :ref:`MMCif writing`
480 :type filename: :class:`str`
481 :type compound_lib: :class:`ost.conop.CompoundLib`
482 :type data_name: :class:`str`
483 :type mmcif_conform: :class:`bool`
484 :type entity_info: :class:`MMCifWriterEntityList`
486 if compound_lib
is None:
487 raise RuntimeError(
"Require valid compound library to write mmCIF format")
489 writer.SetStructure(ent, compound_lib, mmcif_conform = mmcif_conform,
490 entity_info = entity_info)
491 writer.Write(data_name, filename)
501 def _PDBize(biounit, asu, seqres=None, min_polymer_size=None,
502 transformation=False, peptide_min_size=10, nucleicacid_min_size=10,
503 saccharide_min_size=10):
504 if min_polymer_size
is not None:
508 nucleicacid_min_size=nucleicacid_min_size,
509 saccharide_min_size=saccharide_min_size)
511 chains = biounit.GetChainList()
512 c_intvls = biounit.GetChainIntervalList()
513 o_intvls = biounit.GetOperationsIntervalList()
516 ss = seq.CreateSequenceList()
521 operations = biounit.GetOperations()
522 for i
in range(0,len(c_intvls)):
524 l_operations = operations[o_intvls[i][0]:o_intvls[i][1]]
525 if len(l_operations) > 0:
526 for op
in l_operations[0]:
528 rot.PasteRotation(op.rotation)
530 trans.PasteTranslation(op.translation)
533 trans_matrices.append(tr)
534 for op_n
in range(1, len(l_operations)):
536 for o
in l_operations[op_n]:
538 rot.PasteRotation(o.rotation)
540 trans.PasteTranslation(o.translation)
543 for t_o
in trans_matrices:
546 trans_matrices = tmp_ops
548 assu = asu.Select(
'cname='+
','.join(mol.QueryQuoteName(name) \
550 chains[c_intvls[i][0]:c_intvls[i][1]]))
551 pdbizer.Add(assu, trans_matrices, ss)
552 pdb_bu = pdbizer.Finish(transformation)
554 return pdb_bu, pdb_bu.GetTransform().GetMatrix()
557 MMCifInfoBioUnit.PDBize = _PDBize
Manages a collection of images.
def __getitem__(self, key)
def __setitem__(self, key, value)
reader for the mmcif file format
std::vector< Mat4 > Mat4List
def RemoteGet(id, from_repo='pdb')
def SavePDB(models, filename, dialect=None, pqr=False, profile='DEFAULT')
def LoadPDB(filename, restrict_chains="", no_hetatms=None, fault_tolerant=None, load_multi=False, join_spread_atom_records=None, calpha_only=None, profile='DEFAULT', remote=False, remote_repo='pdb', dialect=None, seqres=False, bond_feasibility_check=None, read_conect=False)
mol::CoordGroupHandle DLLEXPORT_OST_IO LoadCHARMMTraj(const mol::EntityHandle &ent, const String &trj_filename, unsigned int stride=1, bool lazy_load=false, bool detect_swap=true, bool byte_swap=false)
import a CHARMM trajectory in dcd format with an existing entity requires the existing entity and the...
def SaveMMCIF(ent, filename, compound_lib=conop.GetDefaultLib(), data_name="OST_structure", mmcif_conform=True, entity_info=MMCifWriterEntityList())
DLLEXPORT_OST_IO img::ImageHandle LoadImage(const boost::filesystem::path &loc)
Function that loads an image from a file.
def LoadMMCIF(filename, fault_tolerant=None, calpha_only=None, profile='DEFAULT', remote=False, seqres=False, info=False)