IMP logo
IMP Reference Guide  develop.d97d4ead1f,2024/11/21
The Integrative Modeling Platform
system_tools.py
1 import IMP
2 import IMP.atom
4 import IMP.pmi
5 import IMP.pmi.tools
6 from collections import defaultdict
7 from math import pi
8 import os
9 import warnings
10 
11 # IMP doesn't statically define an atom type for CA atoms in modified residues
12 # (HETATM records) so add it here
13 _AT_HET_CA = IMP.atom.AtomType("HET: CA ")
14 
15 
16 def resnums2str(res):
17  """Take iterable of TempResidues and return compatified string"""
18  if len(res) == 0:
19  return ''
20  idxs = [r.get_index() for r in res]
21  idxs.sort()
22  all_ranges = []
23  cur_range = [idxs[0], idxs[0]]
24  for idx in idxs[1:]:
25  if idx != cur_range[1]+1:
26  all_ranges.append(cur_range)
27  cur_range = [idx, idx]
28  cur_range[1] = idx
29  all_ranges.append(cur_range)
30  ret = ''
31  for nr, r in enumerate(all_ranges):
32  ret += '%i-%i' % (r[0], r[1])
33  if nr < len(all_ranges)-1:
34  ret += ', '
35  return ret
36 
37 
38 def _select_ca_or_p(hiers, **kwargs):
39  """Select all CA (amino acids) or P (nucleic acids) as appropriate"""
40  sel_p = IMP.atom.Selection(hiers, atom_type=IMP.atom.AT_P, **kwargs)
41  ps = sel_p.get_selected_particles()
42  if ps:
43  # detected nucleotides. Selecting phosphorous instead of CA
44  return ps
45  else:
46  # Also select CA atoms in modified residues (such as MSE)
47  sel = IMP.atom.Selection(hiers, atom_type=IMP.atom.AT_CA, **kwargs) \
48  | IMP.atom.Selection(hiers, residue_type=IMP.atom.MSE,
49  atom_type=_AT_HET_CA, **kwargs)
50  return sel.get_selected_particles()
51 
52 
53 def get_structure(model, pdb_fn, chain_id, res_range=None, offset=0,
54  model_num=None, ca_only=False):
55  """read a structure from a PDB file and return a list of residues
56  @param model The IMP model
57  @param pdb_fn The file to read (in traditional PDB or mmCIF format)
58  @param chain_id Chain ID to read
59  @param res_range Add only a specific set of residues.
60  res_range[0] is the starting and res_range[1] is the ending
61  residue index
62  The ending residue can be "END", that will take everything
63  to the end of the sequence.
64  None gets you all.
65  @param offset Apply an offset to the residue indexes of the PDB file
66  @param model_num Read multi-model PDB and return that model (0-based index)
67  @param ca_only Read only CA atoms (by default, all non-waters are read)
68  """
69  # Read file in mmCIF format if requested
70  if pdb_fn.endswith('.cif'):
71  read_file = IMP.atom.read_mmcif
72  read_multi_file = IMP.atom.read_multimodel_mmcif
73  else:
74  read_file = IMP.atom.read_pdb
75  read_multi_file = IMP.atom.read_multimodel_pdb
76  if ca_only:
78  else:
80 
81  reader = read_file if model_num is None else read_multi_file
82  mh = reader(pdb_fn, model, IMP.atom.ChainPDBSelector([chain_id]) & sel)
83  if model_num is not None:
84  mh = mh[model_num]
85 
86  if res_range == [] or res_range is None:
87  ps = _select_ca_or_p(mh, chain=chain_id)
88  else:
89  start = res_range[0]
90  end = res_range[1]
91  if end == "END":
92  end = IMP.atom.Residue(
93  mh.get_children()[0].get_children()[-1]).get_index()
94  ps = _select_ca_or_p(mh, chain=chain_id,
95  residue_indexes=range(start, end+1))
96  ret = []
97 
98  for p in ps:
99  res = IMP.atom.Residue(IMP.atom.Atom(p).get_parent())
100  res.set_index(res.get_index() + offset)
101  ret.append(res)
102  if len(ret) == 0:
103  warnings.warn(
104  "no residues selected from %s in range %s" % (pdb_fn, res_range),
106  return ret
107 
108 
109 def build_bead(model, residues, input_coord=None):
110  """Generates a single bead"""
111 
112  ds_frag = (residues[0].get_index(), residues[-1].get_index())
113  prt = IMP.Particle(model)
115  ptem = IMP.core.XYZR(prt)
116  mass = IMP.atom.get_mass_from_number_of_residues(len(residues))
117 
118  if ds_frag[0] == ds_frag[-1]:
119  rt = residues[0].get_residue_type()
120  h = IMP.atom.Residue.setup_particle(prt, rt, ds_frag[0])
121  h.set_name('%i_bead' % (ds_frag[0]))
122  prt.set_name('%i_bead' % (ds_frag[0]))
123  try:
125  except IMP.ValueException:
127  IMP.atom.ResidueType("ALA"))
129  ptem.set_radius(radius)
130  else:
132  h.set_name('%i-%i_bead' % (ds_frag[0], ds_frag[-1]))
133  prt.set_name('%i-%i_bead' % (ds_frag[0], ds_frag[-1]))
134  h.set_residue_indexes(range(ds_frag[0], ds_frag[-1] + 1))
135  volume = IMP.atom.get_volume_from_mass(mass)
136  radius = 0.8 * (3.0 / 4.0 / pi * volume) ** (1.0 / 3.0)
137  ptem.set_radius(radius)
138 
140  try:
141  if tuple(input_coord) is not None:
142  ptem.set_coordinates(input_coord)
143  except TypeError:
144  pass
145  return h
146 
147 
148 def build_necklace(model, residues, resolution, input_coord=None):
149  """Generates a string of beads with given length"""
150  out_hiers = []
151  for chunk in list(IMP.pmi.tools.list_chunks_iterator(residues,
152  resolution)):
153  out_hiers.append(build_bead(model, chunk, input_coord=input_coord))
154  return out_hiers
155 
156 
157 def build_ca_centers(model, residues):
158  """Create a bead on the CA position with coarsened size and mass"""
159  out_hiers = []
160  for tempres in residues:
161  residue = tempres.get_hierarchy()
162  rp1 = IMP.Particle(model)
163  rp1.set_name("Residue_%i" % residue.get_index())
164  rt = residue.get_residue_type()
165  this_res = IMP.atom.Residue.setup_particle(rp1, residue)
166  try:
168  except IMP.ValueException:
170  IMP.atom.ResidueType("ALA"))
171  try:
172  mass = IMP.atom.get_mass(rt)
173  except Exception:
175  calpha = IMP.atom.Selection(
176  residue,
177  atom_types=[IMP.atom.AT_CA, _AT_HET_CA]).get_selected_particles()
178  cp = IMP.atom.Selection(
179  residue, atom_type=IMP.atom.AT_P).get_selected_particles()
180 
181  if len(calpha) == 1:
182  central_atom = calpha[0]
183  elif len(cp) == 1:
184  central_atom = cp[0]
185  else:
186  raise ValueError(
187  "build_ca_centers: weird selection (no CA, no "
188  "nucleotide P or ambiguous selection found)")
190  shape = IMP.algebra.Sphere3D(
191  IMP.core.XYZ(central_atom).get_coordinates(), radius)
192  IMP.core.XYZR.setup_particle(rp1, shape)
194  out_hiers.append(this_res)
195  return out_hiers
196 
197 
198 def setup_bead_as_gaussian(mh):
199  """Setup bead as spherical gaussian, using radius as variance"""
200  p = mh.get_particle()
201  center = IMP.core.XYZ(p).get_coordinates()
202  rad = IMP.core.XYZR(p).get_radius()
206  [rad]*3)
208 
209 
210 def show_representation(node):
211  print(node)
213  repr = IMP.atom.Representation(node)
214  resolutions = repr.get_resolutions()
215  for r in resolutions:
216  print('---- resolution %i ----' % r)
217  IMP.atom.show_molecular_hierarchy(repr.get_representation(r))
218  return True
219  else:
220  return False
221 
222 
223 def _get_color_for_representation(rep):
224  """Return an IMP.display.Color object (or None) for the given
225  Representation."""
226  if rep.color is not None:
227  if isinstance(rep.color, float):
228  return IMP.display.get_rgb_color(rep.color)
229  elif isinstance(rep.color, str):
230  return IMP.display.Color(*IMP.pmi.tools.color2rgb(rep.color))
231  elif hasattr(rep.color, '__iter__') and len(rep.color) == 3:
232  return IMP.display.Color(*rep.color)
233  elif isinstance(rep.color, IMP.display.Color):
234  return rep.color
235  else:
236  raise TypeError("Color must be Chimera color name, a hex "
237  "string, a float or (r,g,b) tuple")
238 
239 
240 def _add_fragment_provenance(fragment, first_residue, rephandler):
241  """Track the original source of a fragment's structure.
242  If the residues in the given fragment were extracted from a PDB
243  file, add suitable provenance information to the Model (the name
244  of that file, chain ID, and residue index offset)."""
245  pdb_element = rephandler.pdb_for_residue.get(first_residue.get_index())
246  if pdb_element:
247  m = fragment.get_model()
248  p = IMP.Particle(m, "input structure")
250  p, pdb_element.filename, pdb_element.chain_id, pdb_element.offset)
251  IMP.core.add_provenance(m, fragment, sp)
252  return pdb_element
253 
254 
255 def build_representation(parent, rep, coord_finder, rephandler):
256  """Create requested representation.
257  For beads, identifies continuous segments and sets up as Representation.
258  If any volume-based representations (e.g.,densities) are requested,
259  will instead create a single Representation node.
260  All reps are added as children of the passed parent.
261  @param parent The Molecule to which we'll add representations
262  @param rep What to build. An instance of pmi::topology::_Representation
263  @param coord_finder A _FindCloseStructure object to help localize beads
264  """
265  built_reps = []
266  atomic_res = 0
267  ca_res = 1
268  model = parent.hier.get_model()
269  color = _get_color_for_representation(rep)
270 
271  # first get the primary representation (currently, the smallest bead size)
272  # eventually we won't require beads to be present at all
273  primary_resolution = min(rep.bead_resolutions)
274 
275  # if collective densities, will return single node with everything
276  # below we sample or read the GMMs and add them as representation
277  # flag indicating grouping nonlinear segments with one GMM
278  single_node = False
279  prov_dict = {}
280  if rep.density_residues_per_component:
281  single_node = True
282  num_components = (len(rep.residues)
283  // rep.density_residues_per_component+1)
284  rep_dict = defaultdict(list)
285  segp = IMP.Particle(model)
286  root_representation = IMP.atom.Representation.setup_particle(
287  segp, primary_resolution)
288  built_reps.append(root_representation)
289  res_nums = [r.get_index() for r in rep.residues]
290  IMP.atom.Fragment.setup_particle(segp, res_nums)
291  density_frag = IMP.atom.Fragment.setup_particle(
292  IMP.Particle(model), res_nums)
293  density_frag.get_particle().set_name(
294  "Densities %i" % rep.density_residues_per_component)
295  density_ps = []
296 
297  if os.path.exists(rep.density_prefix + '.txt') \
298  and not rep.density_force_compute:
300  rep.density_prefix + '.txt', density_ps, model)
301  if (len(density_ps) != num_components
302  or not os.path.exists(rep.density_prefix + '.txt')
303  or rep.density_force_compute):
304  fit_coords = []
305  total_mass = 0.0
306  for r in rep.residues:
307  for p in IMP.core.get_leaves(r.hier):
308  fit_coords.append(IMP.core.XYZ(p).get_coordinates())
309  total_mass += IMP.atom.Mass(p).get_mass()
310 
311  # fit GMM
312  density_ps = []
314  num_components,
315  model,
316  density_ps,
317  min_covar=4.0,
318  mass_multiplier=total_mass)
319 
321  rep.density_prefix + '.txt')
322  if rep.density_voxel_size > 0.0:
324  density_ps, rep.density_prefix + '.mrc',
325  rep.density_voxel_size, fast=True)
326 
327  for n, d in enumerate(density_ps):
328  d.set_name('Density #%d' % n)
329  density_frag.add_child(d)
330  root_representation.add_representation(
331  density_frag, IMP.atom.DENSITIES,
332  rep.density_residues_per_component)
333 
334  # get continuous segments from residues
335  segments = []
336  rsort = sorted(list(rep.residues), key=lambda r: r.get_index())
337  prev_idx = rsort[0].get_index()-1
338  prev_structure = rsort[0].get_has_structure()
339  cur_seg = []
340  force_break = False
341  for nr, r in enumerate(rsort):
342  if (r.get_index() != prev_idx+1
343  or r.get_has_structure() != prev_structure or force_break):
344  segments.append(cur_seg)
345  cur_seg = []
346  force_break = False
347  cur_seg.append(r)
348  prev_idx = r.get_index()
349  prev_structure = r.get_has_structure()
350  if r.get_index()-1 in rep.bead_extra_breaks:
351  force_break = True
352  if cur_seg != []:
353  segments.append(cur_seg)
354 
355  # for each segment, merge into beads
356  name_all = 'frags:'
357  name_count = 0
358  for frag_res in segments:
359  res_nums = [r.get_index() for r in frag_res]
360  rrange = "%i-%i" % (res_nums[0], res_nums[-1])
361  name = "Frag_" + rrange
362  if name_count < 3:
363  name_all += rrange + ','
364  elif name_count == 3:
365  name_all += '...'
366  name_count += 1
367  segp = IMP.Particle(model, name)
368  IMP.atom.Fragment.setup_particle(segp, res_nums)
369  if not single_node:
370  this_representation = IMP.atom.Representation.setup_particle(
371  segp, primary_resolution)
372  built_reps.append(this_representation)
373  for resolution in rep.bead_resolutions:
374  fp = IMP.Particle(model)
375  this_resolution = IMP.atom.Fragment.setup_particle(fp, res_nums)
376  this_resolution.set_name("%s: Res %i" % (name, resolution))
377  if frag_res[0].get_has_structure():
378  pdb_element = _add_fragment_provenance(
379  this_resolution, frag_res[0], rephandler)
380  if pdb_element is not None:
381  prov_dict[resolution] = pdb_element
382  # if structured, merge particles as needed
383  if resolution == atomic_res:
384  for residue in frag_res:
385  this_resolution.add_child(residue.get_hierarchy())
386  elif resolution == ca_res and rep.bead_ca_centers:
387  beads = build_ca_centers(model, frag_res)
388  for bead in beads:
389  this_resolution.add_child(bead)
390  else:
392  "X")
393  for residue in frag_res:
394  tempc.add_child(IMP.atom.create_clone(residue.hier))
396  tempc, resolution)
397  for bead in beads.get_children():
398  this_resolution.add_child(bead)
399  del tempc
400  del beads
401  else:
402  # if unstructured, create necklace
403  input_coord = coord_finder.find_nearest_coord(
404  min(r.get_index() for r in frag_res))
405  if input_coord is None:
406  input_coord = rep.bead_default_coord
407  beads = build_necklace(model,
408  frag_res,
409  resolution,
410  input_coord)
411  for bead in beads:
412  this_resolution.add_child(bead)
413 
414  # if requested, color all resolutions the same
415  if color:
416  for lv in IMP.core.get_leaves(this_resolution):
418 
419  # finally decide where to put this resolution
420  # if volumetric, collect resolutions from different
421  # segments together
422  if single_node:
423  rep_dict[resolution] += this_resolution.get_children()
424  else:
425  if resolution == primary_resolution:
426  this_representation.add_child(this_resolution)
427  else:
428  this_representation.add_representation(this_resolution,
429  IMP.atom.BALLS,
430  resolution)
431  # if individual beads to be setup as Gaussians:
432  if rep.setup_particles_as_densities:
433  for p in IMP.core.get_leaves(this_resolution):
434  setup_bead_as_gaussian(p)
435  this_resolution.set_name(
436  this_resolution.get_name() + ' Densities %i' % resolution)
437  this_representation.add_representation(this_resolution,
438  IMP.atom.DENSITIES,
439  resolution)
440 
441  if single_node:
442  root_representation.set_name(name_all.strip(',') + ": Base")
443  d = root_representation.get_representations(IMP.atom.DENSITIES)
444  d[0].set_name('%s: ' % name_all + d[0].get_name())
445  for resolution in rep.bead_resolutions:
446  this_resolution = IMP.atom.Fragment.setup_particle(
447  IMP.Particle(model),
448  [r.get_index() for r in rep.residues])
449  this_resolution.set_name("%s: Res %i" % (name_all, resolution))
450  # Use provenance information from the last original node (hopefully
451  # all nodes have the same provenance, i.e. came from the same
452  # PDB file)
453  if prov_dict.get(resolution):
454  pdb_element = prov_dict[resolution]
456  IMP.Particle(model, "input structure"),
457  pdb_element.filename,
458  pdb_element.chain_id, pdb_element.offset)
459  IMP.core.add_provenance(model, this_resolution, sp)
460  for hier in rep_dict[resolution]:
461  this_resolution.add_child(hier)
462  if resolution == primary_resolution:
463  root_representation.add_child(this_resolution)
464  else:
465  root_representation.add_representation(this_resolution,
466  IMP.atom.BALLS,
467  resolution)
468  return built_reps
def list_chunks_iterator
Yield successive length-sized chunks from a list.
Definition: tools.py:590
Tools for handling Gaussian Mixture Models.
Definition: gmm_tools.py:1
Add mass to a particle.
Definition: Mass.h:23
double get_volume_from_residue_type(ResidueType rt)
Return an estimate for the volume of a given residue.
Simple 3D transformation class.
Represent an RGB color.
Definition: Color.h:25
static Gaussian setup_particle(Model *m, ParticleIndex pi)
Definition: core/Gaussian.h:65
void show_molecular_hierarchy(Hierarchy h)
Print out the molecular hierarchy.
static Fragment setup_particle(Model *m, ParticleIndex pi)
Definition: Fragment.h:67
double get_mass(const Selection &s)
Get the total mass of a hierarchy, in Daltons.
static XYZR setup_particle(Model *m, ParticleIndex pi)
Definition: XYZR.h:48
double get_mass(ResidueType c)
Get the mass from the residue type.
static StructureProvenance setup_particle(Model *m, ParticleIndex pi, std::string filename, std::string chain_id, int residue_offset)
Definition: provenance.h:157
Color get_rgb_color(double f)
Return the color for f from the RGB color map.
double get_mass_from_number_of_residues(unsigned int num_aa)
Estimate the mass of a protein from the number of amino acids.
Miscellaneous utilities.
Definition: tools.py:1
double get_ball_radius_from_volume_3d(double volume)
Return the radius of a sphere with a given volume.
Definition: Sphere3D.h:35
The type of an atom.
static Residue setup_particle(Model *m, ParticleIndex pi, ResidueType t, int index, int insertion_code)
Definition: Residue.h:160
static Representation setup_particle(Model *m, ParticleIndex pi)
GenericHierarchies get_leaves(Hierarchy mhd)
Get all the leaves of the bit of hierarchy.
A reference frame in 3D.
def color2rgb
Given a Chimera color name or hex color value, return RGB.
Definition: tools.py:1558
Warning related to handling of structures.
A Gaussian distribution in 3D.
Definition: Gaussian3D.h:25
def fit_gmm_to_points
fit a GMM to some points.
Definition: gmm_tools.py:243
A decorator for a representation.
double get_volume_from_mass(double m, ProteinDensityReference ref=ALBER)
Estimate the volume of a protein from its mass.
Ints get_index(const ParticlesTemp &particles, const Subset &subset, const Subsets &excluded)
A decorator for a particle representing an atom.
Definition: atom/Atom.h:238
static Mass setup_particle(Model *m, ParticleIndex pi, Float mass)
Definition: Mass.h:48
The type for a residue.
PDBSelector * get_default_pdb_selector()
Definition: pdb.h:542
A decorator for a particle with x,y,z coordinates.
Definition: XYZ.h:30
static Colored setup_particle(Model *m, ParticleIndex pi, Color color)
Definition: Colored.h:62
def write_gmm_to_map
write density map from GMM.
Definition: gmm_tools.py:118
A decorator for a residue.
Definition: Residue.h:137
static bool get_is_setup(const IMP::ParticleAdaptor &p)
Hierarchy create_simplified_along_backbone(Chain input, const IntRanges &residue_segments, bool keep_detailed=false)
Rotation3D get_identity_rotation_3d()
Return a rotation that does not do anything.
Definition: Rotation3D.h:352
Class to handle individual particles of a Model object.
Definition: Particle.h:43
Select all CA ATOM records.
Definition: pdb.h:142
Python classes to represent, score, sample and analyze models.
def write_gmm_to_text
write a list of gaussians to text.
Definition: gmm_tools.py:60
Functionality for loading, creating, manipulating and scoring atomic structures.
void add_provenance(Model *m, ParticleIndex pi, Provenance p)
Add provenance to part of the model.
static Chain setup_particle(Model *m, ParticleIndex pi, std::string id)
Definition: Chain.h:84
An exception for an invalid value being passed to IMP.
Definition: exception.h:136
Select hierarchy particles identified by the biological name.
Definition: Selection.h:70
Select all ATOM and HETATM records with the given chain ids.
Definition: pdb.h:256
def decorate_gmm_from_text
read the output from write_gmm_to_text, decorate as Gaussian and Mass
Definition: gmm_tools.py:22
A decorator for a particle with x,y,z coordinates and a radius.
Definition: XYZR.h:27