IMP logo
IMP Reference Guide  2.19.0
The Integrative Modeling Platform
kernel/write_a_restraint.py

While we do not recommend doing serious work using restraints written in Python, it is often useful when prototyping or testing code. Copy this example and modify as needed.

1 ## \example kernel/write_a_restraint.py
2 # While we do not recommend doing serious work using restraints written
3 # in Python, it is often useful when prototyping or testing code.
4 # Copy this example and modify as needed.
5 #
6 
7 from __future__ import print_function
8 import IMP
9 import sys
10 
11 IMP.setup_from_argv(sys.argv, "Restraint example")
12 
13 # a restraint which checks if particles are sorted in
14 # increasing order on k.
15 
16 
17 class MyRestraint(IMP.Restraint):
18  # take the list of particles and the key to use
19 
20  def __init__(self, m, ps, k):
21  IMP.Restraint.__init__(self, m, "MyRestraint %1%")
22  self.ps = ps
23  self.k = k
24 
25  def unprotected_evaluate(self, da):
26  score = 0
27  for i in range(1, len(self.ps)):
28  p0 = self.ps[i - 1]
29  p1 = self.ps[i]
30  if p0.get_value(k) > p1.get_value(k):
31  diff = (p0.get_value(k) - p1.get_value(k))
32  score = score + diff
33  p0.add_to_derivative(k, -1, da)
34  p1.add_to_derivative(k, 1, da)
35  else:
36  if IMP.get_log_level() >= IMP.TERSE:
37  print(p0.get_name(), "and", p1.get_name(), " are ok")
38  return score
39 
40  def do_get_inputs(self):
41  return self.ps
42 
43 
44 # some code to create and evaluate it
45 k = IMP.FloatKey("a key")
46 m = IMP.Model()
47 ps = []
48 for i in range(0, 10):
49  p = IMP.Particle(m)
50  p.add_attribute(k, i)
51  ps.append(p)
52 r = MyRestraint(m, ps, k)
53 # IMP.set_log_level(IMP.TERSE)
54 print(r.evaluate(True))