IMP logo
IMP Reference Guide  develop.7482b7c7af, 2026/12/05
The Integrative Modeling Platform
write_a_restraint.py
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
7import IMP
8import sys
9
10IMP.setup_from_argv(sys.argv, "Restraint example")
11
12# a restraint which checks if particles are sorted in
13# increasing order on k.
14
15
16class MyRestraint(IMP.Restraint):
17 # take the list of particles and the key to use
18
19 def __init__(self, m, ps, k):
20 super().__init__(m, "MyRestraint %1%")
21 self.ps = ps
22 self.k = k
23
24 def unprotected_evaluate(self, da):
25 score = 0
26 for i in range(1, len(self.ps)):
27 p0 = self.ps[i - 1]
28 p1 = self.ps[i]
29 if p0.get_value(k) > p1.get_value(k):
30 diff = (p0.get_value(k) - p1.get_value(k))
31 score = score + diff
32 p0.add_to_derivative(k, -1, da)
33 p1.add_to_derivative(k, 1, da)
34 else:
35 if IMP.get_log_level() >= IMP.TERSE:
36 print(p0.get_name(), "and", p1.get_name(), " are ok")
37 return score
38
39 def do_get_inputs(self):
40 return self.ps
41
42
43# some code to create and evaluate it
44k = IMP.FloatKey("a key")
45m = IMP.Model()
46ps = []
47for i in range(0, 10):
48 p = IMP.Particle(m)
49 p.add_attribute(k, i)
50 ps.append(p)
51r = MyRestraint(m, ps, k)
52# IMP.set_log_level(IMP.TERSE)
53print(r.evaluate(True))
Class for storing model, its restraints, constraints, and particles.
Definition Model.h:111
Class to handle individual particles of a Model object.
Definition Particle.h:45
A restraint is a term in an IMP ScoringFunction.
Definition Restraint.h:56
void setup_from_argv(int argc, char **argv, std::string description)
Parse the command line flags and return the positional arguments.
LogLevel get_log_level()
Get the currently active global log level.
Definition log.h:92