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