IMP Reference Guide  develop.e6c37e56ed,2022/01/25 The Integrative Modeling Platform
/restraints/basic.py
1 """@namespace IMP.pmi1.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.pmi1.tools
13
14
16
17  """Restraint to keep all structures inside sphere."""
18
19  def __init__(self,
20  representation=None,
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  model = representation.prot.get_model()
41  particles = IMP.pmi1.tools.select(
42  representation,
43  resolution=resolution,
44  hierarchies=hierarchies)
45  elif hierarchies:
47  flatten=True)
48  model = 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__(model, label=label,
55  weight=weight)
57
58  if center is None:
59  c3 = IMP.algebra.Vector3D(0, 0, 0)
60  elif type(center) is IMP.algebra.Vector3D:
61  c3 = center
62  else:
63  raise Exception(
64  "%s: @param center must be an IMP.algebra.Vector3D object" % (
65  self.name))
66
69  lsc = IMP.container.ListSingletonContainer(self.model)
70
74
75
77
78  """A simple distance restraint"""
79
80  def __init__(self,
81  representation=None,
82  tuple_selection1=None,
83  tuple_selection2=None,
84  distancemin=0,
85  distancemax=100,
86  resolution=1.0,
87  kappa=1.0,
88  root_hier=None,
89  label=None,
90  weight=1.):
91  """Setup distance restraint.
92  @param representation DEPRECATED
93  @param tuple_selection1 (resnum, resnum, molecule name, copy
94  number (=0))
95  @param tuple_selection2 (resnum, resnum, molecule name, copy
96  number (=0))
97  @param distancemin The minimum dist
98  @param distancemax The maximum dist
99  @param resolution For selecting particles
100  @param kappa The harmonic parameter
101  @param root_hier The hierarchy to select from (use this instead of
102  representation)
103  @param label A unique label to be used in outputs and
104  particle/restraint names
105  @param weight Weight of restraint
106  \note Pass the same resnum twice to each tuple_selection. Optionally
107  add a copy number (PMI2 only)
108  """
109  if tuple_selection1 is None or tuple_selection2 is None:
110  raise Exception("You must pass tuple_selection1/2")
111  ts1 = IMP.core.HarmonicUpperBound(distancemax, kappa)
112  ts2 = IMP.core.HarmonicLowerBound(distancemin, kappa)
113
114  if representation and not root_hier:
115  model = representation.prot.get_model()
116  particles1 = IMP.pmi1.tools.select(representation,
117  resolution=resolution,
118  name=tuple_selection1[2],
119  residue=tuple_selection1[0])
120  particles2 = IMP.pmi1.tools.select(representation,
121  resolution=resolution,
122  name=tuple_selection2[2],
123  residue=tuple_selection2[0])
124  elif root_hier and not representation:
125  model = root_hier.get_model()
126  copy_num1 = 0
127  if len(tuple_selection1) > 3:
128  copy_num1 = tuple_selection1[3]
129  copy_num2 = 0
130  if len(tuple_selection2) > 3:
131  copy_num2 = tuple_selection2[3]
132
133  sel1 = IMP.atom.Selection(root_hier,
134  resolution=resolution,
135  molecule=tuple_selection1[2],
136  residue_index=tuple_selection1[0],
137  copy_index=copy_num1)
138  particles1 = sel1.get_selected_particles()
139  sel2 = IMP.atom.Selection(root_hier,
140  resolution=resolution,
141  molecule=tuple_selection2[2],
142  residue_index=tuple_selection2[0],
143  copy_index=copy_num2)
144  particles2 = sel2.get_selected_particles()
145  else:
146  raise Exception("Pass representation or root_hier, not both")
147
148  super(DistanceRestraint, self).__init__(model, label=label,
149  weight=weight)
150  print(self.name)
151
152  print("Created distance restraint between "
153  "%s and %s" % (particles1[0].get_name(),
154  particles2[0].get_name()))
155
156  if len(particles1) > 1 or len(particles2) > 1:
157  raise ValueError("more than one particle selected")
158
160  IMP.core.DistanceRestraint(self.model, ts1,
161  particles1[0],
162  particles2[0]))
164  IMP.core.DistanceRestraint(self.model, ts2,
165  particles1[0],
166  particles2[0]))
167
168
169 class TorqueRestraint(IMP.Restraint):
170  import math
171  def __init__(self, m, objects, resolution, angular_tolerance,label='None'):
172  IMP.Restraint.__init__(self, m, "TorqueRestraint %1%")
173  self.softness_angle = 0.5
174  self.plateau = 1e-10
175  self.weight = 1.0
176  self.m=m
178  resolution,
179  flatten=True)
180  self.particles = [h.get_particle() for h in hierarchies]
181  self.ds=[IMP.core.XYZ(p) for p in self.particles]
182  self.label=label
183  self.at=angular_tolerance
184
185  def get_angle_probability(self,xyz,angle_center):
186  maxtheta=angle_center+self.at
187  mintheta=angle_center-self.at
188  angle=self.math.atan2(xyz.get_y(),xyz.get_x() )*180.0/self.math.pi
189  anglediff = (angle - maxtheta + 180 + 360) % 360 - 180
190  argvalue1=anglediff / self.softness_angle
191  anglediff = (angle - mintheta + 180 + 360) % 360 - 180
192  argvalue2=-anglediff / self.softness_angle
193  prob = (1.0-self.plateau) / (1.0 + self.math.exp(-max(argvalue1,argvalue2)))
194  return prob
195
196  def unprotected_evaluate(self, da):
197  s=0.0
198  center=IMP.core.get_centroid(self.ds)
199  angle_center=self.math.atan2(center[1],center[0])*180.0/self.math.pi
200  for xyz in self.ds:
201  s+=-self.math.log(1.0-self.get_angle_probability(xyz,angle_center))
202  return s
203
204  def do_get_inputs(self):
205  return self.particles
206
209
210  def get_output(self):
211  output = {}
212  score = self.weight * self.unprotected_evaluate(None)
213  output["_TotalScore"] = str(score)
214  output["TorqueRestraint_" + self.label] = str(score)
215  return output
216
217
218
219
221  '''
222  PMI2 python restraint. Restrains particles within a
223  Cylinder aligned along the z-axis and
224  centered in x,y=0,0
225  Optionally, one can restrain the cylindrical angle
226  '''
227  import math
228  def __init__(self, m, objects, resolution, radius,mintheta=None,
229  maxtheta=None,repulsive=False,label='None'):
230  '''
231  @param objects PMI2 objects
232  @param resolution the resolution you want the restraint to be applied
234  @param mintheta minimum cylindrical angle in degrees
235  @param maxtheta maximum cylindrical angle in degrees
236  '''
237  IMP.Restraint.__init__(self, m, "CylinderRestraint %1%")
239  self.softness = 3.0
240  self.softness_angle = 0.5
241  self.plateau = 1e-10
242  self.weight = 1.0
243  self.m=m
244  self.mintheta=mintheta
245  self.maxtheta=maxtheta
246  self.repulsive=repulsive
248  resolution,
249  flatten=True)
250  self.particles = [h.get_particle() for h in hierarchies]
251  self.label=label
252
253  def get_probability(self,p):
254  xyz=IMP.core.XYZ(p)
255  r=self.math.sqrt(xyz.get_x()**2+xyz.get_y()**2)
257  if self.repulsive: argvalue=-argvalue
258  prob = (1.0 - self.plateau) / (1.0 + self.math.exp(-argvalue))
259  return prob
260
261  def get_angle_probability(self,p):
262  xyz=IMP.core.XYZ(p)
263  angle=self.math.atan2(xyz.get_y(),xyz.get_x() )*180.0/self.math.pi
264  anglediff = (angle - self.maxtheta + 180 + 360) % 360 - 180
265  argvalue1=anglediff / self.softness_angle
266  anglediff = (angle - self.mintheta + 180 + 360) % 360 - 180
267  argvalue2=-anglediff / self.softness_angle
268  prob = (1.0-self.plateau) / (1.0 + self.math.exp(-max(argvalue1,argvalue2)))
269  return prob
270
271  def unprotected_evaluate(self, da):
272  s=0.0
273  for p in self.particles:
274  s+=-self.math.log(1.0-self.get_probability(p))
275  if self.mintheta is not None and self.maxtheta is not None:
276  s+=-self.math.log(1.0-self.get_angle_probability(p))
277  return s
278
279  def do_get_inputs(self):
280  return self.particles
281
284
285  def get_output(self):
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),
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  model = representation.prot.get_model()
372  ps = IMP.pmi1.tools.select(representation,
373  resolution=resolution,
374  name=tuple_selection[2],
375  residue=tuple_selection[0])
376  elif root_hier and not representation:
377  model = 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__(model, label=label,
396  weight=weight)
398
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
410  lsc = IMP.container.ListSingletonContainer(self.model)
412
413  r3 = IMP.container.SingletonsRestraint(ss3, lsc)
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.
Lower bound harmonic function (non-zero when feature < mean)
Adapt things for PMI (degrees of freedom, restraints, ...) Returns list of list of hierarchies...
Definition: /tools.py:1621
Various classes to hold sets of particles.
Upper bound harmonic function (non-zero when feature > mean)
def __init__
Setup external barrier restraint.
Classes to handle different kinds of restraints.
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
def get_output
Get outputs to write to stat files.
Miscellaneous utilities.
Definition: /tools.py:1
Store a list of ParticleIndexes.
Apply a function to the distance to a fixed point.
A decorator for a particle with x,y,z coordinates.
Definition: XYZ.h:30
Base class for PMI restraints, which wrap IMP.Restraint(s).
Restraint for anchoring a particle to a specific coordinate.
def select
this function uses representation=SimplifiedModel it returns the corresponding selected particles rep...
Definition: /tools.py:727
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...
Restraint to keep all structures inside sphere.
The general base class for IMP exceptions.
Definition: exception.h:49
VectorD< 3 > Vector3D
Definition: VectorD.h:421
a python restraint with bistable potential Authors: G.