19 import os, tempfile, ftplib, http.client
21 from ._ost_io
import *
22 from ost
import mol, geom, conop, seq
23 from ost
import LogWarning
29 if conop.GetDefaultLib():
33 self[
'STRICT'] =
IOProfile(dialect=
'PDB', fault_tolerant=
False,
34 quack_mode=
False, processor=processor.Copy())
35 self[
'SLOPPY'] =
IOProfile(dialect=
'PDB', fault_tolerant=
True,
36 quack_mode=
True, processor=processor.Copy())
37 self[
'CHARMM'] =
IOProfile(dialect=
'CHARMM', fault_tolerant=
True,
38 quack_mode=
False, processor=processor.Copy())
39 self[
'DEFAULT'] =
'STRICT'
42 return IOProfileRegistry.Instance().
Get(key)
45 if isinstance(value, str):
46 value=self[value].Copy()
47 IOProfileRegistry.Instance().Set(key, value)
51 """ Getter which keeps compound library up to date
53 Keeps compound library for default profiles up to date. Reason for that is
54 that conop.SetDefaultLib() after importing io has no effect. Processors
55 (and the associated compound library) are set at import. Custom profiles,
56 i.e. profiles that are not defined in constructor of this class, are
57 returned as is without any update.
59 if key
not in [
'STRICT',
'SLOPPY',
'CHARMM',
'DEFAULT']:
60 return self[key].Copy()
61 prof = self[key].Copy()
62 if conop.GetDefaultLib():
66 prof.processor = processor
70 return len(self.
_dict)
73 return self._dict.__iter__()
77 def _override(val1, val2):
83 def LoadPDB(filename, restrict_chains="", no_hetatms=None,
84 fault_tolerant=
None, load_multi=
False, quack_mode=
None,
85 join_spread_atom_records=
None, calpha_only=
None,
86 profile=
'DEFAULT', remote=
False, remote_repo=
'pdb',
87 dialect=
None, seqres=
False, bond_feasibility_check=
None,
90 Load PDB file from disk and return one or more entities. Several options
91 allow to customize the exact behaviour of the PDB import. For more information
92 on these options, see :doc:`profile`.
94 Residues are flagged as ligand if they are mentioned in a HET record.
96 :param filename: File to be loaded
97 :type filename: :class:`str`
99 :param restrict_chains: If not an empty string, only chains listed in the
100 string will be imported.
101 :type restrict_chains: :class:`str`
103 :param no_hetatms: If set to True, HETATM records will be ignored. Overrides
104 the value of :attr:`IOProfile.no_hetatms`
105 :type no_hetatms: :class:`bool`
107 :param fault_tolerant: Enable/disable fault-tolerant import. If set, overrides
108 the value of :attr:`IOProfile.fault_tolerant`.
109 :type fault_tolerant: :class:`bool`
111 :param load_multi: If set to True, a list of entities will be returned instead
112 of only the first. This is useful when dealing with
114 :type load_multi: :class:`bool`
116 :param quack_mode: Guess the chemical class for unknown residues based on its
117 atoms and connectivity. If set, overrides the value of
118 :attr:`IOProfile.quack_mode`.
119 :type quack_mode: :class:`bool`
121 :param join_spread_atom_records: If set, overrides the value of
122 :attr:`IOProfile.join_spread_atom_records`.
123 :type join_spread_atom_records: :class:`bool`
125 :param calpha_only: When set to true, forces the importer to only load atoms
126 named CA. If set, overrides the value of
127 :attr:`IOProfile.calpha_only`.
128 :type calpha_only: :class:`bool`
130 :param profile: Aggregation of flags and algorithms to control import and
131 processing of molecular structures. Can either be a
132 :class:`str` specifying one of the default profiles
133 ['DEFAULT', 'SLOPPY', 'CHARMM', 'STRICT'] or an actual object
134 of type :class:`ost.io.IOProfile`. If a :class:`str` defines
135 a default profile, :attr:`IOProfile.processor` is set to
136 :class:`ost.conop.RuleBasedProcessor` with the currently
137 set :class:`ost.conop.CompoundLib` available as
138 :func:`ost.conop.GetDefaultLib()`. If no
139 :class:`ost.conop.CompoundLib` is available,
140 :class:`ost.conop.HeuristicProcessor` is used instead. See
141 :doc:`profile` for more info.
142 :type profile: :class:`str`/:class:`ost.io.IOProfile`
144 :param remote: If set to True, the method tries to load the pdb from the remote
145 repository given as *remote_repo*. The filename is then
146 interpreted as the entry id as further specified for the
147 *remote_repo* parameter.
148 :type remote: :class:`bool`
150 :param remote_repo: Remote repository to fetch structure if *remote* is True.
151 Must be one in ['pdb', 'smtl', 'pdb_redo']. In case of
152 'pdb' and 'pdb_redo', the entry must be given as lower
153 case pdb id, which loads the deposited assymetric unit
154 (e.g. '1ake'). In case of 'smtl', the entry must also
155 specify the desired biounit (e.g. '1ake.1').
156 :type remote_repo: :class:`str`
158 :param dialect: Specifies the particular dialect to use. If set, overrides
159 the value of :attr:`IOProfile.dialect`
160 :type dialect: :class:`str`
162 :param seqres: Whether to read SEQRES records. If set to True, the loaded
163 entity and seqres entry will be returned as a tuple.
164 :type seqres: :class:`bool`
166 :param bond_feasibility_check: Flag for :attr:`IOProfile.processor`. If
167 turned on, atoms are only connected by
168 bonds if they are within a reasonable distance
170 :func:`ost.conop.IsBondFeasible`).
171 If set, overrides the value of
172 :attr:`ost.conop.Processor.check_bond_feasibility`
173 :type bond_feasibility_check: :class:`bool`
174 :param read_conect: By default, OpenStructure doesn't read CONECT statements in
175 a pdb file. Reason is that they're often missing and we prefer
176 to rely on the chemical component dictionary from the PDB.
177 However, there may be cases where you really want these CONECT
178 statements. For example novel compounds with no entry in
179 the chemical component dictionary. Setting this to True has
180 two effects: 1) CONECT statements are read and blindly applied
181 2) The processor does not connect any pair of HETATOM atoms in
182 order to not interfer with the CONECT statements.
183 :type read_conect: :class:`bool`
185 :rtype: :class:`~ost.mol.EntityHandle` or a list thereof if `load_multi` is
188 :raises: :exc:`~ost.io.IOException` if the import fails due to an erroneous or
191 def _override(val1, val2):
196 if isinstance(profile, str):
197 prof=profiles.Get(profile)
198 elif isinstance(profile, IOProfile):
201 raise TypeError(
'profile must be of type string or IOProfile, '+\
202 'instead of %s'%type(profile))
203 if dialect
not in (
None,
'PDB',
'CHARMM',):
204 raise ValueError(
'dialect must be PDB or CHARMM')
205 prof.calpha_only=_override(prof.calpha_only, calpha_only)
206 prof.no_hetatms=_override(prof.no_hetatms, no_hetatms)
207 prof.dialect=_override(prof.dialect, dialect)
208 prof.quack_mode=_override(prof.quack_mode, quack_mode)
209 prof.read_conect=_override(prof.read_conect, read_conect)
211 prof.processor.check_bond_feasibility=_override(prof.processor.check_bond_feasibility,
212 bond_feasibility_check)
213 prof.processor.connect_hetatm=_override(prof.processor.connect_hetatm,
215 prof.fault_tolerant=_override(prof.fault_tolerant, fault_tolerant)
216 prof.join_spread_atom_records=_override(prof.join_spread_atom_records,
217 join_spread_atom_records)
221 if remote_repo
not in [
'pdb',
'smtl',
'pdb_redo']:
222 raise IOError(
"remote_repo must be in ['pdb', 'smtl', 'pdb_redo']")
224 tmp_file =
RemoteGet(filename, from_repo=remote_repo)
225 filename = tmp_file.name
227 conop_inst=conop.Conopology.Instance()
229 if prof.dialect==
'PDB':
230 prof.processor.dialect=conop.PDB_DIALECT
231 elif prof.dialect==
'CHARMM':
232 prof.processor.dialect=conop.CHARMM_DIALECT
234 reader.read_seqres=seqres
238 while reader.HasNext():
239 ent=mol.CreateEntity()
240 reader.Import(ent, restrict_chains)
242 prof.processor.Process(ent)
245 raise IOError(
"File '%s' doesn't contain any entities" % filename)
248 ent=mol.CreateEntity()
250 reader.Import(ent, restrict_chains)
252 prof.processor.Process(ent)
254 raise IOError(
"File '%s' doesn't contain any entities" % filename)
256 return ent, reader.seqres
261 def SavePDB(models, filename, dialect=None, pqr=False, profile='DEFAULT'):
263 Save entity or list of entities to disk. If a list of entities is supplied
264 the PDB file will be saved as a multi PDB file. Each of the entities is
265 wrapped into a MODEL/ENDMDL pair.
267 If the atom number exceeds 99999, '*****' is used.
269 :param models: The entity or list of entities (handles or views) to be saved
270 :param filename: The filename
271 :type filename: string
272 :raises: IOException if the restrictions of the PDB format are not satisfied
273 (with the exception of atom numbers, see above):
275 * Chain names with more than one character
276 * Atom positions with coordinates outside range [-999.99, 9999.99]
277 * Residue names longer than three characters
278 * Atom names longer than four characters
279 * Numeric part of :class:`ost.mol.ResNum` outside range [-999, 9999]
280 * Alternative atom indicators longer than one character
282 if not getattr(models,
'__len__',
None):
284 if isinstance(profile, str):
285 profile=profiles.Get(profile)
286 elif isinstance(profile, IOProfile):
287 profile = profile.Copy()
289 raise TypeError(
'profile must be of type string or IOProfile, '+\
290 'instead of %s'%type(profile))
291 profile.dialect=_override(profile.dialect, dialect)
295 writer.write_multi_model=
True
312 image_list.append(image)
315 LoadMapList=LoadImageList
318 lazy_load=
False, stride=1,
319 dialect=
None, detect_swap=
True,swap_bytes=
False):
321 Load CHARMM trajectory file.
323 :param crd: EntityHandle or filename of the (PDB) file containing the
324 structure. The structure must have the same number of atoms as the
326 :param dcd_file: The filename of the DCD file. If not set, and crd is a
327 string, the filename is set to the <crd>.dcd
328 :param layz_load: Whether the trajectory should be loaded on demand. Instead
329 of loading the complete trajectory into memory, the trajectory frames are
330 loaded from disk when requested.
331 :param stride: The spacing of the frames to load. When set to 2, for example,
332 every second frame is loaded from the trajectory. By default, every frame
334 :param dialect: The dialect for the PDB file to use. See :func:`LoadPDB`. If
335 set, overrides the value of the profile
336 :param profile: The IO profile to use for loading the PDB file. See
338 :param detect_swap: if True (the default), then automatic detection of endianess
339 is attempted, otherwise the swap_bytes parameter is used
340 :param swap_bytes: is detect_swap is False, this flag determines whether bytes
341 are swapped upon loading or not
345 dcd_file=
'%s.dcd' % os.path.splitext(crd)[0]
346 crd=
LoadPDB(crd, profile=profile, dialect=dialect)
350 raise ValueError(
"No DCD filename given")
351 return LoadCHARMMTraj_(crd, dcd_file, stride, lazy_load, detect_swap, swap_bytes)
353 def LoadMMCIF(filename, fault_tolerant=None, calpha_only=None,
354 profile=
'DEFAULT', remote=
False, seqres=
False, info=
False):
356 Load a mmCIF file and return one or more entities. Several options allow to
357 customize the exact behaviour of the mmCIF import. For more information on
358 these options, see :doc:`profile`.
360 Residues are flagged as ligand if they are not waters nor covered by an
361 ``entity_poly`` record (ie. they are non-polymer entities in
362 ``pdbx_entity_nonpoly``). Note that all residues except waters will be
363 flagged as ligands if ``seqres=False`` (the default).
365 :param filename: File to be loaded
366 :type filename: :class:`str`
368 :param fault_tolerant: Enable/disable fault-tolerant import. If set, overrides
369 the value of :attr:`IOProfile.fault_tolerant`.
370 :type fault_tolerant: :class:`bool`
372 :param calpha_only: When set to true, forces the importer to only load atoms
373 named CA. If set, overrides the value of
374 :attr:`IOProfile.calpha_only`.
375 :type calpha_only: :class:`bool`
377 :param profile: Aggregation of flags and algorithms to control import and
378 processing of molecular structures. Can either be a
379 :class:`str` specifying one of the default profiles
380 ['DEFAULT', 'SLOPPY', 'CHARMM', 'STRICT'] or an actual object
381 of type :class:`ost.io.IOProfile`. If a :class:`str` defines
382 a default profile, :attr:`IOProfile.processor` is set to
383 :class:`ost.conop.RuleBasedProcessor` with the currently
384 set :class:`ost.conop.CompoundLib` available as
385 :func:`ost.conop.GetDefaultLib()`. If no
386 :class:`ost.conop.CompoundLib` is available,
387 :class:`ost.conop.HeuristicProcessor` is used instead. See
388 :doc:`profile` for more info.
389 :type profile: :class:`str`/:class:`ost.io.IOProfile`
391 :param remote: If set to True, the method tries to load the pdb from the
392 remote pdb repository www.pdb.org. The filename is then
393 interpreted as the pdb id.
394 :type remote: :class:`bool`
396 :param seqres: Whether to return SEQRES records. If True, a
397 :class:`~ost.seq.SequenceList` object is returned as the second
398 item. The sequences in the list are named according to the
400 This feature requires a default
401 :class:`compound library <ost.conop.CompoundLib>`
402 to be defined and accessible via
403 :func:`~ost.conop.GetDefaultLib`. One letter codes of non
404 standard compounds are set to X otherwise.
405 :type seqres: :class:`bool`
407 :param info: Whether to return an info container with the other output.
408 If True, a :class:`MMCifInfo` object is returned as last item.
409 :type info: :class:`bool`
411 :rtype: :class:`~ost.mol.EntityHandle` (or tuple if *seqres* or *info* are
414 :raises: :exc:`~ost.io.IOException` if the import fails due to an erroneous
415 or non-existent file.
417 def _override(val1, val2):
422 if isinstance(profile, str):
423 prof = profiles.Get(profile)
425 prof = profile.Copy()
427 prof.calpha_only=_override(prof.calpha_only, calpha_only)
428 prof.fault_tolerant=_override(prof.fault_tolerant, fault_tolerant)
432 tmp_file =
RemoteGet(filename, from_repo=
'cif')
433 filename = tmp_file.name
436 ent = mol.CreateEntity()
446 prof.processor.Process(ent)
447 reader.info.ConnectBranchLinks()
452 if info
and not reader.seqres:
453 LogWarning(
"MMCifInfo is incomplete when seqres=False")
456 return ent, reader.seqres, reader.info
458 return ent, reader.seqres
460 return ent, reader.info
471 def _PDBize(biounit, asu, seqres=None, min_polymer_size=None,
472 transformation=
False, peptide_min_size=10, nucleicacid_min_size=10,
473 saccharide_min_size=10):
474 if min_polymer_size
is not None:
478 nucleicacid_min_size=nucleicacid_min_size,
479 saccharide_min_size=saccharide_min_size)
481 chains = biounit.GetChainList()
482 c_intvls = biounit.GetChainIntervalList()
483 o_intvls = biounit.GetOperationsIntervalList()
486 ss = seq.CreateSequenceList()
491 operations = biounit.GetOperations()
492 for i
in range(0,len(c_intvls)):
494 l_operations = operations[o_intvls[i][0]:o_intvls[i][1]]
495 if len(l_operations) > 0:
496 for op
in l_operations[0]:
498 rot.PasteRotation(op.rotation)
500 trans.PasteTranslation(op.translation)
503 trans_matrices.append(tr)
504 for op_n
in range(1, len(l_operations)):
506 for o
in l_operations[op_n]:
508 rot.PasteRotation(o.rotation)
510 trans.PasteTranslation(o.translation)
513 for t_o
in trans_matrices:
516 trans_matrices = tmp_ops
518 assu = asu.Select(
'cname='+
','.join(mol.QueryQuoteName(name) \
520 chains[c_intvls[i][0]:c_intvls[i][1]]))
521 pdbizer.Add(assu, trans_matrices, ss)
522 pdb_bu = pdbizer.Finish(transformation)
524 return pdb_bu, pdb_bu.GetTransform().GetMatrix()
527 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.