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 quack_mode=
False, processor=processor.Copy())
34 self[
'SLOPPY'] =
IOProfile(dialect=
'PDB', fault_tolerant=
True,
35 quack_mode=
True, processor=processor.Copy())
36 self[
'CHARMM'] =
IOProfile(dialect=
'CHARMM', fault_tolerant=
True,
37 quack_mode=
False, 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)
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)
72 return self._dict.__iter__()
76 def _override(val1, val2):
82 def LoadPDB(filename, restrict_chains="", no_hetatms=None,
83 fault_tolerant=
None, load_multi=
False, quack_mode=
None,
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 quack_mode: Guess the chemical class for unknown residues based on its
116 atoms and connectivity. If set, overrides the value of
117 :attr:`IOProfile.quack_mode`.
118 :type quack_mode: :class:`bool`
120 :param join_spread_atom_records: If set, overrides the value of
121 :attr:`IOProfile.join_spread_atom_records`.
122 :type join_spread_atom_records: :class:`bool`
124 :param calpha_only: When set to true, forces the importer to only load atoms
125 named CA. If set, overrides the value of
126 :attr:`IOProfile.calpha_only`.
127 :type calpha_only: :class:`bool`
129 :param profile: Aggregation of flags and algorithms to control import and
130 processing of molecular structures. Can either be a
131 :class:`str` specifying one of the default profiles
132 ['DEFAULT', 'SLOPPY', 'CHARMM', 'STRICT'] or an actual object
133 of type :class:`ost.io.IOProfile`. If a :class:`str` defines
134 a default profile, :attr:`IOProfile.processor` is set to
135 :class:`ost.conop.RuleBasedProcessor` with the currently
136 set :class:`ost.conop.CompoundLib` available as
137 :func:`ost.conop.GetDefaultLib()`. If no
138 :class:`ost.conop.CompoundLib` is available,
139 :class:`ost.conop.HeuristicProcessor` is used instead. See
140 :doc:`profile` for more info.
141 :type profile: :class:`str`/:class:`ost.io.IOProfile`
143 :param remote: If set to True, the method tries to load the pdb from the remote
144 repository given as *remote_repo*. The filename is then
145 interpreted as the entry id as further specified for the
146 *remote_repo* parameter.
147 :type remote: :class:`bool`
149 :param remote_repo: Remote repository to fetch structure if *remote* is True.
150 Must be one in ['pdb', 'smtl', 'pdb_redo']. In case of
151 'pdb' and 'pdb_redo', the entry must be given as lower
152 case pdb id, which loads the deposited assymetric unit
153 (e.g. '1ake'). In case of 'smtl', the entry must also
154 specify the desired biounit (e.g. '1ake.1').
155 :type remote_repo: :class:`str`
157 :param dialect: Specifies the particular dialect to use. If set, overrides
158 the value of :attr:`IOProfile.dialect`
159 :type dialect: :class:`str`
161 :param seqres: Whether to read SEQRES records. If set to True, the loaded
162 entity and seqres entry will be returned as a tuple.
163 If file doesnt contain SEQRES records, the returned
164 :class:`ost.seq.SequenceList` will be invalid.
165 :type seqres: :class:`bool`
167 :param bond_feasibility_check: Flag for :attr:`IOProfile.processor`. If
168 turned on, atoms are only connected by
169 bonds if they are within a reasonable distance
171 :func:`ost.conop.IsBondFeasible`).
172 If set, overrides the value of
173 :attr:`ost.conop.Processor.check_bond_feasibility`
174 :type bond_feasibility_check: :class:`bool`
175 :param read_conect: By default, OpenStructure doesn't read CONECT statements in
176 a pdb file. Reason is that they're often missing and we prefer
177 to rely on the chemical component dictionary from the PDB.
178 However, there may be cases where you really want these CONECT
179 statements. For example novel compounds with no entry in
180 the chemical component dictionary. Setting this to True has
181 two effects: 1) CONECT statements are read and blindly applied
182 2) The processor does not connect any pair of HETATOM atoms in
183 order to not interfer with the CONECT statements.
184 :type read_conect: :class:`bool`
186 :rtype: :class:`~ost.mol.EntityHandle` or a list thereof if `load_multi` is
189 :raises: :exc:`~ost.io.IOException` if the import fails due to an erroneous or
192 def _override(val1, val2):
197 if isinstance(profile, str):
198 prof=profiles.Get(profile)
199 elif isinstance(profile, IOProfile):
202 raise TypeError(
'profile must be of type string or IOProfile, '+\
203 'instead of %s'%type(profile))
204 if dialect
not in (
None,
'PDB',
'CHARMM',):
205 raise ValueError(
'dialect must be PDB or CHARMM')
206 prof.calpha_only=_override(prof.calpha_only, calpha_only)
207 prof.no_hetatms=_override(prof.no_hetatms, no_hetatms)
208 prof.dialect=_override(prof.dialect, dialect)
209 prof.quack_mode=_override(prof.quack_mode, quack_mode)
210 prof.read_conect=_override(prof.read_conect, read_conect)
212 prof.processor.check_bond_feasibility=_override(prof.processor.check_bond_feasibility,
213 bond_feasibility_check)
214 prof.processor.connect_hetatm=_override(prof.processor.connect_hetatm,
216 prof.fault_tolerant=_override(prof.fault_tolerant, fault_tolerant)
217 prof.join_spread_atom_records=_override(prof.join_spread_atom_records,
218 join_spread_atom_records)
222 if remote_repo
not in [
'pdb',
'smtl',
'pdb_redo']:
223 raise IOError(
"remote_repo must be in ['pdb', 'smtl', 'pdb_redo']")
225 tmp_file =
RemoteGet(filename, from_repo=remote_repo)
226 filename = tmp_file.name
228 conop_inst=conop.Conopology.Instance()
230 if prof.dialect==
'PDB':
231 prof.processor.dialect=conop.PDB_DIALECT
232 elif prof.dialect==
'CHARMM':
233 prof.processor.dialect=conop.CHARMM_DIALECT
235 reader.read_seqres=seqres
239 while reader.HasNext():
240 ent=mol.CreateEntity()
241 reader.Import(ent, restrict_chains)
243 prof.processor.Process(ent)
246 raise IOError(
"File '%s' doesn't contain any entities" % filename)
249 ent=mol.CreateEntity()
251 reader.Import(ent, restrict_chains)
253 prof.processor.Process(ent)
255 raise IOError(
"File '%s' doesn't contain any entities" % filename)
257 return ent, reader.seqres
262 def SavePDB(models, filename, dialect=None, pqr=False, profile='DEFAULT'):
264 Save entity or list of entities to disk. If a list of entities is supplied
265 the PDB file will be saved as a multi PDB file. Each of the entities is
266 wrapped into a MODEL/ENDMDL pair.
268 If the atom number exceeds 99999, '*****' is used.
270 :param models: The entity or list of entities (handles or views) to be saved
271 :param filename: The filename
272 :type filename: string
273 :raises: IOException if the restrictions of the PDB format are not satisfied
274 (with the exception of atom numbers, see above):
276 * Chain names with more than one character
277 * Atom positions with coordinates outside range [-999.99, 9999.99]
278 * Residue names longer than three characters
279 * Atom names longer than four characters
280 * Numeric part of :class:`ost.mol.ResNum` outside range [-999, 9999]
281 * Alternative atom indicators longer than one character
283 if not getattr(models,
'__len__',
None):
285 if isinstance(profile, str):
286 profile=profiles.Get(profile)
287 elif isinstance(profile, IOProfile):
288 profile = profile.Copy()
290 raise TypeError(
'profile must be of type string or IOProfile, '+\
291 'instead of %s'%type(profile))
292 profile.dialect=_override(profile.dialect, dialect)
296 writer.write_multi_model=
True
313 image_list.append(image)
316 LoadMapList=LoadImageList
319 lazy_load=
False, stride=1,
320 dialect=
None, detect_swap=
True,swap_bytes=
False):
322 Load CHARMM trajectory file.
324 :param crd: EntityHandle or filename of the (PDB) file containing the
325 structure. The structure must have the same number of atoms as the
327 :param dcd_file: The filename of the DCD file. If not set, and crd is a
328 string, the filename is set to the <crd>.dcd
329 :param layz_load: Whether the trajectory should be loaded on demand. Instead
330 of loading the complete trajectory into memory, the trajectory frames are
331 loaded from disk when requested.
332 :param stride: The spacing of the frames to load. When set to 2, for example,
333 every second frame is loaded from the trajectory. By default, every frame
335 :param dialect: The dialect for the PDB file to use. See :func:`LoadPDB`. If
336 set, overrides the value of the profile
337 :param profile: The IO profile to use for loading the PDB file. See
339 :param detect_swap: if True (the default), then automatic detection of endianess
340 is attempted, otherwise the swap_bytes parameter is used
341 :param swap_bytes: is detect_swap is False, this flag determines whether bytes
342 are swapped upon loading or not
346 dcd_file=
'%s.dcd' % os.path.splitext(crd)[0]
347 crd=
LoadPDB(crd, profile=profile, dialect=dialect)
351 raise ValueError(
"No DCD filename given")
352 return LoadCHARMMTraj_(crd, dcd_file, stride, lazy_load, detect_swap, swap_bytes)
354 def LoadMMCIF(filename, fault_tolerant=None, calpha_only=None,
355 profile=
'DEFAULT', remote=
False, seqres=
False, info=
False):
357 Load a mmCIF file and return one or more entities. Several options allow to
358 customize the exact behaviour of the mmCIF import. For more information on
359 these options, see :doc:`profile`.
361 Residues are flagged as ligand if they are not waters nor covered by an
362 ``entity_poly`` record (ie. they are non-polymer entities in
363 ``pdbx_entity_nonpoly``). Note that all residues except waters will be
364 flagged as ligands if ``seqres=False`` (the default).
366 :param filename: File to be loaded
367 :type filename: :class:`str`
369 :param fault_tolerant: Enable/disable fault-tolerant import. If set, overrides
370 the value of :attr:`IOProfile.fault_tolerant`.
371 :type fault_tolerant: :class:`bool`
373 :param calpha_only: When set to true, forces the importer to only load atoms
374 named CA. If set, overrides the value of
375 :attr:`IOProfile.calpha_only`.
376 :type calpha_only: :class:`bool`
378 :param profile: Aggregation of flags and algorithms to control import and
379 processing of molecular structures. Can either be a
380 :class:`str` specifying one of the default profiles
381 ['DEFAULT', 'SLOPPY', 'CHARMM', 'STRICT'] or an actual object
382 of type :class:`ost.io.IOProfile`. If a :class:`str` defines
383 a default profile, :attr:`IOProfile.processor` is set to
384 :class:`ost.conop.RuleBasedProcessor` with the currently
385 set :class:`ost.conop.CompoundLib` available as
386 :func:`ost.conop.GetDefaultLib()`. If no
387 :class:`ost.conop.CompoundLib` is available,
388 :class:`ost.conop.HeuristicProcessor` is used instead. See
389 :doc:`profile` for more info.
390 :type profile: :class:`str`/:class:`ost.io.IOProfile`
392 :param remote: If set to True, the method tries to load the pdb from the
393 remote pdb repository www.pdb.org. The filename is then
394 interpreted as the pdb id.
395 :type remote: :class:`bool`
397 :param seqres: Whether to return SEQRES records. If True, a
398 :class:`~ost.seq.SequenceList` object is returned as the second
399 item. The sequences in the list are named according to the
401 This feature requires a default
402 :class:`compound library <ost.conop.CompoundLib>`
403 to be defined and accessible via
404 :func:`~ost.conop.GetDefaultLib`. One letter codes of non
405 standard compounds are set to X otherwise.
406 :type seqres: :class:`bool`
408 :param info: Whether to return an info container with the other output.
409 If True, a :class:`MMCifInfo` object is returned as last item.
410 :type info: :class:`bool`
412 :rtype: :class:`~ost.mol.EntityHandle` (or tuple if *seqres* or *info* are
415 :raises: :exc:`~ost.io.IOException` if the import fails due to an erroneous
416 or non-existent file.
418 def _override(val1, val2):
423 if isinstance(profile, str):
424 prof = profiles.Get(profile)
426 prof = profile.Copy()
428 prof.calpha_only=_override(prof.calpha_only, calpha_only)
429 prof.fault_tolerant=_override(prof.fault_tolerant, fault_tolerant)
433 tmp_file =
RemoteGet(filename, from_repo=
'cif')
434 filename = tmp_file.name
437 ent = mol.CreateEntity()
447 prof.processor.Process(ent)
448 reader.info.ConnectBranchLinks()
452 return ent, reader.seqres, reader.info
454 return ent, reader.seqres
456 return ent, reader.info
462 def SaveMMCIF(ent, filename, compound_lib = conop.GetDefaultLib(),
463 data_name=
"OST_structure", mmcif_conform =
True,
464 entity_info = MMCifWriterEntityList()):
466 Save OpenStructure entity in mmCIF format
468 :param ent: OpenStructure Entity to be saved
469 :param filename: Filename - .gz suffix triggers gzip compression
470 :param compound_lib: Compound library required when writing, uses
471 :func:`ost.conop.GetDefaultLib` if not given
472 :param data_name: Name of data block that will be written to
473 mmCIF file. Typically, thats the PDB ID or some
475 :param mmcif_conform: Controls processing of structure, i.e. identification
476 of mmCIF entities etc. before writing. Detailed
477 description in :ref:`MMCif writing`. In short:
478 If *mmcif_conform* is set to True, Chains in *ent* are
479 expected to be valid mmCIF entities with residue numbers
480 set according to underlying SEQRES. That should be the
481 case when *ent* has been loaded with :func:`LoadMMCIF`.
482 If *mmcif_conform* is set to False, heuristics kick in
483 to identify and separate mmCIF entities based on
484 :class:`ost.mol.ChemClass` of the residues in a chain.
485 :type ent: :class:`ost.mol.EntityHandle`/:class:`ost.mol.EntityView`
486 :param entity_info: Advanced usage - description in :ref:`MMCif writing`
487 :type filename: :class:`str`
488 :type compound_lib: :class:`ost.conop.CompoundLib`
489 :type data_name: :class:`str`
490 :type mmcif_conform: :class:`bool`
491 :type entity_info: :class:`MMCifWriterEntityList`
493 if compound_lib
is None:
494 raise RuntimeError(
"Require valid compound library to write mmCIF format")
496 writer.SetStructure(ent, compound_lib, mmcif_conform = mmcif_conform,
497 entity_info = entity_info)
498 writer.Write(data_name, filename)
508 def _PDBize(biounit, asu, seqres=None, min_polymer_size=None,
509 transformation=
False, peptide_min_size=10, nucleicacid_min_size=10,
510 saccharide_min_size=10):
511 if min_polymer_size
is not None:
515 nucleicacid_min_size=nucleicacid_min_size,
516 saccharide_min_size=saccharide_min_size)
518 chains = biounit.GetChainList()
519 c_intvls = biounit.GetChainIntervalList()
520 o_intvls = biounit.GetOperationsIntervalList()
523 ss = seq.CreateSequenceList()
528 operations = biounit.GetOperations()
529 for i
in range(0,len(c_intvls)):
531 l_operations = operations[o_intvls[i][0]:o_intvls[i][1]]
532 if len(l_operations) > 0:
533 for op
in l_operations[0]:
535 rot.PasteRotation(op.rotation)
537 trans.PasteTranslation(op.translation)
540 trans_matrices.append(tr)
541 for op_n
in range(1, len(l_operations)):
543 for o
in l_operations[op_n]:
545 rot.PasteRotation(o.rotation)
547 trans.PasteTranslation(o.translation)
550 for t_o
in trans_matrices:
553 trans_matrices = tmp_ops
555 assu = asu.Select(
'cname='+
','.join(mol.QueryQuoteName(name) \
557 chains[c_intvls[i][0]:c_intvls[i][1]]))
558 pdbizer.Add(assu, trans_matrices, ss)
559 pdb_bu = pdbizer.Finish(transformation)
561 return pdb_bu, pdb_bu.GetTransform().GetMatrix()
564 MMCifInfoBioUnit.PDBize = _PDBize
DLLEXPORT_OST_IO img::ImageHandle LoadImage(const boost::filesystem::path &loc)
Function that loads an image from a file.
std::vector< Mat4 > Mat4List
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...
reader for the mmcif file format
Manages a collection of images.