IMP logo
IMP Reference Guide  2.7.0
The Integrative Modeling Platform
basic.py
1 """@namespace IMP.pmi.restraints.basic
2 Some miscellaneous simple restraints.
3 """
4 
5 from __future__ import print_function
6 import IMP
7 import IMP.core
8 import IMP.algebra
9 import IMP.atom
10 import IMP.container
11 import IMP.pmi.tools
12 import IMP.pmi.restraints
13 
14 
16 
17  """Restraint to keep all structures inside sphere."""
18 
19  def __init__(self,
20  representation=None,
21  radius=10.0,
22  hierarchies=None,
23  resolution=10,
24  weight=1.0,
25  center=None,
26  label=None):
27  """Setup external barrier restraint.
28  @param representation DEPRECATED
29  @param radius Size of external barrier
30  @param hierarchies Can be one of the following inputs: IMP Hierarchy,
31  PMI System/State/Molecule/TempResidue, or a list/set of them
32  @param resolution Select which resolutions to act upon
33  @param weight Weight of restraint
34  @param center Center of the external barrier restraint
35  (IMP.algebra.Vector3D object)
36  @param label A unique label to be used in outputs and
37  particle/restraint names.
38  """
39  if representation:
40  m = representation.prot.get_model()
41  particles = IMP.pmi.tools.select(
42  representation,
43  resolution=resolution,
44  hierarchies=hierarchies)
45  elif hierarchies:
46  hiers = IMP.pmi.tools.input_adaptor(hierarchies, resolution,
47  flatten=True)
48  m = hiers[0].get_model()
49  particles = [h.get_particle() for h in hiers]
50  else:
51  raise Exception("%s: must pass representation or hierarchies" % (
52  self.name))
53 
54  super(ExternalBarrier, self).__init__(m, label=label, weight=weight)
55  self.radius = radius
56 
57  if center is None:
58  c3 = IMP.algebra.Vector3D(0, 0, 0)
59  elif type(center) is IMP.algebra.Vector3D:
60  c3 = center
61  else:
62  raise Exception(
63  "%s: @param center must be an IMP.algebra.Vector3D object" % (
64  self.name))
65 
66  ub3 = IMP.core.HarmonicUpperBound(radius, 10.0)
69 
70  lsc.add(particles)
72  self.rs.add_restraint(r3)
73 
74 
76 
77  """A simple distance restraint"""
78 
79  def __init__(self,
80  representation=None,
81  tuple_selection1=None,
82  tuple_selection2=None,
83  distancemin=0,
84  distancemax=100,
85  resolution=1.0,
86  kappa=1.0,
87  root_hier=None,
88  label=None,
89  weight=1.):
90  """Setup distance restraint.
91  @param representation DEPRECATED
92  @param tuple_selection1 (resnum, resnum, molecule name, copy
93  number (=0))
94  @param tuple_selection2 (resnum, resnum, molecule name, copy
95  number (=0))
96  @param distancemin The minimum dist
97  @param distancemax The maximum dist
98  @param resolution For selecting particles
99  @param kappa The harmonic parameter
100  @param root_hier The hierarchy to select from (use this instead of
101  representation)
102  @param label A unique label to be used in outputs and
103  particle/restraint names
104  @param weight Weight of restraint
105  \note Pass the same resnum twice to each tuple_selection. Optionally
106  add a copy number (PMI2 only)
107  """
108  if tuple_selection1 is None or tuple_selection2 is None:
109  raise Exception("You must pass tuple_selection1/2")
110  ts1 = IMP.core.HarmonicUpperBound(distancemax, kappa)
111  ts2 = IMP.core.HarmonicLowerBound(distancemin, kappa)
112 
113  if representation and not root_hier:
114  m = representation.prot.get_model()
115  particles1 = IMP.pmi.tools.select(representation,
116  resolution=resolution,
117  name=tuple_selection1[2],
118  residue=tuple_selection1[0])
119  particles2 = IMP.pmi.tools.select(representation,
120  resolution=resolution,
121  name=tuple_selection2[2],
122  residue=tuple_selection2[0])
123  elif root_hier and not representation:
124  m = root_hier.get_model()
125  copy_num1 = 0
126  if len(tuple_selection1) > 3:
127  copy_num1 = tuple_selection1[3]
128  copy_num2 = 0
129  if len(tuple_selection2) > 3:
130  copy_num2 = tuple_selection2[3]
131 
132  sel1 = IMP.atom.Selection(root_hier,
133  resolution=resolution,
134  molecule=tuple_selection1[2],
135  residue_index=tuple_selection1[0],
136  copy_index=copy_num1)
137  particles1 = sel1.get_selected_particles()
138  sel2 = IMP.atom.Selection(root_hier,
139  resolution=resolution,
140  molecule=tuple_selection2[2],
141  residue_index=tuple_selection2[0],
142  copy_index=copy_num2)
143  particles2 = sel2.get_selected_particles()
144  else:
145  raise Exception("Pass representation or root_hier, not both")
146 
147  super(DistanceRestraint, self).__init__(m, label=label, weight=weight)
148  print(self.name)
149 
150  print("Created distance restraint between "
151  "%s and %s" % (particles1[0].get_name(),
152  particles2[0].get_name()))
153 
154  if len(particles1) > 1 or len(particles2) > 1:
155  raise ValueError("more than one particle selected")
156 
157  self.rs.add_restraint(
158  IMP.core.DistanceRestraint(self.m, ts1,
159  particles1[0],
160  particles2[0]))
161  self.rs.add_restraint(
162  IMP.core.DistanceRestraint(self.m, ts2,
163  particles1[0],
164  particles2[0]))
165 
166 
167 class TorqueRestraint(IMP.Restraint):
168  import math
169  def __init__(self, m, objects, resolution, angular_tolerance,label='None'):
170  IMP.Restraint.__init__(self, m, "TorqueRestraint %1%")
171  self.softness_angle = 0.5
172  self.plateau = 1e-10
173  self.weight = 1.0
174  self.m=m
175  hierarchies = IMP.pmi.tools.input_adaptor(objects,
176  resolution,
177  flatten=True)
178  self.particles = [h.get_particle() for h in hierarchies]
179  self.ds=[IMP.core.XYZ(p) for p in self.particles]
180  self.label=label
181  self.at=angular_tolerance
182 
183  def get_angle_probability(self,xyz,angle_center):
184  maxtheta=angle_center+self.at
185  mintheta=angle_center-self.at
186  angle=self.math.atan2(xyz.get_y(),xyz.get_x() )*180.0/self.math.pi
187  anglediff = (angle - maxtheta + 180 + 360) % 360 - 180
188  argvalue1=anglediff / self.softness_angle
189  anglediff = (angle - mintheta + 180 + 360) % 360 - 180
190  argvalue2=-anglediff / self.softness_angle
191  prob = (1.0-self.plateau) / (1.0 + self.math.exp(-max(argvalue1,argvalue2)))
192  return prob
193 
194  def unprotected_evaluate(self, da):
195  s=0.0
196  center=IMP.core.get_centroid(self.ds)
197  angle_center=self.math.atan2(center[1],center[0])*180.0/self.math.pi
198  for xyz in self.ds:
199  s+=-self.math.log(1.0-self.get_angle_probability(xyz,angle_center))
200  return s
201 
202  def do_get_inputs(self):
203  return self.particles
204 
205  def add_to_model(self):
207 
208  def get_output(self):
209  self.m.update()
210  output = {}
211  score = self.weight * self.unprotected_evaluate(None)
212  output["_TotalScore"] = str(score)
213  output["TorqueRestraint_" + self.label] = str(score)
214  return output
215 
216 
217 
218 
220  '''
221  PMI2 python restraint. Restrains particles within a
222  Cylinder aligned along the z-axis and
223  centered in x,y=0,0
224  Optionally, one can restrain the cylindrical angle
225  '''
226  import math
227  def __init__(self, m, objects, resolution, radius,mintheta=None,
228  maxtheta=None,repulsive=False,label='None'):
229  '''
230  @param objects PMI2 objects
231  @param resolution the resolution you want the restraint to be applied
232  @param radius the radius of the cylinder
233  @param mintheta minimum cylindrical angle in degrees
234  @param maxtheta maximum cylindrical angle in degrees
235  '''
236  IMP.Restraint.__init__(self, m, "CylinderRestraint %1%")
237  self.radius=radius
238  self.softness = 3.0
239  self.softness_angle = 0.5
240  self.plateau = 1e-10
241  self.weight = 1.0
242  self.m=m
243  self.mintheta=mintheta
244  self.maxtheta=maxtheta
245  self.repulsive=repulsive
246  hierarchies = IMP.pmi.tools.input_adaptor(objects,
247  resolution,
248  flatten=True)
249  self.particles = [h.get_particle() for h in hierarchies]
250  self.label=label
251 
252  def get_probability(self,p):
253  xyz=IMP.core.XYZ(p)
254  r=self.math.sqrt(xyz.get_x()**2+xyz.get_y()**2)
255  argvalue=(r-self.radius) / self.softness
256  if self.repulsive: argvalue=-argvalue
257  prob = (1.0 - self.plateau) / (1.0 + self.math.exp(-argvalue))
258  return prob
259 
260  def get_angle_probability(self,p):
261  xyz=IMP.core.XYZ(p)
262  angle=self.math.atan2(xyz.get_y(),xyz.get_x() )*180.0/self.math.pi
263  anglediff = (angle - self.maxtheta + 180 + 360) % 360 - 180
264  argvalue1=anglediff / self.softness_angle
265  anglediff = (angle - self.mintheta + 180 + 360) % 360 - 180
266  argvalue2=-anglediff / self.softness_angle
267  prob = (1.0-self.plateau) / (1.0 + self.math.exp(-max(argvalue1,argvalue2)))
268  return prob
269 
270  def unprotected_evaluate(self, da):
271  s=0.0
272  for p in self.particles:
273  s+=-self.math.log(1.0-self.get_probability(p))
274  if self.mintheta is not None and self.maxtheta is not None:
275  s+=-self.math.log(1.0-self.get_angle_probability(p))
276  return s
277 
278  def do_get_inputs(self):
279  return self.particles
280 
281  def add_to_model(self):
283 
284  def get_output(self):
285  self.m.update()
286  output = {}
287  score = self.weight * self.unprotected_evaluate(None)
288  output["_TotalScore"] = str(score)
289  output["CylinderRestraint_" + self.label] = str(score)
290  return output
291 
292 
293 
295  '''
296  a python restraint with bistable potential
297  Authors: G. Bouvier, R. Pellarin. Pasteur Institute.
298  '''
299  import numpy as np
300  import math
301 
302  def __init__(self,m,p1,p2,dist1,dist2,sigma1,sigma2,weight1,weight2):
303  '''
304  input twp particles, the two equilibrium distances, their amplitudes, and their weights (populations)
305  '''
306  IMP.Restraint.__init__(self, m, "BiStableDistanceRestraint %1%")
307  self.dist1=dist1
308  self.dist2=dist2
309 
310  self.sigma1=sigma1
311  self.sigma2=sigma2
312 
313  self.weight1=weight1
314  self.weight2=weight2
315 
316  if self.weight1+self.weight2 != 1:
317  raise ValueError("The sum of the weights must be one")
318 
319  self.d1=IMP.core.XYZ(p1)
320  self.d2=IMP.core.XYZ(p2)
321  self.particle_list=[p1,p2]
322 
323  def gaussian(self,x, mu, sig, w):
324  return w*self.np.exp(-self.np.power(x - mu, 2.) / (2 * self.np.power(sig, 2.)))
325 
326  def unprotected_evaluate(self,da):
327  dist=IMP.core.get_distance(self.d1,self.d2)
328  prob=self.gaussian(dist,self.dist1,self.sigma1,self.weight1)+\
329  self.gaussian(dist,self.dist2,self.sigma2,self.weight2)
330  return -self.math.log(prob)
331 
332  def do_get_inputs(self):
333  return self.particle_list
334 
335 
337 
338  """Restraint for anchoring a particle to a specific coordinate."""
339 
340  def __init__(self,
341  representation=None,
342  tuple_selection=None,
343  anchor_point=IMP.algebra.Vector3D(0, 0, 0),
344  radius=10.0,
345  kappa=10.0,
346  resolution=1.0,
347  weight=1.0,
348  root_hier=None,
349  label=None):
350  """Setup distance restraint.
351  @param representation DEPRECATED
352  @param tuple_selection (resnum, resnum, molecule name,
353  copy number (=0))
354  @param anchor_point Point to which to restrain particle
355  (IMP.algebra.Vector3D object)
356  @param radius Size of the tolerance length
357  @param kappa The harmonic parameter
358  @param resolution For selecting a particle
359  @param weight Weight of restraint
360  @param root_hier The hierarchy to select from (use this instead of
361  representation)
362  @param label A unique label to be used in outputs and
363  particle/restraint names
364  \note Pass the same resnum twice to each tuple_selection. Optionally
365  add a copy number (PMI2 only)
366  """
367  if tuple_selection is None:
368  raise Exception("You must pass a tuple_selection")
369 
370  if representation and not root_hier:
371  m = representation.prot.get_model()
372  ps = IMP.pmi.tools.select(representation,
373  resolution=resolution,
374  name=tuple_selection[2],
375  residue=tuple_selection[0])
376  elif root_hier and not representation:
377  m = root_hier.get_model()
378  copy_num1 = 0
379  if len(tuple_selection) > 3:
380  copy_num1 = tuple_selection[3]
381 
382  sel1 = IMP.atom.Selection(root_hier,
383  resolution=resolution,
384  molecule=tuple_selection[2],
385  residue_index=tuple_selection[0],
386  copy_index=copy_num1)
387  ps = sel1.get_selected_particles()
388  else:
389  raise Exception("%s: Pass representation or root_hier, not both" %
390  self.name)
391  if len(ps) > 1:
392  raise ValueError("%s: more than one particle selected" %
393  self.name)
394 
395  super(DistanceToPointRestraint, self).__init__(m, label=label,
396  weight=weight)
397  self.radius = radius
398 
399  ub3 = IMP.core.HarmonicUpperBound(self.radius, kappa)
400  if anchor_point is None:
401  c3 = IMP.algebra.Vector3D(0, 0, 0)
402  elif type(anchor_point) is IMP.algebra.Vector3D:
403  c3 = anchor_point
404  else:
405  raise Exception(
406  "%s: @param anchor_point must be an algebra.Vector3D object" %
407  self.name)
408  ss3 = IMP.core.DistanceToSingletonScore(ub3, c3)
409 
411  lsc.add(ps)
412 
413  r3 = IMP.container.SingletonsRestraint(ss3, lsc)
414  self.rs.add_restraint(r3)
415 
416  print("\n%s: Created distance_to_point_restraint between "
417  "%s and %s" % (self.name, ps[0].get_name(), c3))
Applies a SingletonScore to each Singleton in a list.
def __init__
Setup distance restraint.
Definition: basic.py:95
A simple distance restraint.
Definition: basic.py:75
Lower bound harmonic function (non-zero when feature < mean)
def add_to_model
Add the restraint to the model.
Various classes to hold sets of particles.
Upper bound harmonic function (non-zero when feature > mean)
Miscellaneous utilities.
Definition: tools.py:1
algebra::Vector3D get_centroid(const XYZs &ps)
Get the centroid.
Distance restraint between two particles.
double get_distance(XYZR a, XYZR b)
Compute the sphere distance between a and b.
Definition: XYZR.h:89
Classes to handle different kinds of restraints.
def input_adaptor
Adapt things for PMI (degrees of freedom, restraints, ...) Returns list of list of hierarchies...
Definition: tools.py:1608
def __init__
input twp particles, the two equilibrium distances, their amplitudes, and their weights (populations)...
Definition: basic.py:302
def __init__
Setup external barrier restraint.
Definition: basic.py:27
Store a list of ParticleIndexes.
Restraint for anchoring a particle to a specific coordinate.
Definition: basic.py:336
def add_restraint_to_model
Add a PMI restraint to the model.
Definition: tools.py:37
Apply a function to the distance to a fixed point.
A decorator for a particle with x,y,z coordinates.
Definition: XYZ.h:30
Restraint to keep all structures inside sphere.
Definition: basic.py:15
def __init__
Setup distance restraint.
Definition: basic.py:355
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...
The general base class for IMP exceptions.
Definition: exception.h:49
VectorD< 3 > Vector3D
Definition: VectorD.h:395
def select
this function uses representation=SimplifiedModel it returns the corresponding selected particles rep...
Definition: tools.py:731
Functionality for loading, creating, manipulating and scoring atomic structures.
a python restraint with bistable potential Authors: G.
Definition: basic.py:294
Select hierarchy particles identified by the biological name.
Definition: Selection.h:66
def get_output
Get outputs to write to stat files.
virtual ModelObjectsTemp do_get_inputs() const =0
Base class for PMI restraints, which wrap IMP.Restraint(s).
A restraint is a term in an IMP ScoringFunction.
Definition: Restraint.h:52