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 an mmCIF file and return the first model as an entity.
353 Several options allow to customize the exact behaviour of the mmCIF import.
354 For more information on these options, see :doc:`profile`.
356 Residues are flagged as ligand if they are not waters nor covered by an
357 ``entity_poly`` record (ie. they are non-polymer entities in
358 ``pdbx_entity_nonpoly``). Note that all residues except waters will be
359 flagged as ligands if ``seqres=False`` (the default).
361 :param filename: File to be loaded
362 :type filename: :class:`str`
364 :param fault_tolerant: Enable/disable fault-tolerant import. If set, overrides
365 the value of :attr:`IOProfile.fault_tolerant`.
366 :type fault_tolerant: :class:`bool`
368 :param calpha_only: When set to true, forces the importer to only load atoms
369 named CA. If set, overrides the value of
370 :attr:`IOProfile.calpha_only`.
371 :type calpha_only: :class:`bool`
373 :param profile: Aggregation of flags and algorithms to control import and
374 processing of molecular structures. Can either be a
375 :class:`str` specifying one of the default profiles
376 ['DEFAULT', 'SLOPPY', 'CHARMM', 'STRICT'] or an actual object
377 of type :class:`ost.io.IOProfile`. If a :class:`str` defines
378 a default profile, :attr:`IOProfile.processor` is set to
379 :class:`ost.conop.RuleBasedProcessor` with the currently
380 set :class:`ost.conop.CompoundLib` available as
381 :func:`ost.conop.GetDefaultLib()`. If no
382 :class:`ost.conop.CompoundLib` is available,
383 :class:`ost.conop.HeuristicProcessor` is used instead. See
384 :doc:`profile` for more info.
385 :type profile: :class:`str`/:class:`ost.io.IOProfile`
387 :param remote: If set to True, the method tries to load the pdb from the
388 remote pdb repository www.pdb.org. The filename is then
389 interpreted as the pdb id.
390 :type remote: :class:`bool`
392 :param seqres: Whether to return SEQRES records. If True, a
393 :class:`~ost.seq.SequenceList` object is returned as the second
394 item. The sequences in the list are named according to the
396 This feature requires a default
397 :class:`compound library <ost.conop.CompoundLib>`
398 to be defined and accessible via
399 :func:`~ost.conop.GetDefaultLib`. One letter codes of non
400 standard compounds are set to X otherwise.
401 :type seqres: :class:`bool`
403 :param info: Whether to return an info container with the other output.
404 If True, a :class:`MMCifInfo` object is returned as last item.
405 :type info: :class:`bool`
407 :rtype: :class:`~ost.mol.EntityHandle` (or tuple if *seqres* or *info* are
410 :raises: :exc:`~ost.io.IOException` if the import fails due to an erroneous
411 or non-existent file.
413 def _override(val1, val2):
418 if isinstance(profile, str):
419 prof = profiles.Get(profile)
421 prof = profile.Copy()
423 prof.calpha_only=_override(prof.calpha_only, calpha_only)
424 prof.fault_tolerant=_override(prof.fault_tolerant, fault_tolerant)
428 tmp_file =
RemoteGet(filename, from_repo=
'cif')
429 filename = tmp_file.name
432 ent = mol.CreateEntity()
442 prof.processor.Process(ent)
446 return ent, reader.seqres, reader.info
448 return ent, reader.seqres
450 return ent, reader.info
456 def SaveMMCIF(ent, filename, compound_lib = conop.GetDefaultLib(),
457 data_name=
"OST_structure", mmcif_conform =
True,
458 entity_info = MMCifWriterEntityList()):
460 Save OpenStructure entity in mmCIF format
462 :param ent: OpenStructure Entity to be saved
463 :param filename: Filename - .gz suffix triggers gzip compression
464 :param compound_lib: Compound library required when writing, uses
465 :func:`ost.conop.GetDefaultLib` if not given
466 :param data_name: Name of data block that will be written to
467 mmCIF file. Typically, thats the PDB ID or some
469 :param mmcif_conform: Controls processing of structure, i.e. identification
470 of mmCIF entities etc. before writing. Detailed
471 description in :ref:`MMCif writing`. In short:
472 If *mmcif_conform* is set to True, Chains in *ent* are
473 expected to be valid mmCIF entities with residue numbers
474 set according to underlying SEQRES. That should be the
475 case when *ent* has been loaded with :func:`LoadMMCIF`.
476 If *mmcif_conform* is set to False, heuristics kick in
477 to identify and separate mmCIF entities based on
478 :class:`ost.mol.ChemClass` of the residues in a chain.
479 :type ent: :class:`ost.mol.EntityHandle`/:class:`ost.mol.EntityView`
480 :param entity_info: Advanced usage - description in :ref:`MMCif writing`
481 :type filename: :class:`str`
482 :type compound_lib: :class:`ost.conop.CompoundLib`
483 :type data_name: :class:`str`
484 :type mmcif_conform: :class:`bool`
485 :type entity_info: :class:`MMCifWriterEntityList`
487 if compound_lib
is None:
488 raise RuntimeError(
"Require valid compound library to write mmCIF format")
490 writer.SetStructure(ent, compound_lib, mmcif_conform = mmcif_conform,
491 entity_info = entity_info)
492 writer.Write(data_name, filename)
502 def _PDBize(biounit, asu, seqres=None, min_polymer_size=None,
503 transformation=False, peptide_min_size=10, nucleicacid_min_size=10,
504 saccharide_min_size=10):
505 if min_polymer_size
is not None:
509 nucleicacid_min_size=nucleicacid_min_size,
510 saccharide_min_size=saccharide_min_size)
512 chains = biounit.GetChainList()
513 c_intvls = biounit.GetChainIntervalList()
514 o_intvls = biounit.GetOperationsIntervalList()
517 ss = seq.CreateSequenceList()
522 operations = biounit.GetOperations()
523 for i
in range(0,len(c_intvls)):
525 l_operations = operations[o_intvls[i][0]:o_intvls[i][1]]
526 if len(l_operations) > 0:
527 for op
in l_operations[0]:
529 rot.PasteRotation(op.rotation)
531 trans.PasteTranslation(op.translation)
534 trans_matrices.append(tr)
535 for op_n
in range(1, len(l_operations)):
537 for o
in l_operations[op_n]:
539 rot.PasteRotation(o.rotation)
541 trans.PasteTranslation(o.translation)
544 for t_o
in trans_matrices:
547 trans_matrices = tmp_ops
549 assu = asu.Select(
'cname='+
','.join(mol.QueryQuoteName(name) \
551 chains[c_intvls[i][0]:c_intvls[i][1]]))
552 pdbizer.Add(assu, trans_matrices, ss)
553 pdb_bu = pdbizer.Finish(transformation)
555 return pdb_bu, pdb_bu.GetTransform().GetMatrix()
558 MMCifInfoBioUnit.PDBize = _PDBize
561 def LoadSDF(filename, fault_tolerant=None, profile='DEFAULT'):
563 Load SDF file from disk and return an entity.
565 :param filename: File to be loaded
566 :type filename: :class:`str`
568 :param fault_tolerant: Enable/disable fault-tolerant import. If set, overrides
569 the value of :attr:`IOProfile.fault_tolerant`.
570 :type fault_tolerant: :class:`bool`
572 :param profile: Aggregation of flags and algorithms to control import and
573 processing of molecular structures. Can either be a
574 :class:`str` specifying one of the default profiles
575 ['DEFAULT', 'SLOPPY', 'CHARMM', 'STRICT'] or an actual object
576 of type :class:`ost.io.IOProfile`.
577 See :doc:`profile` for more info.
578 :type profile: :class:`str`/:class:`ost.io.IOProfile`
580 :raises: :exc:`~ost.io.IOException` if the import fails due to an erroneous or
583 def _override(val1, val2):
589 if isinstance(profile, str):
590 prof = profiles.Get(profile)
591 elif isinstance(profile, IOProfile):
592 prof = profile.Copy()
594 raise TypeError(
'profile must be of type string or IOProfile, ' + \
595 'instead of %s' % type(profile))
596 prof.fault_tolerant = _override(prof.fault_tolerant, fault_tolerant)
599 ent = mol.CreateEntity()
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...
mol::EntityHandle DLLEXPORT_OST_IO LoadSDF(const String &file_name)
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)