IMP logo
IMP Reference Guide  2.6.2
The Integrative Modeling Platform
pmi/representation.py
1 #!/usr/bin/env python
2 
3 """@namespace IMP.pmi.representation
4  Representation of the system.
5 """
6 
7 from __future__ import print_function
8 import IMP
9 import IMP.core
10 import IMP.algebra
11 import IMP.atom
12 import IMP.display
13 import IMP.isd
14 import IMP.pmi
15 import IMP.pmi.tools
16 import IMP.pmi.output
17 import IMP.rmf
18 import IMP.pmi.topology
19 import RMF
20 from math import pi, sqrt
21 from operator import itemgetter
22 import os
23 
24 class Representation(object):
25  # Authors: Peter Cimermancic, Riccardo Pellarin, Charles Greenberg
26 
27  '''
28  Set up the representation of all proteins and nucleic acid macromolecules.
29 
30  Create the molecular hierarchies, representation,
31  sequence connectivity for the various involved proteins and
32  nucleic acid macromolecules:
33 
34  Create a protein, DNA or RNA, represent it as a set of connected balls of appropriate
35  radii and number of residues, PDB at given resolution(s), or ideal helices.
36 
37  How to use the SimplifiedModel class (typical use):
38 
39  see test/test_hierarchy_contruction.py
40 
41  examples:
42 
43  1) Create a chain of helices and flexible parts
44 
45  c_1_119 =self.add_component_necklace("prot1",1,119,20)
46  c_120_131 =self.add_component_ideal_helix("prot1",resolutions=[1,10],resrange=(120,131))
47  c_132_138 =self.add_component_beads("prot1",[(132,138)])
48  c_139_156 =self.add_component_ideal_helix("prot1",resolutions=[1,10],resrange=(139,156))
49  c_157_174 =self.add_component_beads("prot1",[(157,174)])
50  c_175_182 =self.add_component_ideal_helix("prot1",resolutions=[1,10],resrange=(175,182))
51  c_183_194 =self.add_component_beads("prot1",[(183,194)])
52  c_195_216 =self.add_component_ideal_helix("prot1",resolutions=[1,10],resrange=(195,216))
53  c_217_250 =self.add_component_beads("prot1",[(217,250)])
54 
55 
56  self.set_rigid_body_from_hierarchies(c_120_131)
57  self.set_rigid_body_from_hierarchies(c_139_156)
58  self.set_rigid_body_from_hierarchies(c_175_182)
59  self.set_rigid_body_from_hierarchies(c_195_216)
60 
61  clist=[c_1_119,c_120_131,c_132_138,c_139_156,c_157_174,c_175_182,c_183_194,c_195_216,
62  c_217_250]
63 
64  self.set_chain_of_super_rigid_bodies(clist,2,3)
65 
66  self.set_super_rigid_bodies(["prot1"])
67 
68  '''
69 
70  def __init__(self, m, upperharmonic=True, disorderedlength=True):
71  """Constructor.
72  @param m the model
73  @param upperharmonic This flag uses either harmonic (False)
74  or upperharmonic (True) in the intra-pair
75  connectivity restraint.
76  @param disorderedlength This flag uses either disordered length
77  calculated for random coil peptides (True) or zero
78  surface-to-surface distance between beads (False)
79  as optimal distance for the sequence connectivity
80  restraint.
81  """
82 
83  # this flag uses either harmonic (False) or upperharmonic (True)
84  # in the intra-pair connectivity restraint. Harmonic is used whe you want to
85  # remove the intra-ev term from energy calculations, e.g.:
86  # upperharmonic=False
87  # ip=self.get_connected_intra_pairs()
88  # ev.add_excluded_particle_pairs(ip)
89 
90  self.upperharmonic = upperharmonic
91  self.disorderedlength = disorderedlength
92  self.rigid_bodies = []
93  self.fixed_rigid_bodies = []
94  self.fixed_floppy_bodies = []
95  self.floppy_bodies = []
96  # self.super_rigid_bodies is a list of tuples.
97  # each tuple, corresponding to a particular super rigid body
98  # the tuple is (super_rigid_xyzs,super_rigid_rbs)
99  # where super_rigid_xyzs are the flexible xyz particles
100  # and super_rigid_rbs is the list of rigid bodies.
101  self.super_rigid_bodies = []
102  self.rigid_body_symmetries = []
103  self.output_level = "low"
104  self.label = "None"
105 
106  self.maxtrans_rb = 2.0
107  self.maxrot_rb = 0.04
108  self.maxtrans_srb = 2.0
109  self.maxrot_srb = 0.2
110  self.rigidbodiesarefixed = False
111  self.floppybodiesarefixed = False
112  self.maxtrans_fb = 3.0
113  self.resolution = 10.0
114  self.bblenght = 100.0
115  self.kappa = 100.0
116  self.m = m
117 
118  self.representation_is_modified = False
119  self.unmodeledregions_cr_dict = {}
120  self.sortedsegments_cr_dict = {}
122  self.connected_intra_pairs = []
123  self.hier_dict = {}
124  self.color_dict = {}
125  self.sequence_dict = {}
126  self.hier_geometry_pairs = {}
127  self.hier_db = IMP.pmi.tools.HierarchyDatabase()
128  # this dictionary stores the hierarchies by component name and representation type
129  # self.hier_representation[name][representation_type]
130  # where representation type is Res:X, Beads, Densities, Representation,
131  # etc...
132  self.hier_representation = {}
133  self.hier_resolution = {}
134  # reference structures is a dictionary that contains the coordinates of
135  # structures that are used to calculate the rmsd
136  self.reference_structures = {}
137  self.elements = {}
138  self.linker_restraints = IMP.RestraintSet(self.m, "linker_restraints")
139  self.linker_restraints_dict = {}
140  self.threetoone = {'ALA': 'A', 'ARG': 'R', 'ASN': 'N', 'ASP': 'D',
141  'CYS': 'C', 'GLU': 'E', 'GLN': 'Q', 'GLY': 'G',
142  'HIS': 'H', 'ILE': 'I', 'LEU': 'L', 'LYS': 'K',
143  'MET': 'M', 'PHE': 'F', 'PRO': 'P', 'SER': 'S',
144  'THR': 'T', 'TRP': 'W', 'TYR': 'Y', 'VAL': 'V', 'UNK': 'X'}
145 
146  self.onetothree = dict((v, k) for k, v in self.threetoone.items())
147 
148  self.residuenamekey = IMP.StringKey("ResidueName")
149 
150  def set_label(self, label):
151  self.label = label
152 
153  def create_component(self, name, color=0.0):
155  protein_h.set_name(name)
156  self.hier_dict[name] = protein_h
157  self.hier_representation[name] = {}
158  self.hier_db.add_name(name)
159  self.prot.add_child(protein_h)
160  self.color_dict[name] = color
161  self.elements[name] = []
162 
163  # Deprecation warning
164 
165  @IMP.deprecated_method("2.5", "Use create_component() instead.")
166  def add_component_name(self, *args, **kwargs):
167  self.create_component(*args, **kwargs)
168 
169  def get_component_names(self):
170  return list(self.hier_dict.keys())
171 
172  def add_component_sequence(self, name, filename, id=None, offs=None,
173  format="FASTA"):
174  '''
175  Add the primary sequence for a single component.
176 
177  @param name Human-readable name of the component
178  @param filename Name of the FASTA file
179  @param id Identifier of the sequence in the FASTA file header
180  (if not provided, use `name` instead)
181  '''
182  record_dict = IMP.pmi.topology.Sequences(filename)
183  if id is None:
184  id = name
185  if id not in record_dict:
186  raise KeyError("id %s not found in fasta file" % id)
187  length = len(record_dict[id])
188  self.sequence_dict[name] = str(record_dict[id])
189  if offs is not None:
190  offs_str="-"*offs
191  self.sequence_dict[name]=offs_str+self.sequence_dict[name]
192 
193  self.elements[name].append((length, length, " ", "end"))
194 
195  def autobuild_model(self, name, pdbname, chain,
196  resolutions=None, resrange=None,
197  missingbeadsize=20,
198  color=None, pdbresrange=None, offset=0,
199  show=False, isnucleicacid=False,
200  attachbeads=False):
201 
202  self.representation_is_modified = True
203  outhiers = []
204 
205  if color is None:
206  color = self.color_dict[name]
207  else:
208  self.color_dict[name] = color
209 
210  if resolutions is None:
211  resolutions = [1]
212  print("autobuild_model: constructing %s from pdb %s and chain %s" % (name, pdbname, str(chain)))
213 
214  # get the initial and end residues of the pdb
215  t = IMP.atom.read_pdb(pdbname, self.m,
217 
218  # find start and end indexes
219 
220  start = IMP.atom.Residue(
221  t.get_children()[0].get_children()[0]).get_index()
222  end = IMP.atom.Residue(
223  t.get_children()[0].get_children()[-1]).get_index()
224 
225  # check if resrange was defined, otherwise
226  # use the sequence, or the pdb resrange
227 
228  if resrange is None:
229  if name in self.sequence_dict:
230  resrange = (1, len(self.sequence_dict[name]))
231  else:
232  resrange = (start + offset, end + offset)
233  else:
234  if resrange[1]==-1:
235  resrange = (resrange[0],end)
236  start = resrange[0] - offset
237  end = resrange[1] - offset
238 
240  t,
241  resrange[0],
242  resrange[1])
243 
245  t,
246  resrange[0],
247  terminus="N")
249  t,
250  resrange[1],
251  terminus="C")
252 
253  # construct pdb fragments and intervening beads
254  for n, g in enumerate(gaps):
255  first = g[0]
256  last = g[1]
257  if g[2] == "cont":
258  print("autobuild_model: constructing fragment %s from pdb" % (str((first, last))))
259  outhiers += self.add_component_pdb(name, pdbname,
260  chain, resolutions=resolutions,
261  color=color, cacenters=True,
262  resrange=(first, last),
263  offset=offset, isnucleicacid=isnucleicacid)
264  elif g[2] == "gap" and n > 0:
265  print("autobuild_model: constructing fragment %s as a bead" % (str((first, last))))
266  parts = self.hier_db.get_particles_at_closest_resolution(name,
267  first + offset - 1,
268  1)
269  xyz = IMP.core.XYZ(parts[0]).get_coordinates()
270  outhiers += self.add_component_necklace(name,
271  first+offset, last+offset, missingbeadsize, incoord=xyz)
272 
273  elif g[2] == "gap" and n == 0:
274  # add pre-beads
275  print("autobuild_model: constructing fragment %s as a bead" % (str((first, last))))
276  outhiers += self.add_component_necklace(name,
277  first+offset, last+offset, missingbeadsize, incoord=xyznter)
278 
279  return outhiers
280 
281  # Deprecation warning
282 
283  @IMP.deprecated_method("2.5", "Use autobuild_model() instead.")
284  def autobuild_pdb_and_intervening_beads(self, *args, **kwargs):
285  r = self.autobuild_model(*args, **kwargs)
286  return r
287 
288  def add_component_pdb(self, name, pdbname, chain, resolutions, color=None,
289  resrange=None, offset=0, cacenters=True, show=False,
290  isnucleicacid=False, readnonwateratoms=False,
291  read_ca_cb_only=False):
292  '''
293  Add a component that has an associated 3D structure in a PDB file.
294 
295  Reads the PDB, and constructs the fragments corresponding to contiguous
296  sequence stretches.
297 
298  @return a list of hierarchies.
299 
300  @param name (string) the name of the component
301  @param pdbname (string) the name of the PDB file
302  @param chain (string or integer) can be either a string (eg, "A")
303  or an integer (eg, 0 or 1) in case you want
304  to get the corresponding chain number in the PDB.
305  @param resolutions (integers) a list of integers that corresponds
306  to the resolutions that have to be generated
307  @param color (float from 0 to 1) the color applied to the
308  hierarchies generated
309  @param resrange (tuple of integers): the residue range to extract
310  from the PDB. It is a tuple (beg,end). If not specified,
311  all residues belonging to the specified chain are read.
312  @param offset (integer) specifies the residue index offset to be
313  applied when reading the PDB (the FASTA sequence is
314  assumed to start from residue 1, so use this parameter
315  if the PDB file does not start at residue 1)
316  @param cacenters (boolean) if True generates resolution=1 beads
317  centered on C-alpha atoms.
318  @param show (boolean) print out the molecular hierarchy at the end.
319  @param isnucleicacid (boolean) use True if you're reading a PDB
320  with nucleic acids.
321  @param readnonwateratoms (boolean) if True fixes some pathological PDB.
322  @param read_ca_cb_only (boolean) if True, only reads CA/CB
323  '''
324 
325  self.representation_is_modified = True
326  if color is None:
327  # if the color is not passed, then get the stored color
328  color = self.color_dict[name]
329  protein_h = self.hier_dict[name]
330  outhiers = []
331 
332  # determine selector
334  if read_ca_cb_only:
335  cacbsel = IMP.atom.OrPDBSelector(
338  sel = IMP.atom.AndPDBSelector(cacbsel, sel)
339  if type(chain) == str:
342  sel)
343  t = IMP.atom.read_pdb(pdbname, self.m, sel)
344 
345  # get the first and last residue
346  start = IMP.atom.Residue(
347  t.get_children()[0].get_children()[0]).get_index()
348  end = IMP.atom.Residue(
349  t.get_children()[0].get_children()[-1]).get_index()
350  c = IMP.atom.Chain(IMP.atom.get_by_type(t, IMP.atom.CHAIN_TYPE)[0])
351  else:
352  t = IMP.atom.read_pdb(pdbname, self.m, sel)
353  c = IMP.atom.Chain(
354  IMP.atom.get_by_type(t, IMP.atom.CHAIN_TYPE)[chain])
355 
356  # get the first and last residue
357  start = IMP.atom.Residue(c.get_children()[0]).get_index()
358  end = IMP.atom.Residue(c.get_children()[-1]).get_index()
359  chain = c.get_id()
360 
361  if not resrange is None:
362  if resrange[0] > start:
363  start = resrange[0]
364  if resrange[1] < end:
365  end = resrange[1]
366 
367  if not isnucleicacid:
368  # do what you have to do for proteins
369  sel = IMP.atom.Selection(
370  c,
371  residue_indexes=list(range(
372  start,
373  end + 1)),
374  atom_type=IMP.atom.AT_CA)
375 
376  else:
377  # do what you have to do for nucleic-acids
378  # to work, nucleic acids should not be indicated as HETATM in the pdb
379  sel = IMP.atom.Selection(
380  c,
381  residue_indexes=list(range(
382  start,
383  end + 1)),
384  atom_type=IMP.atom.AT_P)
385 
386  ps = sel.get_selected_particles()
387  if len(ps) == 0:
388  raise ValueError("%s no residue found in pdb %s chain %s that overlaps with the queried stretch %s-%s" \
389  % (name, pdbname, str(chain), str(resrange[0]), str(resrange[1])))
391 
392  for p in ps:
393  par = IMP.atom.Atom(p).get_parent()
394  ri = IMP.atom.Residue(par).get_index()
395  IMP.atom.Residue(par).set_index(ri + offset)
396  c0.add_child(par)
397  start = start + offset
398  end = end + offset
399 
400  self.elements[name].append(
401  (start, end, pdbname.split("/")[-1] + ":" + chain, "pdb"))
402 
403  outhiers += self.coarse_hierarchy(name, start, end,
404  resolutions, isnucleicacid, c0, protein_h, "pdb", color)
405 
406  if show:
408 
409  del c
410  del c0
411  del t
412 
413  return outhiers
414 
415  def add_component_ideal_helix(
416  self,
417  name,
418  resolutions,
419  resrange,
420  color=None,
421  show=False):
422 
423  self.representation_is_modified = True
424  from math import pi, cos, sin
425 
426  protein_h = self.hier_dict[name]
427  outhiers = []
428  if color is None:
429  color = self.color_dict[name]
430 
431  start = resrange[0]
432  end = resrange[1]
433  self.elements[name].append((start, end, " ", "helix"))
435  for n, res in enumerate(range(start, end + 1)):
436  if name in self.sequence_dict:
437  try:
438  rtstr = self.onetothree[
439  self.sequence_dict[name][res-1]]
440  except:
441  rtstr = "UNK"
442  rt = IMP.atom.ResidueType(rtstr)
443  else:
444  rt = IMP.atom.ResidueType("ALA")
445 
446  # get the residue volume
447  try:
449  # mass=IMP.atom.get_mass_from_residue_type(rt)
450  except IMP.ValueException:
452  IMP.atom.ResidueType("ALA"))
453  # mass=IMP.atom.get_mass_from_residue_type(IMP.atom.ResidueType("ALA"))
455 
456  r = IMP.atom.Residue.setup_particle(IMP.Particle(self.m), rt, res)
457  p = IMP.Particle(self.m)
459  x = 2.3 * cos(n * 2 * pi / 3.6)
460  y = 2.3 * sin(n * 2 * pi / 3.6)
461  z = 6.2 / 3.6 / 2 * n * 2 * pi / 3.6
462  d.set_coordinates(IMP.algebra.Vector3D(x, y, z))
463  d.set_radius(radius)
464  # print d
465  a = IMP.atom.Atom.setup_particle(p, IMP.atom.AT_CA)
466  r.add_child(a)
467  c0.add_child(r)
468 
469  outhiers += self.coarse_hierarchy(name, start, end,
470  resolutions, False, c0, protein_h, "helix", color)
471 
472  if show:
474 
475  del c0
476  return outhiers
477 
478  def add_component_beads(self, name, ds, colors=None, incoord=None):
479  """ add beads to the representation
480  @param name the component name
481  @param ds a list of tuples corresponding to the residue ranges
482  of the beads
483  @param colors a list of colors associated to the beads
484  @param incoord the coordinate tuple corresponding to the position
485  of the beads
486  """
487 
488  from math import pi
489  self.representation_is_modified = True
490 
491  protein_h = self.hier_dict[name]
492  outhiers = []
493  if colors is None:
494  colors = [self.color_dict[name]]
495 
496 
497  for n, dss in enumerate(ds):
498  ds_frag = (dss[0], dss[1])
499  self.elements[name].append((dss[0], dss[1], " ", "bead"))
500  prt = IMP.Particle(self.m)
501  if ds_frag[0] == ds_frag[1]:
502  # if the bead represent a single residue
503  if name in self.sequence_dict:
504  try:
505  rtstr = self.onetothree[
506  self.sequence_dict[name][ds_frag[0]-1]]
507  except:
508  rtstr = "UNK"
509  rt = IMP.atom.ResidueType(rtstr)
510  else:
511  rt = IMP.atom.ResidueType("ALA")
512  h = IMP.atom.Residue.setup_particle(prt, rt, ds_frag[0])
513  h.set_name(name + '_%i_bead' % (ds_frag[0]))
514  prt.set_name(name + '_%i_bead' % (ds_frag[0]))
515  resolution = 1
516  else:
518  h.set_name(name + '_%i-%i_bead' % (ds_frag[0], ds_frag[1]))
519  prt.set_name(name + '_%i-%i_bead' % (ds_frag[0], ds_frag[1]))
520  h.set_residue_indexes(list(range(ds_frag[0], ds_frag[1] + 1)))
521  resolution = len(h.get_residue_indexes())
522  if "Beads" not in self.hier_representation[name]:
524  root.set_name("Beads")
525  self.hier_representation[name]["Beads"] = root
526  protein_h.add_child(root)
527  self.hier_representation[name]["Beads"].add_child(h)
528 
529  for kk in range(ds_frag[0], ds_frag[1] + 1):
530  self.hier_db.add_particles(name, kk, resolution, [h])
531 
532  try:
533  clr = IMP.display.get_rgb_color(colors[n])
534  except:
535  clr = IMP.display.get_rgb_color(colors[0])
536 
538 
539  # decorate particles according to their resolution
540  IMP.pmi.Resolution.setup_particle(prt, resolution)
541 
543  ptem = IMP.core.XYZR(prt)
545  if resolution == 1:
546  try:
548  except IMP.ValueException:
550  IMP.atom.ResidueType("ALA"))
553  ptem.set_radius(radius)
554  else:
555  volume = IMP.atom.get_volume_from_mass(mass)
556  radius = 0.8 * (3.0 / 4.0 / pi * volume) ** (1.0 / 3.0)
558  ptem.set_radius(radius)
559  try:
560  if not tuple(incoord) is None:
561  ptem.set_coordinates(incoord)
562  except TypeError:
563  pass
566  self.floppy_bodies.append(prt)
567  IMP.core.XYZ(prt).set_coordinates_are_optimized(True)
568  outhiers += [h]
569 
570  return outhiers
571 
572  def add_component_necklace(self, name, begin, end, length, color=None,
573  incoord=None):
574  '''
575  Generates a string of beads with given length.
576  '''
577  self.representation_is_modified = True
578  outhiers = []
579  if color is None:
580  colors=None
581  else:
582  colors=[color]
583  for chunk in IMP.pmi.tools.list_chunks_iterator(range(begin, end + 1), length):
584  outhiers += self.add_component_beads(name,
585  [(chunk[0], chunk[-1])], colors=colors,incoord=incoord)
586  return outhiers
587 
589  self, name, hierarchies=None, selection_tuples=None,
590  particles=None,
591  resolution=0.0, num_components=10,
592  inputfile=None, outputfile=None,
593  outputmap=None,
594  kernel_type=None,
595  covariance_type='full', voxel_size=1.0,
596  out_hier_name='',
597  sampled_points=1000000, num_iter=100,
598  simulation_res=1.0,
599  multiply_by_total_mass=True,
600  transform=None,
601  intermediate_map_fn=None,
602  density_ps_to_copy=None,
603  use_precomputed_gaussians=False):
604  '''
605  Sets up a Gaussian Mixture Model for this component.
606  Can specify input GMM file or it will be computed.
607  @param name component name
608  @param hierarchies set up GMM for some hierarchies
609  @param selection_tuples (list of tuples) example (first_residue,last_residue,component_name)
610  @param particles set up GMM for particles directly
611  @param resolution usual PMI resolution for selecting particles from the hierarchies
612  @param inputfile read the GMM from this file
613  @param outputfile fit and write the GMM to this file (text)
614  @param outputmap after fitting, create GMM density file (mrc)
615  @param kernel_type for creating the intermediate density (points are sampled to make GMM). Options are IMP.em.GAUSSIAN, IMP.em.SPHERE, and IMP.em.BINARIZED_SPHERE
616  @param covariance_type for fitting the GMM. options are 'full', 'diagonal' and 'spherical'
617  @param voxel_size for creating the intermediate density map and output map.
618  lower number increases accuracy but also rasterizing time grows
619  @param out_hier_name name of the output density hierarchy
620  @param sampled_points number of points to sample. more will increase accuracy and fitting time
621  @param num_iter num GMM iterations. more will increase accuracy and fitting time
622  @param multiply_by_total_mass multiply the weights of the GMM by this value (only works on creation!)
623  @param transform for input file only, apply a transformation (eg for multiple copies same GMM)
624  @param intermediate_map_fn for debugging, this will write the intermediate (simulated) map
625  @param density_ps_to_copy in case you already created the appropriate GMM (eg, for beads)
626  @param use_precomputed_gaussians Set this flag and pass fragments - will use roughly spherical Gaussian setup
627  '''
628  import numpy as np
629  import sys
630  import IMP.em
631  import IMP.isd.gmm_tools
632 
633  # prepare output
634  self.representation_is_modified = True
635  out_hier = []
636  protein_h = self.hier_dict[name]
637  if "Densities" not in self.hier_representation[name]:
639  root.set_name("Densities")
640  self.hier_representation[name]["Densities"] = root
641  protein_h.add_child(root)
642 
643  # gather passed particles
644  fragment_particles = []
645  if not particles is None:
646  fragment_particles += particles
647  if not hierarchies is None:
648  fragment_particles += IMP.pmi.tools.select(
649  self, resolution=resolution,
650  hierarchies=hierarchies)
651  if not selection_tuples is None:
652  for st in selection_tuples:
653  fragment_particles += IMP.pmi.tools.select_by_tuple(
654  self, tupleselection=st,
655  resolution=resolution,
656  name_is_ambiguous=False)
657 
658  # compute or read gaussians
659  density_particles = []
660  if inputfile:
662  inputfile, density_particles,
663  self.m, transform)
664  elif density_ps_to_copy:
665  for ip in density_ps_to_copy:
666  p = IMP.Particle(self.m)
667  shape = IMP.core.Gaussian(ip).get_gaussian()
668  mass = IMP.atom.Mass(ip).get_mass()
671  density_particles.append(p)
672  elif use_precomputed_gaussians:
673  if len(fragment_particles) == 0:
674  print("add_component_density: no particle was selected")
675  return out_hier
676  for p in fragment_particles:
677  if not (IMP.atom.Fragment.get_is_setup(self.m,p.get_particle_index()) and
678  IMP.core.XYZ.get_is_setup(self.m,p.get_particle_index())):
679  raise Exception("The particles you selected must be Fragments and XYZs")
680  nres=len(IMP.atom.Fragment(self.m,p.get_particle_index()).get_residue_indexes())
681  pos=IMP.core.XYZ(self.m,p.get_particle_index()).get_coordinates()
682  density_particles=[]
683  try:
684  IMP.isd.get_data_path("beads/bead_%i.txt"%nres)
685  except:
686  raise Exception("We haven't created a bead file for",nres,"residues")
687  transform = IMP.algebra.Transformation3D(pos)
689  IMP.isd.get_data_path("beads/bead_%i.txt"%nres), density_particles,
690  self.m, transform)
691  else:
692  #compute the gaussians here
693  if len(fragment_particles) == 0:
694  print("add_component_density: no particle was selected")
695  return out_hier
696 
697  density_particles = IMP.isd.gmm_tools.sample_and_fit_to_particles(
698  self.m,
699  fragment_particles,
700  num_components,
701  sampled_points,
702  simulation_res,
703  voxel_size,
704  num_iter,
705  covariance_type,
706  multiply_by_total_mass,
707  outputmap,
708  outputfile)
709 
710  # prepare output hierarchy
712  s0.set_name(out_hier_name)
713  self.hier_representation[name]["Densities"].add_child(s0)
714  out_hier.append(s0)
715  for nps, p in enumerate(density_particles):
716  s0.add_child(p)
717  p.set_name(s0.get_name() + '_gaussian_%i' % nps)
718  return out_hier
719 
720  def get_component_density(self, name):
721  return self.hier_representation[name]["Densities"]
722 
723  def add_all_atom_densities(self, name, hierarchies=None,
724  selection_tuples=None,
725  particles=None,
726  resolution=0,
727  output_map=None,
728  voxel_size=1.0):
729  '''Decorates all specified particles as Gaussians directly.
730  @param name component name
731  @param hierarchies set up GMM for some hierarchies
732  @param selection_tuples (list of tuples) example (first_residue,last_residue,component_name)
733  @param particles set up GMM for particles directly
734  @param resolution usual PMI resolution for selecting particles from the hierarchies
735  '''
736 
737  import IMP.em
738  import numpy as np
739  import sys
740  from math import sqrt
741  self.representation_is_modified = True
742 
743  if particles is None:
744  fragment_particles = []
745  else:
746  fragment_particles = particles
747 
748  if not hierarchies is None:
749  fragment_particles += IMP.pmi.tools.select(
750  self, resolution=resolution,
751  hierarchies=hierarchies)
752 
753  if not selection_tuples is None:
754  for st in selection_tuples:
755  fragment_particles += IMP.pmi.tools.select_by_tuple(
756  self, tupleselection=st,
757  resolution=resolution,
758  name_is_ambiguous=False)
759 
760  if len(fragment_particles) == 0:
761  print("add all atom densities: no particle was selected")
762  return
763 
764  # create a spherical gaussian for each particle based on atom type
765  print('setting up all atom gaussians num_particles',len(fragment_particles))
766  for n,p in enumerate(fragment_particles):
767  if IMP.core.Gaussian.get_is_setup(p): continue
768  center=IMP.core.XYZ(p).get_coordinates()
769  rad=IMP.core.XYZR(p).get_radius()
770  mass=IMP.atom.Mass(p).get_mass()
774  print('setting up particle',p.get_name(), " as individual gaussian particle")
775 
776  if not output_map is None:
777  print('writing map to', output_map)
779  fragment_particles,
780  output_map,
781  voxel_size)
782 
783  def add_component_hierarchy_clone(self, name, hierarchy):
784  '''
785  Make a copy of a hierarchy and append it to a component.
786  '''
787  outhier = []
788  self.representation_is_modified = True
789  protein_h = self.hier_dict[name]
790  hierclone = IMP.atom.create_clone(hierarchy)
791  hierclone.set_name(hierclone.get_name() + "_clone")
792  protein_h.add_child(hierclone)
793  outhier.append(hierclone)
794 
795  psmain = IMP.atom.get_leaves(hierarchy)
796  psclone = IMP.atom.get_leaves(hierclone)
797 
798  # copying attributes
799  for n, pmain in enumerate(psmain):
800  pclone = psclone[n]
802  resolution = IMP.pmi.Resolution(pmain).get_resolution()
803  IMP.pmi.Resolution.setup_particle(pclone, resolution)
804  for kk in IMP.pmi.tools.get_residue_indexes(pclone):
805  self.hier_db.add_particles(
806  name,
807  kk,
809  [pclone])
810 
812  uncertainty = IMP.pmi.Uncertainty(pmain).get_uncertainty()
813  IMP.pmi.Uncertainty.setup_particle(pclone, uncertainty)
814 
816  symmetric = IMP.pmi.Symmetric(pmain).get_symmetric()
817  IMP.pmi.Symmetric.setup_particle(pclone, symmetric)
818 
819  return outhier
820 
821  def dump_particle_descriptors(self):
822  import numpy
823  import pickle
824  import IMP.isd
825  import IMP.isd.gmm_tools
826 
827  particles_attributes={}
828  floppy_body_attributes={}
829  gaussians=[]
830  for h in IMP.atom.get_leaves(self.prot):
831  leaf=h
832  name=h.get_name()
833  hroot=self.prot
834  hparent=h.get_parent()
835  while hparent != hroot:
836  hparent=h.get_parent()
837  name+="|"+hparent.get_name()
838  h=hparent
839  particles_attributes[name]={"COORDINATES":numpy.array(IMP.core.XYZR(leaf.get_particle()).get_coordinates()),
840  "RADIUS":IMP.core.XYZR(leaf.get_particle()).get_radius(),
841  "MASS":IMP.atom.Mass(leaf.get_particle()).get_mass()}
842  if IMP.core.Gaussian.get_is_setup(leaf.get_particle()):
843  gaussians.append(IMP.core.Gaussian(leaf.get_particle()))
844 
845  rigid_body_attributes={}
846  for rb in self.rigid_bodies:
847  name=rb.get_name()
848  rf=rb.get_reference_frame()
849  t=rf.get_transformation_to()
850  trans=t.get_translation()
851  rot=t.get_rotation()
852  rigid_body_attributes[name]={"TRANSLATION":numpy.array(trans),
853  "ROTATION":numpy.array(rot.get_quaternion()),
854  "COORDINATES_NONRIGID_MEMBER":{},
855  "COORDINATES_RIGID_MEMBER":{}}
856  for mi in rb.get_member_indexes():
857  rm=self.m.get_particle(mi)
859  name_part=rm.get_name()
860  xyz=[self.m.get_attribute(fk, rm) for fk in [IMP.FloatKey(4), IMP.FloatKey(5), IMP.FloatKey(6)]]
861  rigid_body_attributes[name]["COORDINATES_NONRIGID_MEMBER"][name_part]=numpy.array(xyz)
862  else:
863  name_part=rm.get_name()
864  xyz=IMP.core.XYZ(rm).get_coordinates()
865  rigid_body_attributes[name]["COORDINATES_RIGID_MEMBER"][name_part]=numpy.array(xyz)
866 
867 
868  IMP.isd.gmm_tools.write_gmm_to_text(gaussians,"model_gmm.txt")
869  pickle.dump(particles_attributes,
870  open("particles_attributes.pkl", "wb"))
871  pickle.dump(rigid_body_attributes,
872  open("rigid_body_attributes.pkl", "wb"))
873 
874 
875 
876  def load_particle_descriptors(self):
877  import numpy
878  import pickle
879  import IMP.isd
880  import IMP.isd.gmm_tools
881 
882  particles_attributes = pickle.load(open("particles_attributes.pkl",
883  "rb"))
884  rigid_body_attributes = pickle.load(open("rigid_body_attributes.pkl",
885  "rb"))
886 
887  particles=[]
888  hierarchies=[]
889  gaussians=[]
890  for h in IMP.atom.get_leaves(self.prot):
891  leaf=h
892  name=h.get_name()
893  hroot=self.prot
894  hparent=h.get_parent()
895  while hparent != hroot:
896  hparent=h.get_parent()
897  name+="|"+hparent.get_name()
898  h=hparent
899 
900  xyzr=IMP.core.XYZR(leaf.get_particle())
901  xyzr.set_coordinates(particles_attributes[name]["COORDINATES"])
902  #xyzr.set_radius(particles_attributes[name]["RADIUS"])
903  #IMP.atom.Mass(leaf.get_particle()).set_mass(particles_attributes[name]["MASS"])
904  if IMP.core.Gaussian.get_is_setup(leaf.get_particle()):
905  gaussians.append(IMP.core.Gaussian(leaf.get_particle()))
906 
907  for rb in self.rigid_bodies:
908  name=rb.get_name()
909  trans=rigid_body_attributes[name]["TRANSLATION"]
910  rot=rigid_body_attributes[name]["ROTATION"]
913  rb.set_reference_frame(rf)
914  coor_nrm_ref=rigid_body_attributes[name]["COORDINATES_NONRIGID_MEMBER"]
915  coor_rm_ref_dict=rigid_body_attributes[name]["COORDINATES_RIGID_MEMBER"]
916  coor_rm_model=[]
917  coor_rm_ref=[]
918  for mi in rb.get_member_indexes():
919  rm=self.m.get_particle(mi)
921  name_part=rm.get_name()
922  xyz=coor_nrm_ref[name_part]
923  for n,fk in enumerate([IMP.FloatKey(4), IMP.FloatKey(5), IMP.FloatKey(6)]):
924  self.m.set_attribute(fk, rm,xyz[n])
925  else:
926  name_part=rm.get_name()
927  coor_rm_ref.append(IMP.algebra.Vector3D(coor_rm_ref_dict[name_part]))
928  coor_rm_model.append(IMP.core.XYZ(rm).get_coordinates())
929  if len(coor_rm_model)==0: continue
931  IMP.core.transform(rb,t)
932 
933  IMP.isd.gmm_tools.decorate_gmm_from_text("model_gmm.txt",gaussians,self.m)
934 
935  def set_coordinates_from_rmf(self, component_name, rmf_file_name,
936  rmf_frame_number,
937  rmf_component_name=None,
938  check_number_particles=True,
939  representation_name_to_rmf_name_map=None,
940  state_number=0,
941  save_file=False):
942  '''Read and replace coordinates from an RMF file.
943  Replace the coordinates of particles with the same name.
944  It assumes that the RMF and the representation have the particles
945  in the same order.
946  @param component_name Component name
947  @param rmf_component_name Name of the component in the RMF file
948  (if not specified, use `component_name`)
949  @param representation_name_to_rmf_name_map a dictionary that map
950  the original rmf particle name to the recipient particle component name
951  @param save_file: save a file with the names of particles of the component
952 
953  '''
954  import IMP.pmi.analysis
955 
956  prots = IMP.pmi.analysis.get_hiers_from_rmf(
957  self.m,
958  rmf_frame_number,
959  rmf_file_name)
960 
961  if not prots:
962  raise ValueError("cannot read hierarchy from rmf")
963 
964  prot=prots[0]
965 
966  # if len(self.rigid_bodies)!=0:
967  # print "set_coordinates_from_rmf: cannot proceed if rigid bodies were initialized. Use the function before defining the rigid bodies"
968  # exit()
969 
970  allpsrmf = IMP.atom.get_leaves(prot)
971 
972  psrmf = []
973  for p in allpsrmf:
974  (protname, is_a_bead) = IMP.pmi.tools.get_prot_name_from_particle(
975  p, self.hier_dict.keys())
976  if not rmf_component_name is None and protname == rmf_component_name:
977  psrmf.append(p)
978  elif rmf_component_name is None and protname == component_name:
979  psrmf.append(p)
980 
981  psrepr = IMP.atom.get_leaves(self.hier_dict[component_name])
982 
983  import itertools
984  reprnames=[p.get_name() for p in psrepr]
985  rmfnames=[p.get_name() for p in psrmf]
986 
987  if save_file:
988  fl=open(component_name+".txt","w")
989  for i in itertools.izip_longest(reprnames,rmfnames): fl.write(str(i[0])+","+str(i[1])+"\n")
990 
991 
992  if check_number_particles and not representation_name_to_rmf_name_map:
993  if len(psrmf) != len(psrepr):
994  fl=open(component_name+".txt","w")
995  for i in itertools.izip_longest(reprnames,rmfnames): fl.write(str(i[0])+","+str(i[1])+"\n")
996  raise ValueError("%s cannot proceed the rmf and the representation don't have the same number of particles; "
997  "particles in rmf: %s particles in the representation: %s" % (str(component_name), str(len(psrmf)), str(len(psrepr))))
998 
999 
1000  if not representation_name_to_rmf_name_map:
1001  for n, prmf in enumerate(psrmf):
1002 
1003  prmfname = prmf.get_name()
1004  preprname = psrepr[n].get_name()
1005  if IMP.core.RigidMember.get_is_setup(psrepr[n]):
1006  raise ValueError("component %s cannot proceed if rigid bodies were initialized. Use the function before defining the rigid bodies" % component_name)
1008  raise ValueError("component %s cannot proceed if rigid bodies were initialized. Use the function before defining the rigid bodies" % component_name)
1009 
1010  if prmfname != preprname:
1011  print("set_coordinates_from_rmf: WARNING rmf particle and representation particles have not the same name %s %s " % (prmfname, preprname))
1012  if IMP.core.XYZ.get_is_setup(prmf) and IMP.core.XYZ.get_is_setup(psrepr[n]):
1013  xyz = IMP.core.XYZ(prmf).get_coordinates()
1014  IMP.core.XYZ(psrepr[n]).set_coordinates(xyz)
1015  else:
1016  print("set_coordinates_from_rmf: WARNING particles are not XYZ decorated %s %s " % (str(IMP.core.XYZ.get_is_setup(prmf)), str(IMP.core.XYZ.get_is_setup(psrepr[n]))))
1017 
1019  gprmf=IMP.core.Gaussian(prmf)
1020  grepr=IMP.core.Gaussian(psrepr[n])
1021  g=gprmf.get_gaussian()
1022  grepr.set_gaussian(g)
1023 
1024 
1025  else:
1026  repr_name_particle_map={}
1027  rmf_name_particle_map={}
1028  for p in psrmf:
1029  rmf_name_particle_map[p.get_name()]=p
1030  #for p in psrepr:
1031  # repr_name_particle_map[p.get_name()]=p
1032 
1033  for prepr in psrepr:
1034  try:
1035  prmf=rmf_name_particle_map[representation_name_to_rmf_name_map[prepr.get_name()]]
1036  except KeyError:
1037  print("set_coordinates_from_rmf: WARNING missing particle name in representation_name_to_rmf_name_map, skipping...")
1038  continue
1039  xyz = IMP.core.XYZ(prmf).get_coordinates()
1040  IMP.core.XYZ(prepr).set_coordinates(xyz)
1041 
1042 
1043  def check_root(self, name, protein_h, resolution):
1044  '''
1045  If the root hierarchy does not exist, construct it.
1046  '''
1047  if "Res:" + str(int(resolution)) not in self.hier_representation[name]:
1049  root.set_name(name + "_Res:" + str(int(resolution)))
1050  self.hier_representation[name][
1051  "Res:" + str(int(resolution))] = root
1052  protein_h.add_child(root)
1053 
1054  def coarse_hierarchy(self, name, start, end, resolutions, isnucleicacid,
1055  input_hierarchy, protein_h, type, color):
1056  '''
1057  Generate all needed coarse grained layers.
1058 
1059  @param name name of the protein
1060  @param resolutions list of resolutions
1061  @param protein_h root hierarchy
1062  @param input_hierarchy hierarchy to coarse grain
1063  @param type a string, typically "pdb" or "helix"
1064  '''
1065  outhiers = []
1066 
1067  if (1 in resolutions) or (0 in resolutions):
1068  # in that case create residues and append atoms
1069 
1070  if 1 in resolutions:
1071  self.check_root(name, protein_h, 1)
1073  s1.set_name('%s_%i-%i_%s' % (name, start, end, type))
1074  # s1.set_residue_indexes(range(start,end+1))
1075  self.hier_representation[name]["Res:1"].add_child(s1)
1076  outhiers += [s1]
1077  if 0 in resolutions:
1078  self.check_root(name, protein_h, 0)
1080  s0.set_name('%s_%i-%i_%s' % (name, start, end, type))
1081  # s0.set_residue_indexes(range(start,end+1))
1082  self.hier_representation[name]["Res:0"].add_child(s0)
1083  outhiers += [s0]
1084 
1085  if not isnucleicacid:
1086  sel = IMP.atom.Selection(
1087  input_hierarchy,
1088  atom_type=IMP.atom.AT_CA)
1089  else:
1090  sel = IMP.atom.Selection(
1091  input_hierarchy,
1092  atom_type=IMP.atom.AT_P)
1093 
1094  for p in sel.get_selected_particles():
1095  resobject = IMP.atom.Residue(IMP.atom.Atom(p).get_parent())
1096  if 0 in resolutions:
1097  # if you ask for atoms
1098  resclone0 = IMP.atom.create_clone(resobject)
1099  resindex = IMP.atom.Residue(resclone0).get_index()
1100  s0.add_child(resclone0)
1101  self.hier_db.add_particles(
1102  name,
1103  resindex,
1104  0,
1105  resclone0.get_children())
1106 
1107  chil = resclone0.get_children()
1108  for ch in chil:
1110  try:
1111  clr = IMP.display.get_rgb_color(color)
1112  except:
1113  clr = IMP.display.get_rgb_color(1.0)
1115 
1116  if 1 in resolutions:
1117  # else clone the residue
1118  resclone1 = IMP.atom.create_clone_one(resobject)
1119  resindex = IMP.atom.Residue(resclone1).get_index()
1120  s1.add_child(resclone1)
1121  self.hier_db.add_particles(name, resindex, 1, [resclone1])
1122 
1123  rt = IMP.atom.Residue(resclone1).get_residue_type()
1124  xyz = IMP.core.XYZ(p).get_coordinates()
1125  prt = resclone1.get_particle()
1126  prt.set_name('%s_%i_%s' % (name, resindex, type))
1127  IMP.core.XYZ.setup_particle(prt).set_coordinates(xyz)
1128 
1129  try:
1131  # mass=IMP.atom.get_mass_from_residue_type(rt)
1132  except IMP.ValueException:
1134  IMP.atom.ResidueType("ALA"))
1135  # mass=IMP.atom.get_mass_from_residue_type(IMP.atom.ResidueType("ALA"))
1137  IMP.core.XYZR.setup_particle(prt).set_radius(radius)
1142  try:
1143  clr = IMP.display.get_rgb_color(color)
1144  except:
1145  clr = IMP.display.get_rgb_color(1.0)
1147 
1148  for r in resolutions:
1149  if r != 0 and r != 1:
1150  self.check_root(name, protein_h, r)
1152  input_hierarchy,
1153  r)
1154 
1155  chil = s.get_children()
1157  s0.set_name('%s_%i-%i_%s' % (name, start, end, type))
1158  # s0.set_residue_indexes(range(start,end+1))
1159  for ch in chil:
1160  s0.add_child(ch)
1161  self.hier_representation[name][
1162  "Res:" + str(int(r))].add_child(s0)
1163  outhiers += [s0]
1164  del s
1165 
1166  for prt in IMP.atom.get_leaves(s0):
1167  ri = IMP.atom.Fragment(prt).get_residue_indexes()
1168  first = ri[0]
1169  last = ri[-1]
1170  if first == last:
1171  prt.set_name('%s_%i_%s' % (name, first, type))
1172  else:
1173  prt.set_name('%s_%i_%i_%s' % (name, first, last, type))
1174  for kk in ri:
1175  self.hier_db.add_particles(name, kk, r, [prt])
1176 
1177  radius = IMP.core.XYZR(prt).get_radius()
1181 
1182  # setting up color for each particle in the
1183  # hierarchy, if colors missing in the colors list set it to
1184  # red
1185  try:
1186  clr = IMP.display.get_rgb_color(color)
1187  except:
1188  colors.append(1.0)
1189  clr = IMP.display.get_rgb_color(colors[pdb_part_count])
1191 
1192  return outhiers
1193 
1195  '''
1196  Get the hierarchies at the given resolution.
1197 
1198  The map between resolution and hierarchies is cached to accelerate
1199  the selection algorithm. The cache is invalidated when the
1200  representation was changed by any add_component_xxx.
1201  '''
1202 
1203  if self.representation_is_modified:
1204  rhbr = self.hier_db.get_all_root_hierarchies_by_resolution(
1205  resolution)
1206  self.hier_resolution[resolution] = rhbr
1207  self.representation_is_modified = False
1208  return rhbr
1209  else:
1210  if resolution in self.hier_resolution:
1211  return self.hier_resolution[resolution]
1212  else:
1213  rhbr = self.hier_db.get_all_root_hierarchies_by_resolution(
1214  resolution)
1215  self.hier_resolution[resolution] = rhbr
1216  return rhbr
1217 
1219  self, max_translation=300., max_rotation=2.0 * pi,
1220  avoidcollision=True, cutoff=10.0, niterations=100,
1221  bounding_box=None,
1222  excluded_rigid_bodies=None,
1223  hierarchies_excluded_from_collision=None):
1224  '''
1225  Shuffle configuration; used to restart the optimization.
1226 
1227  The configuration of the system is initialized by placing each
1228  rigid body and each bead randomly in a box with a side of
1229  `max_translation` angstroms, and far enough from each other to
1230  prevent any steric clashes. The rigid bodies are also randomly rotated.
1231 
1232  @param avoidcollision check if the particle/rigid body was
1233  placed close to another particle; uses the optional
1234  arguments cutoff and niterations
1235  @param bounding_box defined by ((x1,y1,z1),(x2,y2,z2))
1236  '''
1237 
1238  if excluded_rigid_bodies is None:
1239  excluded_rigid_bodies = []
1240  if hierarchies_excluded_from_collision is None:
1241  hierarchies_excluded_from_collision = []
1242 
1243  if len(self.rigid_bodies) == 0:
1244  print("shuffle_configuration: rigid bodies were not intialized")
1245 
1247  gcpf.set_distance(cutoff)
1248  ps = []
1249  hierarchies_excluded_from_collision_indexes = []
1250  for p in IMP.atom.get_leaves(self.prot):
1252  ps.append(p)
1254  # remove the densities particles out of the calculation
1255  hierarchies_excluded_from_collision_indexes += IMP.get_indexes([p])
1256  allparticleindexes = IMP.get_indexes(ps)
1257 
1258  if not bounding_box is None:
1259  ((x1, y1, z1), (x2, y2, z2)) = bounding_box
1260  ub = IMP.algebra.Vector3D(x1, y1, z1)
1261  lb = IMP.algebra.Vector3D(x2, y2, z2)
1262  bb = IMP.algebra.BoundingBox3D(ub, lb)
1263 
1264  for h in hierarchies_excluded_from_collision:
1265  hierarchies_excluded_from_collision_indexes += IMP.get_indexes(IMP.atom.get_leaves(h))
1266 
1267 
1268  allparticleindexes = list(
1269  set(allparticleindexes) - set(hierarchies_excluded_from_collision_indexes))
1270 
1271  print(hierarchies_excluded_from_collision)
1272  print(len(allparticleindexes),len(hierarchies_excluded_from_collision_indexes))
1273 
1274  for rb in self.rigid_bodies:
1275  if rb not in excluded_rigid_bodies:
1276  if avoidcollision:
1277 
1278  rbindexes = rb.get_member_particle_indexes()
1279 
1280  rbindexes = list(
1281  set(rbindexes) - set(hierarchies_excluded_from_collision_indexes))
1282  otherparticleindexes = list(
1283  set(allparticleindexes) - set(rbindexes))
1284 
1285  if len(otherparticleindexes) is None:
1286  continue
1287 
1288  niter = 0
1289  while niter < niterations:
1290  rbxyz = (rb.get_x(), rb.get_y(), rb.get_z())
1291 
1292  if not bounding_box is None:
1293  # overrides the perturbation
1294  translation = IMP.algebra.get_random_vector_in(bb)
1295  old_coord=IMP.core.XYZ(rb).get_coordinates()
1297  transformation = IMP.algebra.Transformation3D(
1298  rotation,
1299  translation-old_coord)
1300  else:
1302  rbxyz,
1303  max_translation,
1304  max_rotation)
1305 
1306  IMP.core.transform(rb, transformation)
1307 
1308  if avoidcollision:
1309  self.m.update()
1310  npairs = len(
1311  gcpf.get_close_pairs(
1312  self.m,
1313  otherparticleindexes,
1314  rbindexes))
1315  if npairs == 0:
1316  niter = niterations
1317  else:
1318  niter += 1
1319  print("shuffle_configuration: rigid body placed close to other %d particles, trying again..." % npairs)
1320  print("shuffle_configuration: rigid body name: " + rb.get_name())
1321  if niter == niterations:
1322  raise ValueError("tried the maximum number of iterations to avoid collisions, increase the distance cutoff")
1323  else:
1324  break
1325 
1326  print('shuffling', len(self.floppy_bodies), 'floppy bodies')
1327  for fb in self.floppy_bodies:
1328  if avoidcollision:
1331  if rm and nrm:
1332  fbindexes = IMP.get_indexes([fb])
1333  otherparticleindexes = list(
1334  set(allparticleindexes) - set(fbindexes))
1335  if len(otherparticleindexes) is None:
1336  continue
1337  else:
1338  continue
1339 
1340  niter = 0
1341  while niter < niterations:
1342  fbxyz = IMP.core.XYZ(fb).get_coordinates()
1343  if not bounding_box is None:
1344  # overrides the perturbation
1345  translation = IMP.algebra.get_random_vector_in(bb)
1346  transformation = IMP.algebra.Transformation3D(translation-fbxyz)
1347  else:
1349  fbxyz,
1350  max_translation,
1351  max_rotation)
1352 
1354  d=IMP.core.RigidBodyMember(fb).get_rigid_body()
1356  d=IMP.core.RigidBody(fb)
1357  elif IMP.core.XYZ.get_is_setup(fb):
1358  d=IMP.core.XYZ(fb)
1359 
1360  IMP.core.transform(d, transformation)
1361 
1362  if avoidcollision:
1363  self.m.update()
1364  npairs = len(
1365  gcpf.get_close_pairs(
1366  self.m,
1367  otherparticleindexes,
1368  fbindexes))
1369  if npairs == 0:
1370  niter = niterations
1371  else:
1372  niter += 1
1373  print("shuffle_configuration: floppy body placed close to other %d particles, trying again..." % npairs)
1374  if niter == niterations:
1375  raise ValueError("tried the maximum number of iterations to avoid collisions, increase the distance cutoff")
1376  else:
1377  break
1378 
1379  def set_current_coordinates_as_reference_for_rmsd(self, label="None"):
1380  # getting only coordinates from pdb
1381  ps = IMP.pmi.tools.select(self, resolution=1.0)
1382  # storing the reference coordinates and the particles
1383  self.reference_structures[label] = (
1384  [IMP.core.XYZ(p).get_coordinates() for p in ps],
1385  ps)
1386 
1387  def get_all_rmsds(self):
1388  rmsds = {}
1389 
1390  for label in self.reference_structures:
1391 
1392  current_coordinates = [IMP.core.XYZ(p).get_coordinates()
1393  for p in self.reference_structures[label][1]]
1394  reference_coordinates = self.reference_structures[label][0]
1395  if len(reference_coordinates) != len(current_coordinates):
1396  print("calculate_all_rmsds: reference and actual coordinates are not the same")
1397  continue
1399  current_coordinates,
1400  reference_coordinates)
1401  rmsd_global = IMP.algebra.get_rmsd(
1402  reference_coordinates,
1403  current_coordinates)
1404  # warning: temporary we are calculating the drms, and not the rmsd,
1405  # for the relative distance
1406  rmsd_relative = IMP.atom.get_drms(
1407  reference_coordinates,
1408  current_coordinates)
1409  rmsds[label + "_GlobalRMSD"] = rmsd_global
1410  rmsds[label + "_RelativeDRMS"] = rmsd_relative
1411  return rmsds
1412 
1413  def setup_component_geometry(self, name, color=None, resolution=1.0):
1414  if color is None:
1415  color = self.color_dict[name]
1416  # this function stores all particle pairs
1417  # ordered by residue number, to be used
1418  # to construct backbone traces
1419  self.hier_geometry_pairs[name] = []
1420  protein_h = self.hier_dict[name]
1421  pbr = IMP.pmi.tools.select(self, name=name, resolution=resolution)
1422  pbr = IMP.pmi.tools.sort_by_residues(pbr)
1423 
1424  for n in range(len(pbr) - 1):
1425  self.hier_geometry_pairs[name].append((pbr[n], pbr[n + 1], color))
1426 
1428  self, name, resolution=10, scale=1.0):
1429  '''
1430  Generate restraints between contiguous fragments in the hierarchy.
1431  The linkers are generated at resolution 10 by default.
1432 
1433  '''
1434 
1435  unmodeledregions_cr = IMP.RestraintSet(self.m, "unmodeledregions")
1436  sortedsegments_cr = IMP.RestraintSet(self.m, "sortedsegments")
1437 
1438  protein_h = self.hier_dict[name]
1439  SortedSegments = []
1440  frs = self.hier_db.get_preroot_fragments_by_resolution(
1441  name,
1442  resolution)
1443 
1444  for fr in frs:
1445  try:
1446  start = fr.get_children()[0]
1447  except:
1448  start = fr
1449 
1450  try:
1451  end = fr.get_children()[-1]
1452  except:
1453  end = fr
1454 
1455  startres = IMP.pmi.tools.get_residue_indexes(start)[0]
1456  endres = IMP.pmi.tools.get_residue_indexes(end)[-1]
1457  SortedSegments.append((start, end, startres))
1458  SortedSegments = sorted(SortedSegments, key=itemgetter(2))
1459 
1460  # connect the particles
1461  for x in range(len(SortedSegments) - 1):
1462  last = SortedSegments[x][1]
1463  first = SortedSegments[x + 1][0]
1464 
1465  nreslast = len(IMP.pmi.tools.get_residue_indexes(last))
1466  lastresn = IMP.pmi.tools.get_residue_indexes(last)[-1]
1467  nresfirst = len(IMP.pmi.tools.get_residue_indexes(first))
1468  firstresn = IMP.pmi.tools.get_residue_indexes(first)[0]
1469 
1470  residuegap = firstresn - lastresn - 1
1471  if self.disorderedlength and (nreslast / 2 + nresfirst / 2 + residuegap) > 20.0:
1472  # calculate the distance between the sphere centers using Kohn
1473  # PNAS 2004
1474  optdist = sqrt(5 / 3) * 1.93 * \
1475  (nreslast / 2 + nresfirst / 2 + residuegap) ** 0.6
1476  # optdist2=sqrt(5/3)*1.93*((nreslast)**0.6+(nresfirst)**0.6)/2
1477  if self.upperharmonic:
1478  hu = IMP.core.HarmonicUpperBound(optdist, self.kappa)
1479  else:
1480  hu = IMP.core.Harmonic(optdist, self.kappa)
1481  dps = IMP.core.DistancePairScore(hu)
1482  else: # default
1483  optdist = (0.0 + (float(residuegap) + 1.0) * 3.6) * scale
1484  if self.upperharmonic: # default
1485  hu = IMP.core.HarmonicUpperBound(optdist, self.kappa)
1486  else:
1487  hu = IMP.core.Harmonic(optdist, self.kappa)
1489 
1490  pt0 = last.get_particle()
1491  pt1 = first.get_particle()
1492  r = IMP.core.PairRestraint(self.m, dps, (pt0.get_index(), pt1.get_index()))
1493 
1494  print("Adding sequence connectivity restraint between", pt0.get_name(), " and ", pt1.get_name(), 'of distance', optdist)
1495  sortedsegments_cr.add_restraint(r)
1496  self.linker_restraints_dict[
1497  "LinkerRestraint-" + pt0.get_name() + "-" + pt1.get_name()] = r
1498  self.connected_intra_pairs.append((pt0, pt1))
1499  self.connected_intra_pairs.append((pt1, pt0))
1500 
1501  self.linker_restraints.add_restraint(sortedsegments_cr)
1502  self.linker_restraints.add_restraint(unmodeledregions_cr)
1503  IMP.pmi.tools.add_restraint_to_model(self.m, self.linker_restraints)
1504  self.sortedsegments_cr_dict[name] = sortedsegments_cr
1505  self.unmodeledregions_cr_dict[name] = unmodeledregions_cr
1506 
1507  def optimize_floppy_bodies(self, nsteps, temperature=1.0):
1508  import IMP.pmi.samplers
1509  pts = IMP.pmi.tools.ParticleToSampleList()
1510  for n, fb in enumerate(self.floppy_bodies):
1511  pts.add_particle(fb, "Floppy_Bodies", 1.0, "Floppy_Body_" + str(n))
1512  if len(pts.get_particles_to_sample()) > 0:
1513  mc = IMP.pmi.samplers.MonteCarlo(self.m, [pts], temperature)
1514  print("optimize_floppy_bodies: optimizing %i floppy bodies" % len(self.floppy_bodies))
1515  mc.optimize(nsteps)
1516  else:
1517  print("optimize_floppy_bodies: no particle to optimize")
1518 
1519  def create_rotational_symmetry(self, maincopy, copies):
1520  from math import pi
1521  self.representation_is_modified = True
1522  ncopies = len(copies) + 1
1523 
1524  sel = IMP.atom.Selection(self.prot, molecule=maincopy)
1525  mainparticles = sel.get_selected_particles()
1526 
1527  for k in range(len(copies)):
1529  IMP.algebra.Vector3D(0, 0, 1), 2 * pi / ncopies * (k + 1))
1530  sm = IMP.core.TransformationSymmetry(rotation3D)
1531 
1532  sel = IMP.atom.Selection(self.prot, molecule=copies[k])
1533  copyparticles = sel.get_selected_particles()
1534 
1535  mainpurged = []
1536  copypurged = []
1537  for n, p in enumerate(mainparticles):
1538  print(p.get_name())
1539  pc = copyparticles[n]
1540 
1541  mainpurged.append(p)
1543 
1544  copypurged.append(pc)
1546 
1548  for n, p in enumerate(mainpurged):
1549 
1550  pc = copypurged[n]
1551  print("setting " + p.get_name() + " as reference for " + pc.get_name())
1552 
1554  lc.add(pc.get_index())
1555 
1556  c = IMP.container.SingletonsConstraint(sm, None, lc)
1557  self.m.add_score_state(c)
1558 
1559  self.m.update()
1560 
1561 
1562  def create_rigid_body_symmetry(self, particles_reference, particles_copy,label="None",
1563  initial_transformation=IMP.algebra.get_identity_transformation_3d()):
1564  from math import pi
1565  self.representation_is_modified = True
1566 
1567  mainparticles = particles_reference
1568 
1569  t=initial_transformation
1570  p=IMP.Particle(self.m)
1571  p.set_name("RigidBody_Symmetry")
1573 
1575 
1576 
1577  copyparticles = particles_copy
1578 
1579  mainpurged = []
1580  copypurged = []
1581  for n, p in enumerate(mainparticles):
1582  print(p.get_name())
1583  pc = copyparticles[n]
1584 
1585  mainpurged.append(p)
1588  else:
1589  IMP.pmi.Symmetric(p).set_symmetric(0)
1590 
1591  copypurged.append(pc)
1592  if not IMP.pmi.Symmetric.get_is_setup(pc):
1594  else:
1595  IMP.pmi.Symmetric(pc).set_symmetric(1)
1596 
1598  for n, p in enumerate(mainpurged):
1599 
1600  pc = copypurged[n]
1601  print("setting " + p.get_name() + " as reference for " + pc.get_name())
1602 
1604  lc.add(pc.get_index())
1605 
1606  c = IMP.container.SingletonsConstraint(sm, None, lc)
1607  self.m.add_score_state(c)
1608 
1609  self.m.update()
1610  self.rigid_bodies.append(rb)
1611  self.rigid_body_symmetries.append(rb)
1612  rb.set_name(label+".rigid_body_symmetry."+str(len(self.rigid_body_symmetries)))
1613 
1614 
1615  def create_amyloid_fibril_symmetry(self, maincopy, axial_copies,
1616  longitudinal_copies, axis=(0, 0, 1), translation_value=4.8):
1617 
1618  from math import pi
1619  self.representation_is_modified = True
1620 
1621  outhiers = []
1622  protein_h = self.hier_dict[maincopy]
1623  mainparts = IMP.atom.get_leaves(protein_h)
1624 
1625  for ilc in range(-longitudinal_copies, longitudinal_copies + 1):
1626  for iac in range(axial_copies):
1627  copyname = maincopy + "_a" + str(ilc) + "_l" + str(iac)
1628  self.create_component(copyname, 0.0)
1629  for hier in protein_h.get_children():
1630  self.add_component_hierarchy_clone(copyname, hier)
1631  copyhier = self.hier_dict[copyname]
1632  outhiers.append(copyhier)
1633  copyparts = IMP.atom.get_leaves(copyhier)
1635  IMP.algebra.Vector3D(axis),
1636  2 * pi / axial_copies * (float(iac)))
1637  translation_vector = tuple(
1638  [translation_value * float(ilc) * x for x in axis])
1639  print(translation_vector)
1640  translation = IMP.algebra.Vector3D(translation_vector)
1642  IMP.algebra.Transformation3D(rotation3D, translation))
1644  for n, p in enumerate(mainparts):
1645  pc = copyparts[n]
1648  if not IMP.pmi.Symmetric.get_is_setup(pc):
1651  lc.add(pc.get_index())
1652  c = IMP.container.SingletonsConstraint(sm, None, lc)
1653  self.m.add_score_state(c)
1654  self.m.update()
1655  return outhiers
1656 
1657  def link_components_to_rmf(self, rmfname, frameindex):
1658  '''
1659  Load coordinates in the current representation.
1660  This should be done only if the hierarchy self.prot is identical
1661  to the one as stored in the rmf i.e. all components were added.
1662  '''
1663  import IMP.rmf
1664  import RMF
1665 
1666  rh = RMF.open_rmf_file_read_only(rmfname)
1667  IMP.rmf.link_hierarchies(rh, [self.prot])
1668  IMP.rmf.load_frame(rh, RMF.FrameID(frameindex))
1669  del rh
1670 
1671  def create_components_from_rmf(self, rmfname, frameindex):
1672  '''
1673  still not working.
1674  create the representation (i.e. hierarchies) from the rmf file.
1675  it will be stored in self.prot, which will be overwritten.
1676  load the coordinates from the rmf file at frameindex.
1677  '''
1678  rh = RMF.open_rmf_file(rmfname)
1679  self.prot = IMP.rmf.create_hierarchies(rh, self.m)[0]
1681  IMP.rmf.link_hierarchies(rh, [self.prot])
1682  IMP.rmf.load_frame(rh, RMF.FrameID(frameindex))
1683  del rh
1684  for p in self.prot.get_children():
1685  self.create_component(p.get_name())
1686  self.hier_dict[p.get_name()] = p
1687  '''
1688  still missing: save rigid bodies contained in the rmf in self.rigid_bodies
1689  save floppy bodies in self.floppy_bodies
1690  get the connectivity restraints
1691  '''
1692 
1693  def set_rigid_body_from_hierarchies(self, hiers, particles=None):
1694  '''
1695  Construct a rigid body from hierarchies (and optionally particles).
1696 
1697  @param hiers list of hierarchies to make rigid
1698  @param particles list of particles to add to the rigid body
1699  '''
1700 
1701  if particles is None:
1702  rigid_parts = set()
1703  else:
1704  rigid_parts = set(particles)
1705 
1706  name = ""
1707  print("set_rigid_body_from_hierarchies> setting up a new rigid body")
1708  for hier in hiers:
1709  ps = IMP.atom.get_leaves(hier)
1710 
1711  for p in ps:
1713  rb = IMP.core.RigidMember(p).get_rigid_body()
1714  print("set_rigid_body_from_hierarchies> WARNING particle %s already belongs to rigid body %s" % (p.get_name(), rb.get_name()))
1715  else:
1716  rigid_parts.add(p)
1717  name += hier.get_name() + "-"
1718  print("set_rigid_body_from_hierarchies> adding %s to the rigid body" % hier.get_name())
1719 
1720  if len(list(rigid_parts)) != 0:
1721  rb = IMP.atom.create_rigid_body(list(rigid_parts))
1722  rb.set_coordinates_are_optimized(True)
1723  rb.set_name(name + "rigid_body")
1724  self.rigid_bodies.append(rb)
1725  return rb
1726 
1727  else:
1728  print("set_rigid_body_from_hierarchies> rigid body could not be setup")
1729 
1730  def set_rigid_bodies(self, subunits):
1731  '''
1732  Construct a rigid body from a list of subunits.
1733 
1734  Each subunit is a tuple that identifies the residue ranges and the
1735  component name (as used in create_component()).
1736 
1737  subunits: [(name_1,(first_residue_1,last_residue_1)),(name_2,(first_residue_2,last_residue_2)),.....]
1738  or
1739  [name_1,name_2,(name_3,(first_residue_3,last_residue_3)),.....]
1740 
1741  example: ["prot1","prot2",("prot3",(1,10))]
1742 
1743  sometimes, we know about structure of an interaction
1744  and here we make such PPIs rigid
1745  '''
1746 
1747  rigid_parts = set()
1748  for s in subunits:
1749  if type(s) == type(tuple()) and len(s) == 2:
1750  sel = IMP.atom.Selection(
1751  self.prot,
1752  molecule=s[0],
1753  residue_indexes=list(range(s[1][0],
1754  s[1][1] + 1)))
1755  if len(sel.get_selected_particles()) == 0:
1756  print("set_rigid_bodies: selected particle does not exist")
1757  for p in sel.get_selected_particles():
1758  # if not p in self.floppy_bodies:
1760  rb = IMP.core.RigidMember(p).get_rigid_body()
1761  print("set_rigid_body_from_hierarchies> WARNING particle %s already belongs to rigid body %s" % (p.get_name(), rb.get_name()))
1762  else:
1763  rigid_parts.add(p)
1764 
1765  elif type(s) == type(str()):
1766  sel = IMP.atom.Selection(self.prot, molecule=s)
1767  if len(sel.get_selected_particles()) == 0:
1768  print("set_rigid_bodies: selected particle does not exist")
1769  for p in sel.get_selected_particles():
1770  # if not p in self.floppy_bodies:
1772  rb = IMP.core.RigidMember(p).get_rigid_body()
1773  print("set_rigid_body_from_hierarchies> WARNING particle %s already belongs to rigid body %s" % (p.get_name(), rb.get_name()))
1774  else:
1775  rigid_parts.add(p)
1776 
1777  rb = IMP.atom.create_rigid_body(list(rigid_parts))
1778  rb.set_coordinates_are_optimized(True)
1779  rb.set_name(''.join(str(subunits)) + "_rigid_body")
1780  self.rigid_bodies.append(rb)
1781  return rb
1782 
1783  def set_super_rigid_body_from_hierarchies(
1784  self,
1785  hiers,
1786  axis=None,
1787  min_size=0):
1788  # axis is the rotation axis for 2D rotation
1789  super_rigid_xyzs = set()
1790  super_rigid_rbs = set()
1791  name = ""
1792  print("set_super_rigid_body_from_hierarchies> setting up a new SUPER rigid body")
1793 
1794  for hier in hiers:
1795  ps = IMP.atom.get_leaves(hier)
1796  for p in ps:
1798  rb = IMP.core.RigidMember(p).get_rigid_body()
1799  super_rigid_rbs.add(rb)
1800  else:
1801  super_rigid_xyzs.add(p)
1802  print("set_rigid_body_from_hierarchies> adding %s to the rigid body" % hier.get_name())
1803  if len(super_rigid_rbs) < min_size:
1804  return
1805  if axis is None:
1806  self.super_rigid_bodies.append((super_rigid_xyzs, super_rigid_rbs))
1807  else:
1808  # these will be 2D rotation SRB
1809  self.super_rigid_bodies.append(
1810  (super_rigid_xyzs, super_rigid_rbs, axis))
1811 
1812  def fix_rigid_bodies(self, rigid_bodies):
1813  self.fixed_rigid_bodies += rigid_bodies
1814 
1815 
1817  self, hiers, min_length=None, max_length=None, axis=None):
1818  '''
1819  Make a chain of super rigid bodies from a list of hierarchies.
1820 
1821  Takes a linear list of hierarchies (they are supposed to be
1822  sequence-contiguous) and produces a chain of super rigid bodies
1823  with given length range, specified by min_length and max_length.
1824  '''
1825  try:
1826  hiers = IMP.pmi.tools.flatten_list(hiers)
1827  except:
1828  pass
1829  for hs in IMP.pmi.tools.sublist_iterator(hiers, min_length, max_length):
1830  self.set_super_rigid_body_from_hierarchies(hs, axis, min_length)
1831 
1832  def set_super_rigid_bodies(self, subunits, coords=None):
1833  super_rigid_xyzs = set()
1834  super_rigid_rbs = set()
1835 
1836  for s in subunits:
1837  if type(s) == type(tuple()) and len(s) == 3:
1838  sel = IMP.atom.Selection(
1839  self.prot,
1840  molecule=s[2],
1841  residue_indexes=list(range(s[0],
1842  s[1] + 1)))
1843  if len(sel.get_selected_particles()) == 0:
1844  print("set_rigid_bodies: selected particle does not exist")
1845  for p in sel.get_selected_particles():
1847  rb = IMP.core.RigidMember(p).get_rigid_body()
1848  super_rigid_rbs.add(rb)
1849  else:
1850  super_rigid_xyzs.add(p)
1851  elif type(s) == type(str()):
1852  sel = IMP.atom.Selection(self.prot, molecule=s)
1853  if len(sel.get_selected_particles()) == 0:
1854  print("set_rigid_bodies: selected particle does not exist")
1855  for p in sel.get_selected_particles():
1856  # if not p in self.floppy_bodies:
1858  rb = IMP.core.RigidMember(p).get_rigid_body()
1859  super_rigid_rbs.add(rb)
1860  else:
1861  super_rigid_xyzs.add(p)
1862  self.super_rigid_bodies.append((super_rigid_xyzs, super_rigid_rbs))
1863 
1864  def remove_floppy_bodies_from_component(self, component_name):
1865  '''
1866  Remove leaves of hierarchies from the floppy bodies list based
1867  on the component name
1868  '''
1869  hs=IMP.atom.get_leaves(self.hier_dict[component_name])
1870  ps=[h.get_particle() for h in hs]
1871  for p in self.floppy_bodies:
1872  try:
1873  if p in ps: self.floppy_bodies.remove(p)
1874  if p in hs: self.floppy_bodies.remove(p)
1875  except:
1876  continue
1877 
1878 
1879  def remove_floppy_bodies(self, hierarchies):
1880  '''
1881  Remove leaves of hierarchies from the floppy bodies list.
1882 
1883  Given a list of hierarchies, get the leaves and remove the
1884  corresponding particles from the floppy bodies list. We need this
1885  function because sometimes
1886  we want to constrain the floppy bodies in a rigid body - for instance
1887  when you want to associate a bead with a density particle.
1888  '''
1889  for h in hierarchies:
1890  ps = IMP.atom.get_leaves(h)
1891  for p in ps:
1892  if p in self.floppy_bodies:
1893  print("remove_floppy_bodies: removing %s from floppy body list" % p.get_name())
1894  self.floppy_bodies.remove(p)
1895 
1896 
1897  def set_floppy_bodies(self):
1898  for p in self.floppy_bodies:
1899  name = p.get_name()
1900  p.set_name(name + "_floppy_body")
1902  print("I'm trying to make this particle flexible although it was assigned to a rigid body", p.get_name())
1903  rb = IMP.core.RigidMember(p).get_rigid_body()
1904  try:
1905  rb.set_is_rigid_member(p.get_index(), False)
1906  except:
1907  # some IMP versions still work with that
1908  rb.set_is_rigid_member(p.get_particle_index(), False)
1909  p.set_name(p.get_name() + "_rigid_body_member")
1910 
1911  def set_floppy_bodies_from_hierarchies(self, hiers):
1912  for hier in hiers:
1913  ps = IMP.atom.get_leaves(hier)
1914  for p in ps:
1915  IMP.core.XYZ(p).set_coordinates_are_optimized(True)
1916  self.floppy_bodies.append(p)
1917 
1919  self,
1920  selection_tuples,
1921  resolution=None):
1922  '''
1923  selection tuples must be [(r1,r2,"name1"),(r1,r2,"name2"),....]
1924  @return the particles
1925  '''
1926  particles = []
1927  print(selection_tuples)
1928  for s in selection_tuples:
1929  ps = IMP.pmi.tools.select_by_tuple(
1930  representation=self, tupleselection=tuple(s),
1931  resolution=None, name_is_ambiguous=False)
1932  particles += ps
1933  return particles
1934 
1935  def get_connected_intra_pairs(self):
1936  return self.connected_intra_pairs
1937 
1938  def set_rigid_bodies_max_trans(self, maxtrans):
1939  self.maxtrans_rb = maxtrans
1940 
1941  def set_rigid_bodies_max_rot(self, maxrot):
1942  self.maxrot_rb = maxrot
1943 
1944  def set_super_rigid_bodies_max_trans(self, maxtrans):
1945  self.maxtrans_srb = maxtrans
1946 
1947  def set_super_rigid_bodies_max_rot(self, maxrot):
1948  self.maxrot_srb = maxrot
1949 
1950  def set_floppy_bodies_max_trans(self, maxtrans):
1951  self.maxtrans_fb = maxtrans
1952 
1953  def set_rigid_bodies_as_fixed(self, rigidbodiesarefixed=True):
1954  '''
1955  Fix rigid bodies in their actual position.
1956  The get_particles_to_sample() function will return
1957  just the floppy bodies (if they are not fixed).
1958  '''
1959  self.rigidbodiesarefixed = rigidbodiesarefixed
1960 
1961  def set_floppy_bodies_as_fixed(self, floppybodiesarefixed=True):
1962  '''
1963  Fix floppy bodies in their actual position.
1964  The get_particles_to_sample() function will return
1965  just the rigid bodies (if they are not fixed).
1966  '''
1967  self.floppybodiesarefixed=floppybodiesarefixed
1968 
1969  def draw_hierarchy_graph(self):
1970  for c in IMP.atom.Hierarchy(self.prot).get_children():
1971  print("Drawing hierarchy graph for " + c.get_name())
1972  IMP.pmi.output.get_graph_from_hierarchy(c)
1973 
1974  def get_geometries(self):
1975  # create segments at the lowest resolution
1976  seggeos = []
1977  for name in self.hier_geometry_pairs:
1978  for pt in self.hier_geometry_pairs[name]:
1979  p1 = pt[0]
1980  p2 = pt[1]
1981  color = pt[2]
1982  try:
1983  clr = IMP.display.get_rgb_color(color)
1984  except:
1985  clr = IMP.display.get_rgb_color(1.0)
1986  coor1 = IMP.core.XYZ(p1).get_coordinates()
1987  coor2 = IMP.core.XYZ(p2).get_coordinates()
1988  seg = IMP.algebra.Segment3D(coor1, coor2)
1989  seggeos.append(IMP.display.SegmentGeometry(seg, clr))
1990  return seggeos
1991 
1992  def setup_bonds(self):
1993  # create segments at the lowest resolution
1994  seggeos = []
1995  for name in self.hier_geometry_pairs:
1996  for pt in self.hier_geometry_pairs[name]:
1997 
1998  p1 = pt[0]
1999  p2 = pt[1]
2000  if not IMP.atom.Bonded.get_is_setup(p1):
2002  if not IMP.atom.Bonded.get_is_setup(p2):
2004 
2007  IMP.atom.Bonded(p1),
2008  IMP.atom.Bonded(p2),
2009  1)
2010 
2011  def show_component_table(self, name):
2012  if name in self.sequence_dict:
2013  lastresn = len(self.sequence_dict[name])
2014  firstresn = 1
2015  else:
2016  residues = self.hier_db.get_residue_numbers(name)
2017  firstresn = min(residues)
2018  lastresn = max(residues)
2019 
2020  for nres in range(firstresn, lastresn + 1):
2021  try:
2022  resolutions = self.hier_db.get_residue_resolutions(name, nres)
2023  ps = []
2024  for r in resolutions:
2025  ps += self.hier_db.get_particles(name, nres, r)
2026  print("%20s %7s" % (name, nres), " ".join(["%20s %7s" % (str(p.get_name()),
2027  str(IMP.pmi.Resolution(p).get_resolution())) for p in ps]))
2028  except:
2029  print("%20s %20s" % (name, nres), "**** not represented ****")
2030 
2031  def draw_hierarchy_composition(self):
2032 
2033  ks = list(self.elements.keys())
2034  ks.sort()
2035 
2036  max = 0
2037  for k in self.elements:
2038  for l in self.elements[k]:
2039  if l[1] > max:
2040  max = l[1]
2041 
2042  for k in ks:
2043  self.draw_component_composition(k, max)
2044 
2045  def draw_component_composition(self, name, max=1000, draw_pdb_names=False):
2046  from matplotlib import pyplot
2047  import matplotlib as mpl
2048  k = name
2049  tmplist = sorted(self.elements[k], key=itemgetter(0))
2050  try:
2051  endres = tmplist[-1][1]
2052  except:
2053  print("draw_component_composition: missing information for component %s" % name)
2054  return
2055  fig = pyplot.figure(figsize=(26.0 * float(endres) / max + 2, 2))
2056  ax = fig.add_axes([0.05, 0.475, 0.9, 0.15])
2057 
2058  # Set the colormap and norm to correspond to the data for which
2059  # the colorbar will be used.
2060  cmap = mpl.cm.cool
2061  norm = mpl.colors.Normalize(vmin=5, vmax=10)
2062  bounds = [1]
2063  colors = []
2064 
2065  for n, l in enumerate(tmplist):
2066  firstres = l[0]
2067  lastres = l[1]
2068  if l[3] != "end":
2069  if bounds[-1] != l[0]:
2070  colors.append("white")
2071  bounds.append(l[0])
2072  if l[3] == "pdb":
2073  colors.append("#99CCFF")
2074  if l[3] == "bead":
2075  colors.append("#FFFF99")
2076  if l[3] == "helix":
2077  colors.append("#33CCCC")
2078  if l[3] != "end":
2079  bounds.append(l[1] + 1)
2080  else:
2081  if l[3] == "pdb":
2082  colors.append("#99CCFF")
2083  if l[3] == "bead":
2084  colors.append("#FFFF99")
2085  if l[3] == "helix":
2086  colors.append("#33CCCC")
2087  if l[3] != "end":
2088  bounds.append(l[1] + 1)
2089  else:
2090  if bounds[-1] - 1 == l[0]:
2091  bounds.pop()
2092  bounds.append(l[0])
2093  else:
2094  colors.append("white")
2095  bounds.append(l[0])
2096 
2097  bounds.append(bounds[-1])
2098  colors.append("white")
2099  cmap = mpl.colors.ListedColormap(colors)
2100  cmap.set_over('0.25')
2101  cmap.set_under('0.75')
2102 
2103  norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
2104  cb2 = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
2105  norm=norm,
2106  # to use 'extend', you must
2107  # specify two extra boundaries:
2108  boundaries=bounds,
2109  ticks=bounds, # optional
2110  spacing='proportional',
2111  orientation='horizontal')
2112 
2113  extra_artists = []
2114  npdb = 0
2115 
2116  if draw_pdb_names:
2117  for l in tmplist:
2118  if l[3] == "pdb":
2119  npdb += 1
2120  mid = 1.0 / endres * float(l[0])
2121  # t =ax.text(mid, float(npdb-1)/2.0+1.5, l[2], ha="left", va="center", rotation=0,
2122  # size=10)
2123  # t=ax.annotate(l[0],2)
2124  t = ax.annotate(
2125  l[2], xy=(mid, 1), xycoords='axes fraction',
2126  xytext=(mid + 0.025, float(npdb - 1) / 2.0 + 1.5), textcoords='axes fraction',
2127  arrowprops=dict(arrowstyle="->",
2128  connectionstyle="angle,angleA=0,angleB=90,rad=10"),
2129  )
2130  extra_artists.append(t)
2131 
2132  # set the title of the bar
2133  title = ax.text(-0.005, 0.5, k, ha="right", va="center", rotation=90,
2134  size=20)
2135 
2136  extra_artists.append(title)
2137  # changing the xticks labels
2138  labels = len(bounds) * [" "]
2139  ax.set_xticklabels(labels)
2140  mid = 1.0 / endres * float(bounds[0])
2141  t = ax.annotate(bounds[0], xy=(mid, 0), xycoords='axes fraction',
2142  xytext=(mid - 0.01, -0.5), textcoords='axes fraction',)
2143  extra_artists.append(t)
2144  offsets = [0, -0.5, -1.0]
2145  nclashes = 0
2146  for n in range(1, len(bounds)):
2147  if bounds[n] == bounds[n - 1]:
2148  continue
2149  mid = 1.0 / endres * float(bounds[n])
2150  if (float(bounds[n]) - float(bounds[n - 1])) / max <= 0.01:
2151  nclashes += 1
2152  offset = offsets[nclashes % 3]
2153  else:
2154  nclashes = 0
2155  offset = offsets[0]
2156  if offset > -0.75:
2157  t = ax.annotate(
2158  bounds[n], xy=(mid, 0), xycoords='axes fraction',
2159  xytext=(mid, -0.5 + offset), textcoords='axes fraction')
2160  else:
2161  t = ax.annotate(
2162  bounds[n], xy=(mid, 0), xycoords='axes fraction',
2163  xytext=(mid, -0.5 + offset), textcoords='axes fraction', arrowprops=dict(arrowstyle="-"))
2164  extra_artists.append(t)
2165 
2166  cb2.add_lines(bounds, ["black"] * len(bounds), [1] * len(bounds))
2167  # cb2.set_label(k)
2168 
2169  pyplot.savefig(
2170  k + "structure.pdf",
2171  dpi=150,
2172  transparent="True",
2173  bbox_extra_artists=(extra_artists),
2174  bbox_inches='tight')
2175  pyplot.show()
2176 
2177  def draw_coordinates_projection(self):
2178  import matplotlib.pyplot as pp
2179  xpairs = []
2180  ypairs = []
2181  for name in self.hier_geometry_pairs:
2182  for pt in self.hier_geometry_pairs[name]:
2183  p1 = pt[0]
2184  p2 = pt[1]
2185  color = pt[2]
2186  coor1 = IMP.core.XYZ(p1).get_coordinates()
2187  coor2 = IMP.core.XYZ(p2).get_coordinates()
2188  x1 = coor1[0]
2189  x2 = coor2[0]
2190  y1 = coor1[1]
2191  y2 = coor2[1]
2192  xpairs.append([x1, x2])
2193  ypairs.append([y1, y2])
2194  xlist = []
2195  ylist = []
2196  for xends, yends in zip(xpairs, ypairs):
2197  xlist.extend(xends)
2198  xlist.append(None)
2199  ylist.extend(yends)
2200  ylist.append(None)
2201  pp.plot(xlist, ylist, 'b-', alpha=0.1)
2202  pp.show()
2203 
2204  def get_prot_name_from_particle(self, particle):
2205  names = self.get_component_names()
2206  particle0 = particle
2207  name = None
2208  while not name in names:
2209  h = IMP.atom.Hierarchy(particle0).get_parent()
2210  name = h.get_name()
2211  particle0 = h.get_particle()
2212  return name
2213 
2214 
2215  def get_particles_to_sample(self):
2216  # get the list of samplable particles with their type
2217  # and the mover displacement. Everything wrapped in a dictionary,
2218  # to be used by samplers modules
2219  ps = {}
2220 
2221  # remove symmetric particles: they are not sampled
2222  rbtmp = []
2223  fbtmp = []
2224  srbtmp = []
2225  if not self.rigidbodiesarefixed:
2226  for rb in self.rigid_bodies:
2228  if IMP.pmi.Symmetric(rb).get_symmetric() != 1:
2229  rbtmp.append(rb)
2230  else:
2231  if rb not in self.fixed_rigid_bodies:
2232  rbtmp.append(rb)
2233 
2234  if not self.floppybodiesarefixed:
2235  for fb in self.floppy_bodies:
2237  if IMP.pmi.Symmetric(fb).get_symmetric() != 1:
2238  fbtmp.append(fb)
2239  else:
2240  fbtmp.append(fb)
2241 
2242  for srb in self.super_rigid_bodies:
2243  # going to prune the fixed rigid bodies out
2244  # of the super rigid body list
2245  rigid_bodies = list(srb[1])
2246  filtered_rigid_bodies = []
2247  for rb in rigid_bodies:
2248  if rb not in self.fixed_rigid_bodies:
2249  filtered_rigid_bodies.append(rb)
2250  srbtmp.append((srb[0], filtered_rigid_bodies))
2251 
2252  self.rigid_bodies = rbtmp
2253  self.floppy_bodies = fbtmp
2254  self.super_rigid_bodies = srbtmp
2255 
2256  ps["Rigid_Bodies_SimplifiedModel"] = (
2257  self.rigid_bodies,
2258  self.maxtrans_rb,
2259  self.maxrot_rb)
2260  ps["Floppy_Bodies_SimplifiedModel"] = (
2261  self.floppy_bodies,
2262  self.maxtrans_fb)
2263  ps["SR_Bodies_SimplifiedModel"] = (
2264  self.super_rigid_bodies,
2265  self.maxtrans_srb,
2266  self.maxrot_srb)
2267  return ps
2268 
2269  def set_output_level(self, level):
2270  self.output_level = level
2271 
2272  def _evaluate(self, deriv):
2273  """Evaluate the total score of all added restraints"""
2275  return r.evaluate(deriv)
2276 
2277  def get_output(self):
2278  output = {}
2279  score = 0.0
2280 
2281  output["SimplifiedModel_Total_Score_" +
2282  self.label] = str(self._evaluate(False))
2283  output["SimplifiedModel_Linker_Score_" +
2284  self.label] = str(self.linker_restraints.unprotected_evaluate(None))
2285  for name in self.sortedsegments_cr_dict:
2286  partialscore = self.sortedsegments_cr_dict[name].evaluate(False)
2287  score += partialscore
2288  output[
2289  "SimplifiedModel_Link_SortedSegments_" +
2290  name +
2291  "_" +
2292  self.label] = str(
2293  partialscore)
2294  partialscore = self.unmodeledregions_cr_dict[name].evaluate(False)
2295  score += partialscore
2296  output[
2297  "SimplifiedModel_Link_UnmodeledRegions_" +
2298  name +
2299  "_" +
2300  self.label] = str(
2301  partialscore)
2302  for rb in self.rigid_body_symmetries:
2303  name=rb.get_name()
2304  output[name +"_" +self.label]=str(rb.get_reference_frame().get_transformation_to())
2305  for name in self.linker_restraints_dict:
2306  output[
2307  name +
2308  "_" +
2309  self.label] = str(
2310  self.linker_restraints_dict[
2311  name].unprotected_evaluate(
2312  None))
2313 
2314  if len(self.reference_structures.keys()) != 0:
2315  rmsds = self.get_all_rmsds()
2316  for label in rmsds:
2317  output[
2318  "SimplifiedModel_" +
2319  label +
2320  "_" +
2321  self.label] = rmsds[
2322  label]
2323 
2324  if self.output_level == "high":
2325  for p in IMP.atom.get_leaves(self.prot):
2326  d = IMP.core.XYZR(p)
2327  output["Coordinates_" +
2328  p.get_name() + "_" + self.label] = str(d)
2329 
2330  output["_TotalScore"] = str(score)
2331  return output
2332 
2333  def get_test_output(self):
2334  # this method is called by test functions and return an enriched output
2335  output = self.get_output()
2336  for n, p in enumerate(self.get_particles_to_sample()):
2337  output["Particle_to_sample_" + str(n)] = str(p)
2338  output["Number_of_particles"] = len(IMP.atom.get_leaves(self.prot))
2339  output["Hierarchy_Dictionary"] = list(self.hier_dict.keys())
2340  output["Number_of_floppy_bodies"] = len(self.floppy_bodies)
2341  output["Number_of_rigid_bodies"] = len(self.rigid_bodies)
2342  output["Number_of_super_bodies"] = len(self.super_rigid_bodies)
2343  output["Selection_resolution_1"] = len(
2344  IMP.pmi.tools.select(self, resolution=1))
2345  output["Selection_resolution_5"] = len(
2346  IMP.pmi.tools.select(self, resolution=5))
2347  output["Selection_resolution_7"] = len(
2348  IMP.pmi.tools.select(self, resolution=5))
2349  output["Selection_resolution_10"] = len(
2350  IMP.pmi.tools.select(self, resolution=10))
2351  output["Selection_resolution_100"] = len(
2352  IMP.pmi.tools.select(self, resolution=100))
2353  output["Selection_All"] = len(IMP.pmi.tools.select(self))
2354  output["Selection_resolution=1"] = len(
2355  IMP.pmi.tools.select(self, resolution=1))
2356  output["Selection_resolution=1,resid=10"] = len(
2357  IMP.pmi.tools.select(self, resolution=1, residue=10))
2358  for resolution in self.hier_resolution:
2359  output["Hier_resolution_dictionary" +
2360  str(resolution)] = len(self.hier_resolution[resolution])
2361  for name in self.hier_dict:
2362  output[
2363  "Selection_resolution=1,resid=10,name=" +
2364  name] = len(
2366  self,
2367  resolution=1,
2368  name=name,
2369  residue=10))
2370  output[
2371  "Selection_resolution=1,resid=10,name=" +
2372  name +
2373  ",ambiguous"] = len(
2375  self,
2376  resolution=1,
2377  name=name,
2378  name_is_ambiguous=True,
2379  residue=10))
2380  output[
2381  "Selection_resolution=1,resid=10,name=" +
2382  name +
2383  ",ambiguous"] = len(
2385  self,
2386  resolution=1,
2387  name=name,
2388  name_is_ambiguous=True,
2389  residue=10))
2390  output[
2391  "Selection_resolution=1,resrange=(10,20),name=" +
2392  name] = len(
2394  self,
2395  resolution=1,
2396  name=name,
2397  first_residue=10,
2398  last_residue=20))
2399  output[
2400  "Selection_resolution=1,resrange=(10,20),name=" +
2401  name +
2402  ",ambiguous"] = len(
2404  self,
2405  resolution=1,
2406  name=name,
2407  name_is_ambiguous=True,
2408  first_residue=10,
2409  last_residue=20))
2410  output[
2411  "Selection_resolution=10,resrange=(10,20),name=" +
2412  name] = len(
2414  self,
2415  resolution=10,
2416  name=name,
2417  first_residue=10,
2418  last_residue=20))
2419  output[
2420  "Selection_resolution=10,resrange=(10,20),name=" +
2421  name +
2422  ",ambiguous"] = len(
2424  self,
2425  resolution=10,
2426  name=name,
2427  name_is_ambiguous=True,
2428  first_residue=10,
2429  last_residue=20))
2430  output[
2431  "Selection_resolution=100,resrange=(10,20),name=" +
2432  name] = len(
2434  self,
2435  resolution=100,
2436  name=name,
2437  first_residue=10,
2438  last_residue=20))
2439  output[
2440  "Selection_resolution=100,resrange=(10,20),name=" +
2441  name +
2442  ",ambiguous"] = len(
2444  self,
2445  resolution=100,
2446  name=name,
2447  name_is_ambiguous=True,
2448  first_residue=10,
2449  last_residue=20))
2450 
2451  return output
2452 
2453 
2454 # Deprecation warning for the old SimplifiedModel class
2455 
2456 @IMP.deprecated_object("2.5", "Use Representation instead.")
2457 class SimplifiedModel(Representation):
2458 
2459  def __init__(self, *args, **kwargs):
2460  Representation.__init__(self, *args, **kwargs)
def link_components_to_rmf
Load coordinates in the current representation.
Select non water and non hydrogen atoms.
Definition: pdb.h:243
def list_chunks_iterator
Yield successive length-sized chunks from a list.
Definition: tools.py:1115
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.
A decorator to associate a particle with a part of a protein/DNA/RNA.
Definition: Fragment.h:20
static Gaussian setup_particle(Model *m, ParticleIndex pi)
Definition: Gaussian.h:48
void show_molecular_hierarchy(Hierarchy h)
Print out the molecular hierarchy.
double get_drms(const Vector3DsOrXYZs0 &m1, const Vector3DsOrXYZs1 &m2)
def get_restraint_set
Get a RestraintSet containing all PMI restraints added to the model.
Definition: tools.py:49
Apply a SingletonFunction to a SingletonContainer to maintain an invariant.
atom::Hierarchies create_hierarchies(RMF::FileConstHandle fh, Model *m)
Set the coordinates of a particle to be a transformed version of a reference.
Definition: core/symmetry.h:76
Store the representations for a system.
Definition: tools.py:832
def shuffle_configuration
Shuffle configuration; used to restart the optimization.
A member of a rigid body, it has internal (local) coordinates.
Definition: rigid_bodies.h:358
static bool get_is_setup(const IMP::ParticleAdaptor &p)
Definition: rigid_bodies.h:359
Set of python classes to create a multi-state, multi-resolution IMP hierarchy.
static Atom setup_particle(Model *m, ParticleIndex pi, Atom other)
Definition: atom/Atom.h:242
static Fragment setup_particle(Model *m, ParticleIndex pi)
Definition: Fragment.h:63
Upper bound harmonic function (non-zero when feature > mean)
static Symmetric setup_particle(Model *m, ParticleIndex pi, Float symmetric)
Definition: Symmetric.h:44
def set_coordinates_from_rmf
Read and replace coordinates from an RMF file.
static XYZR setup_particle(Model *m, ParticleIndex pi)
Definition: XYZR.h:48
A decorator for a particle which has bonds.
Select atoms which are selected by both selectors.
Definition: pdb.h:326
Rotation3D get_random_rotation_3d(const Rotation3D &center, double distance)
Pick a rotation at random near the provided one.
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
def set_rigid_bodies_as_fixed
Fix rigid bodies in their actual position.
def get_particles_from_selection_tuples
selection tuples must be [(r1,r2,"name1"),(r1,r2,"name2"),....
Add symmetric attribute to a particle.
Definition: Symmetric.h:23
double get_ball_radius_from_volume_3d(double volume)
Return the radius of a sphere with a given volume.
Definition: Sphere3D.h:35
def setup_component_sequence_connectivity
Generate restraints between contiguous fragments in the hierarchy.
Add uncertainty to a particle.
Definition: Uncertainty.h:24
A score on the distance between the surfaces of two spheres.
static Residue setup_particle(Model *m, ParticleIndex pi, ResidueType t, int index, int insertion_code)
Definition: Residue.h:157
static bool get_is_setup(const IMP::ParticleAdaptor &p)
Definition: rigid_bodies.h:469
static bool get_is_setup(const IMP::ParticleAdaptor &p)
Definition: XYZ.h:49
def get_prot_name_from_particle
Return the component name provided a particle and a list of names.
Definition: tools.py:980
static XYZ setup_particle(Model *m, ParticleIndex pi)
Definition: XYZ.h:51
void read_pdb(TextInput input, int model, Hierarchy h)
def get_residue_gaps_in_hierarchy
Return the residue index gaps and contiguous segments in the hierarchy.
Definition: tools.py:625
def remove_floppy_bodies
Remove leaves of hierarchies from the floppy bodies list.
Vector3D get_random_vector_in(const Cylinder3D &c)
Generate a random vector in a cylinder with uniform density.
static Uncertainty setup_particle(Model *m, ParticleIndex pi, Float uncertainty)
Definition: Uncertainty.h:45
def remove_floppy_bodies_from_component
Remove leaves of hierarchies from the floppy bodies list based on the component name.
A reference frame in 3D.
Add resolution to a particle.
Definition: Resolution.h:24
Bond create_bond(Bonded a, Bonded b, Bond o)
Connect the two wrapped particles by a custom bond.
Object used to hold a set of restraints.
Definition: RestraintSet.h:36
static Molecule setup_particle(Model *m, ParticleIndex pi)
Definition: Molecule.h:37
Rotation3D get_rotation_about_axis(const Vector3D &axis, double angle)
Generate a Rotation3D object from a rotation around an axis.
Select all CB ATOM records.
Definition: pdb.h:91
A Gaussian distribution in 3D.
Definition: Gaussian3D.h:24
static bool get_is_setup(Model *m, ParticleIndex pi)
Definition: Fragment.h:46
static Hierarchy setup_particle(Model *m, ParticleIndex pi, ParticleIndexesAdaptor children=ParticleIndexesAdaptor())
Create a Hierarchy of level t by adding the needed attributes.
ParticleIndexPairs get_indexes(const ParticlePairsTemp &ps)
def set_rigid_bodies
Construct a rigid body from a list of subunits.
double get_volume_from_mass(double m, ProteinDensityReference ref=ALBER)
Estimate the volume of a protein from its mass.
The standard decorator for manipulating molecular structures.
Ints get_index(const ParticlesTemp &particles, const Subset &subset, const Subsets &excluded)
Store a list of ParticleIndexes.
def deprecated_method
Python decorator to mark a method as deprecated.
Definition: __init__.py:9630
A decorator for a particle representing an atom.
Definition: atom/Atom.h:234
void transform(XYZ a, const algebra::Transformation3D &tr)
Apply a transformation to the particle.
static Mass setup_particle(Model *m, ParticleIndex pi, Float mass)
Definition: Mass.h:44
def add_restraint_to_model
Add a PMI restraint to the model.
Definition: tools.py:37
static Bonded setup_particle(Model *m, ParticleIndex pi)
The type for a residue.
static bool get_is_setup(Model *m, ParticleIndex pi)
Definition: Symmetric.h:29
double get_rmsd(const Vector3DsOrXYZs0 &m1, const Vector3DsOrXYZs1 &m2)
def add_all_atom_densities
Decorates all specified particles as Gaussians directly.
def coarse_hierarchy
Generate all needed coarse grained layers.
def add_component_pdb
Add a component that has an associated 3D structure in a PDB file.
Basic utilities for handling cryo-electron microscopy 3D density maps.
void load_frame(RMF::FileConstHandle file, RMF::FrameID frame)
A decorator for a particle with x,y,z coordinates.
Definition: XYZ.h:30
static bool get_is_setup(Model *m, ParticleIndex pi)
Definition: Resolution.h:30
A base class for Keys.
Definition: Key.h:46
static Colored setup_particle(Model *m, ParticleIndex pi, Color color)
Definition: Colored.h:62
def set_chain_of_super_rigid_bodies
Make a chain of super rigid bodies from a list of hierarchies.
def add_component_sequence
Add the primary sequence for a single component.
def write_gmm_to_map
write density map from GMM.
Definition: gmm_tools.py:80
Tools for clustering and cluster analysis.
Definition: pmi/Analysis.py:1
static Resolution setup_particle(Model *m, ParticleIndex pi, Float resolution)
Definition: Resolution.h:45
def create_components_from_rmf
still not working.
def get_closest_residue_position
this function works with plain hierarchies, as read from the pdb, no multi-scale hierarchies ...
Definition: tools.py:525
3D rotation class.
Definition: Rotation3D.h:46
Transformation3D get_identity_transformation_3d()
Return a transformation that does not do anything.
Find all nearby pairs by testing all pairs.
Classes for writing output files and processing them.
Definition: output.py:1
Simple implementation of segments in 3D.
Definition: Segment3D.h:24
static bool get_is_setup(const IMP::ParticleAdaptor &p)
Definition: rigid_bodies.h:147
def deprecated_object
Python decorator to mark a class as deprecated.
Definition: __init__.py:9614
A decorator for a residue.
Definition: Residue.h:134
Sampling of the system.
Definition: samplers.py:1
Basic functionality that is expected to be used by a wide variety of IMP users.
General purpose algebraic and geometric methods that are expected to be used by a wide variety of IMP...
static bool get_is_setup(const IMP::ParticleAdaptor &p)
def add_component_density
Sets up a Gaussian Mixture Model for this component.
Sample using Monte Carlo.
Definition: samplers.py:36
The general base class for IMP exceptions.
Definition: exception.h:49
Hierarchy create_simplified_along_backbone(Chain input, const IntRanges &residue_segments, bool keep_detailed=false)
VectorD< 3 > Vector3D
Definition: VectorD.h:395
IMP::core::RigidBody create_rigid_body(Hierarchy h)
static Reference setup_particle(Model *m, ParticleIndex pi, ParticleIndexAdaptor reference)
Definition: core/symmetry.h:32
Rotation3D get_identity_rotation_3d()
Return a rotation that does not do anything.
Definition: Rotation3D.h:236
void link_hierarchies(RMF::FileConstHandle fh, const atom::Hierarchies &hs)
Class to handle individual model particles.
Definition: Particle.h:37
Bond get_bond(Bonded a, Bonded b)
Get the bond between two particles.
std::string get_data_path(std::string file_name)
Return the full path to one of this module's data files.
Select atoms which are selected by either or both selectors.
Definition: pdb.h:349
def get_hierarchies_at_given_resolution
Get the hierarchies at the given resolution.
Store info for a chain of a protein.
Definition: Chain.h:21
Applies a PairScore to a Pair.
Definition: PairRestraint.h:29
def select
this function uses representation=SimplifiedModel it returns the corresponding selected particles rep...
Definition: tools.py:702
Select all CA ATOM records.
Definition: pdb.h:77
Python classes to represent, score, sample and analyze models.
static bool get_is_setup(Model *m, ParticleIndex pi)
Definition: Uncertainty.h:30
double get_resolution(Model *m, ParticleIndex pi)
Estimate the resolution of the hierarchy as used by Representation.
A decorator for a rigid body.
Definition: rigid_bodies.h:75
Set up the representation of all proteins and nucleic acid macromolecules.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
Definition: Gaussian.h:47
A dictionary-like wrapper for reading and storing sequence data.
def write_gmm_to_text
write a list of gaussians to text.
Definition: gmm_tools.py:62
Transformation3D get_transformation_aligning_first_to_second(Vector3Ds a, Vector3Ds b)
Output IMP model data in various file formats.
Functionality for loading, creating, manipulating and scoring atomic structures.
static Chain setup_particle(Model *m, ParticleIndex pi, std::string id)
Definition: Chain.h:41
Hierarchies get_leaves(const Selection &h)
def add_component_necklace
Generates a string of beads with given length.
An exception for an invalid value being passed to IMP.
Definition: exception.h:137
def set_floppy_bodies_as_fixed
Fix floppy bodies in their actual position.
Select hierarchy particles identified by the biological name.
Definition: Selection.h:66
static RigidBody setup_particle(Model *m, ParticleIndex pi, ParticleIndexesAdaptor ps)
Definition: rigid_bodies.h:158
Select all ATOM and HETATM records with the given chain ids.
Definition: pdb.h:189
Support for the RMF file format for storing hierarchical molecular data and markup.
def set_rigid_body_from_hierarchies
Construct a rigid body from hierarchies (and optionally particles).
def decorate_gmm_from_text
read the output from write_gmm_to_text, decorate as Gaussian and Mass
Definition: gmm_tools.py:22
def get_residue_indexes
Retrieve the residue indexes for the given particle.
Definition: tools.py:1000
static bool get_is_setup(const IMP::ParticleAdaptor &p)
Definition: rigid_bodies.h:490
Transformation3D get_random_local_transformation(Vector3D origin, double max_translation=5., double max_angle_in_rad=0.26)
Get a local transformation.
def check_root
If the root hierarchy does not exist, construct it.
def add_component_beads
add beads to the representation
Inferential scoring building on methods developed as part of the Inferential Structure Determination ...
def sublist_iterator
Yield all sublists of length >= lmin and <= lmax.
Definition: tools.py:1096
def add_component_hierarchy_clone
Make a copy of a hierarchy and append it to a component.
Harmonic function (symmetric about the mean)
Definition: core/Harmonic.h:24
A decorator for a particle with x,y,z coordinates and a radius.
Definition: XYZR.h:27