IMP logo
IMP Reference Guide  2.11.1
The Integrative Modeling Platform
system_tools.py
1 from __future__ import print_function, division
2 import IMP
3 import IMP.atom
5 import IMP.pmi
6 import IMP.pmi.tools
7 from collections import defaultdict
8 from math import pi
9 import os
10 import warnings
11 
12 def resnums2str(res):
13  """Take iterable of TempResidues and return compatified string"""
14  if len(res)==0:
15  return ''
16  idxs = [r.get_index() for r in res]
17  idxs.sort()
18  all_ranges=[]
19  cur_range=[idxs[0],idxs[0]]
20  for idx in idxs[1:]:
21  if idx!=cur_range[1]+1:
22  all_ranges.append(cur_range)
23  cur_range=[idx,idx]
24  cur_range[1]=idx
25  all_ranges.append(cur_range)
26  ret = ''
27  for nr,r in enumerate(all_ranges):
28  ret+='%i-%i'%(r[0],r[1])
29  if nr<len(all_ranges)-1:
30  ret+=', '
31  return ret
32 
33 def get_structure(model,pdb_fn,chain_id,res_range=None,offset=0,model_num=None,ca_only=False):
34  """read a structure from a PDB file and return a list of residues
35  @param model The IMP model
36  @param pdb_fn The file to read (in traditional PDB or mmCIF format)
37  @param chain_id Chain ID to read
38  @param res_range Add only a specific set of residues.
39  res_range[0] is the starting and res_range[1] is the ending residue index
40  The ending residue can be "END", that will take everything to the end of the sequence.
41  None gets you all.
42  @param offset Apply an offset to the residue indexes of the PDB file
43  @param model_num Read multi-model PDB and return that model
44  @param ca_only Read only CA atoms (by default, all non-waters are read)
45  """
47  # Read file in mmCIF format if requested
48  read_file = IMP.atom.read_pdb
49  read_multi_file = IMP.atom.read_multimodel_pdb
50  if pdb_fn.endswith('.cif'):
51  read_file = IMP.atom.read_mmcif
52  read_multi_file = IMP.atom.read_multimodel_mmcif
53  if ca_only:
55  if model_num is None:
56  mh = read_file(pdb_fn,model,
58 
59  else:
60  mhs = read_multi_file(pdb_fn,model,sel)
61  if model_num>=len(mhs):
62  raise Exception("you requested model num "+str(model_num)+\
63  " but the PDB file only contains "+str(len(mhs))+" models")
64  mh = IMP.atom.Selection(mhs[model_num],chain=chain_id,with_representation=True)
65 
66  if res_range==[] or res_range is None:
67  sel = IMP.atom.Selection(mh,chain=chain_id,atom_type=IMP.atom.AtomType('CA'))
68  sel_p = IMP.atom.Selection(mh,chain=chain_id,atom_type=IMP.atom.AT_P)
69  else:
70  start = res_range[0]
71  end = res_range[1]
72  if end=="END":
73  end = IMP.atom.Residue(mh.get_children()[0].get_children()[-1]).get_index()
74  sel = IMP.atom.Selection(mh,chain=chain_id,residue_indexes=range(start,end+1),
75  atom_type=IMP.atom.AtomType('CA'))
76  sel_p = IMP.atom.Selection(mh,chain=chain_id,residue_indexes=range(start,end+1),
77  atom_type=IMP.atom.AT_P)
78  ret = []
79 
80  if sel_p.get_selected_particles():
81  "WARNING: detected nucleotides. Selecting phosphorous instead of CA"
82  sel=sel_p
83 
84  for p in sel.get_selected_particles():
85  res = IMP.atom.Residue(IMP.atom.Atom(p).get_parent())
86  res.set_index(res.get_index() + offset)
87  ret.append(res)
88  if len(ret) == 0:
89  warnings.warn(
90  "no residues selected from %s in range %s" % (pdb_fn, res_range),
92  return ret
93 
94 def build_bead(model,residues,input_coord=None):
95  """Generates a single bead"""
96 
97  ds_frag = (residues[0].get_index(), residues[-1].get_index())
98  prt = IMP.Particle(model)
100  ptem = IMP.core.XYZR(prt)
101  mass = IMP.atom.get_mass_from_number_of_residues(len(residues))
102 
103  if ds_frag[0] == ds_frag[-1]:
104  rt = residues[0].get_residue_type()
105  h = IMP.atom.Residue.setup_particle(prt, rt, ds_frag[0])
106  h.set_name('%i_bead' % (ds_frag[0]))
107  prt.set_name('%i_bead' % (ds_frag[0]))
108  try:
110  except IMP.ValueException:
112  IMP.atom.ResidueType("ALA"))
114  ptem.set_radius(radius)
115  else:
117  h.set_name('%i-%i_bead' % (ds_frag[0], ds_frag[-1]))
118  prt.set_name('%i-%i_bead' % (ds_frag[0], ds_frag[-1]))
119  h.set_residue_indexes(range(ds_frag[0], ds_frag[-1] + 1))
120  volume = IMP.atom.get_volume_from_mass(mass)
121  radius = 0.8 * (3.0 / 4.0 / pi * volume) ** (1.0 / 3.0)
122  ptem.set_radius(radius)
123 
125  try:
126  if tuple(input_coord) is not None:
127  ptem.set_coordinates(input_coord)
128  except TypeError:
129  pass
130  return h
131 
132 def build_necklace(model,residues, resolution, input_coord=None):
133  """Generates a string of beads with given length"""
134  out_hiers = []
135  for chunk in list(IMP.pmi.tools.list_chunks_iterator(residues, resolution)):
136  out_hiers.append(build_bead(model,chunk, input_coord=input_coord))
137  return out_hiers
138 
139 def build_ca_centers(model,residues):
140  """Create a bead on the CA position with coarsened size and mass"""
141  out_hiers = []
142  for tempres in residues:
143  residue = tempres.get_hierarchy()
144  rp1 = IMP.Particle(model)
145  rp1.set_name("Residue_%i"%residue.get_index())
146  rt = residue.get_residue_type()
147  this_res = IMP.atom.Residue.setup_particle(rp1,residue)
148  try:
150  except IMP.ValueException:
152  IMP.atom.ResidueType("ALA"))
153  try:
154  mass = IMP.atom.get_mass(rt)
155  except:
157  calpha = IMP.atom.Selection(residue,atom_type=IMP.atom.AT_CA). \
158  get_selected_particles()
159  cp=IMP.atom.Selection(residue,atom_type=IMP.atom.AT_P). \
160  get_selected_particles()
161 
162  if len(calpha)==1:
163  central_atom=calpha[0]
164  elif len(cp)==1:
165  central_atom=cp[0]
166  else:
167  raise("build_ca_centers: weird selection (no Ca, no nucleotide P or ambiguous selection found)")
169  shape = IMP.algebra.Sphere3D(IMP.core.XYZ(central_atom).get_coordinates(),radius)
172  out_hiers.append(this_res)
173  return out_hiers
174 
175 def setup_bead_as_gaussian(mh):
176  """Setup bead as spherical gaussian, using radius as variance"""
177  p = mh.get_particle()
178  center = IMP.core.XYZ(p).get_coordinates()
179  rad = IMP.core.XYZR(p).get_radius()
180  mass = IMP.atom.Mass(p).get_mass()
184 
185 
186 def show_representation(node):
187  print(node)
189  repr = IMP.atom.Representation(node)
190  resolutions = repr.get_resolutions()
191  for r in resolutions:
192  print('---- resolution %i ----' %r)
193  IMP.atom.show_molecular_hierarchy(repr.get_representation(r))
194  return True
195  else:
196  return False
197 
198 def _get_color_for_representation(rep):
199  """Return an IMP.display.Color object (or None) for the given
200  Representation."""
201  if rep.color is not None:
202  if isinstance(rep.color, float):
203  return IMP.display.get_rgb_color(rep.color)
204  elif isinstance(rep.color, str):
205  return IMP.display.Color(*IMP.pmi.tools.color2rgb(rep.color))
206  elif hasattr(rep.color,'__iter__') and len(rep.color)==3:
207  return IMP.display.Color(*rep.color)
208  elif isinstance(rep.color, IMP.display.Color):
209  return rep.color
210  else:
211  raise TypeError("Color must be Chimera color name, a hex "
212  "string, a float or (r,g,b) tuple")
213 
214 def build_representation(parent, rep, coord_finder):
215  """Create requested representation.
216  For beads, identifies continuous segments and sets up as Representation.
217  If any volume-based representations (e.g.,densities) are requested,
218  will instead create a single Representation node.
219  All reps are added as children of the passed parent.
220  @param parent The Molecule to which we'll add add representations
221  @param rep What to build. An instance of pmi::topology::_Representation
222  @param coord_finder A _FindCloseStructure object to help localize beads
223  """
224  built_reps = []
225  atomic_res = 0
226  ca_res = 1
227  model = parent.hier.get_model()
228  color = _get_color_for_representation(rep)
229 
230  # first get the primary representation (currently, the smallest bead size)
231  # eventually we won't require beads to be present at all
232  primary_resolution = min(rep.bead_resolutions)
233 
234  # if collective densities, will return single node with everything
235  # below we sample or read the GMMs and add them as representation
236  single_node = False # flag indicating grouping nonlinear segments with one GMM
237  if rep.density_residues_per_component:
238  single_node = True
239  num_components = len(rep.residues)//rep.density_residues_per_component+1
240  rep_dict = defaultdict(list)
241  segp = IMP.Particle(model)
242  root_representation = IMP.atom.Representation.setup_particle(segp,
243  primary_resolution)
244  built_reps.append(root_representation)
245  res_nums = [r.get_index() for r in rep.residues]
246  IMP.atom.Fragment.setup_particle(segp,res_nums)
247  density_frag = IMP.atom.Fragment.setup_particle(IMP.Particle(model),res_nums)
248  density_frag.get_particle().set_name("Densities %i"%rep.density_residues_per_component)
249  density_ps = []
250 
251  if os.path.exists(rep.density_prefix+'.txt') and not rep.density_force_compute:
252  IMP.isd.gmm_tools.decorate_gmm_from_text(rep.density_prefix+'.txt',
253  density_ps,
254  model)
255  if len(density_ps)!=num_components or not os.path.exists(rep.density_prefix+'.txt') or rep.density_force_compute:
256  fit_coords = []
257  total_mass = 0.0
258  for r in rep.residues:
259  for p in IMP.core.get_leaves(r.hier):
260  fit_coords.append(IMP.core.XYZ(p).get_coordinates())
261  total_mass += IMP.atom.Mass(p).get_mass()
262 
263  # fit GMM
264  density_ps = []
266  num_components,
267  model,
268  density_ps,
269  min_covar=4.0,
270  mass_multiplier=total_mass)
271 
272  IMP.isd.gmm_tools.write_gmm_to_text(density_ps,rep.density_prefix+'.txt')
273  if rep.density_voxel_size>0.0:
274  IMP.isd.gmm_tools.write_gmm_to_map(density_ps,rep.density_prefix+'.mrc',
275  rep.density_voxel_size,fast=True)
276 
277  for n, d in enumerate(density_ps):
278  d.set_name('Density #%d' % n)
279  density_frag.add_child(d)
280  root_representation.add_representation(density_frag,
281  IMP.atom.DENSITIES,
282  rep.density_residues_per_component)
283 
284  # get continuous segments from residues
285  segments = []
286  rsort = sorted(list(rep.residues),key=lambda r:r.get_index())
287  prev_idx = rsort[0].get_index()-1
288  prev_structure = rsort[0].get_has_structure()
289  cur_seg = []
290  force_break = False
291  for nr,r in enumerate(rsort):
292  if r.get_index()!=prev_idx+1 or r.get_has_structure()!=prev_structure or force_break:
293  segments.append(cur_seg)
294  cur_seg = []
295  force_break = False
296  cur_seg.append(r)
297  prev_idx = r.get_index()
298  prev_structure = r.get_has_structure()
299  if r.get_index()-1 in rep.bead_extra_breaks:
300  force_break = True
301  if cur_seg!=[]:
302  segments.append(cur_seg)
303 
304  # for each segment, merge into beads
305  name_all = 'frags:'
306  name_count = 0
307  for frag_res in segments:
308  res_nums = [r.get_index() for r in frag_res]
309  rrange = "%i-%i"%(res_nums[0],res_nums[-1])
310  name = "Frag_"+rrange
311  if name_count<3:
312  name_all +=rrange+','
313  elif name_count==3:
314  name_all +='...'
315  name_count+=1
316  segp = IMP.Particle(model,name)
317  this_segment = IMP.atom.Fragment.setup_particle(segp,res_nums)
318  if not single_node:
319  this_representation = IMP.atom.Representation.setup_particle(segp,primary_resolution)
320  built_reps.append(this_representation)
321  for resolution in rep.bead_resolutions:
322  fp = IMP.Particle(model)
323  this_resolution = IMP.atom.Fragment.setup_particle(fp,res_nums)
324  this_resolution.set_name("%s: Res %i"%(name,resolution))
325  if frag_res[0].get_has_structure():
326  # if structured, merge particles as needed
327  if resolution==atomic_res:
328  for residue in frag_res:
329  this_resolution.add_child(residue.get_hierarchy())
330  elif resolution==ca_res and rep.bead_ca_centers:
331  beads = build_ca_centers(model,frag_res)
332  for bead in beads:
333  this_resolution.add_child(bead)
334  else:
335  tempc = IMP.atom.Chain.setup_particle(IMP.Particle(model),"X")
336  for residue in frag_res:
337  tempc.add_child(IMP.atom.create_clone(residue.hier))
338  beads = IMP.atom.create_simplified_along_backbone(tempc,resolution)
339  for bead in beads.get_children():
340  this_resolution.add_child(bead)
341  del tempc
342  del beads
343  else:
344  # if unstructured, create necklace
345  input_coord = coord_finder.find_nearest_coord(min(r.get_index() for r in frag_res))
346  if input_coord is None:
347  input_coord = rep.bead_default_coord
348  beads = build_necklace(model,
349  frag_res,
350  resolution,
351  input_coord)
352  for bead in beads:
353  this_resolution.add_child(bead)
354 
355  # if requested, color all resolutions the same
356  if color:
357  for lv in IMP.core.get_leaves(this_resolution):
359 
360  # finally decide where to put this resolution
361  # if volumetric, collect resolutions from different segments together
362  if single_node:
363  rep_dict[resolution]+=this_resolution.get_children()
364  else:
365  if resolution==primary_resolution:
366  this_representation.add_child(this_resolution)
367  else:
368  this_representation.add_representation(this_resolution,
369  IMP.atom.BALLS,
370  resolution)
371  # if individual beads to be setup as Gaussians:
372  if rep.setup_particles_as_densities:
373  for p in IMP.core.get_leaves(this_resolution):
374  setup_bead_as_gaussian(p)
375  this_resolution.set_name(this_resolution.get_name()+' Densities %i'%resolution)
376  this_representation.add_representation(this_resolution,
377  IMP.atom.DENSITIES,
378  resolution)
379 
380  if single_node:
381  root_representation.set_name(name_all.strip(',')+": Base")
382  d = root_representation.get_representations(IMP.atom.DENSITIES)
383  d[0].set_name('%s: '%name_all + d[0].get_name())
384  for resolution in rep.bead_resolutions:
385  this_resolution = IMP.atom.Fragment.setup_particle(
386  IMP.Particle(model),
387  [r.get_index() for r in rep.residues])
388  this_resolution.set_name("%s: Res %i"%(name_all,resolution))
389  for hier in rep_dict[resolution]:
390  this_resolution.add_child(hier)
391  if resolution==primary_resolution:
392  root_representation.add_child(this_resolution)
393  else:
394  root_representation.add_representation(this_resolution,
395  IMP.atom.BALLS,
396  resolution)
397  return built_reps
def list_chunks_iterator
Yield successive length-sized chunks from a list.
Definition: tools.py:974
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:24
static Gaussian setup_particle(Model *m, ParticleIndex pi)
Definition: core/Gaussian.h:48
void show_molecular_hierarchy(Hierarchy h)
Print out the molecular hierarchy.
static Fragment setup_particle(Model *m, ParticleIndex pi)
Definition: Fragment.h:63
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
Select atoms which are selected by both selectors.
Definition: pdb.h:348
double get_mass(ResidueType c)
Get the mass from the residue type.
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:157
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:1937
Warning related to handling of structures.
A Gaussian distribution in 3D.
Definition: Gaussian3D.h:24
def fit_gmm_to_points
fit a GMM to some points.
Definition: gmm_tools.py:231
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:234
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:473
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:113
A decorator for a residue.
Definition: Residue.h:134
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:309
Class to handle individual particles of a Model object.
Definition: Particle.h:41
Select all CA ATOM records.
Definition: pdb.h:77
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:62
Functionality for loading, creating, manipulating and scoring atomic structures.
static Chain setup_particle(Model *m, ParticleIndex pi, std::string id)
Definition: Chain.h:81
An exception for an invalid value being passed to IMP.
Definition: exception.h:137
Select hierarchy particles identified by the biological name.
Definition: Selection.h:66
Select all ATOM and HETATM records with the given chain ids.
Definition: pdb.h:189
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