IMP logo
IMP Reference Guide  develop.1441b25730,2025/12/12
The Integrative Modeling Platform
kernel/write_an_optimizer_state.py

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

1 ## \example kernel/write_an_optimizer_state.py
2 # While we do not recommend doing serious work using optimizer states
3 # written in Python, it is often useful when prototyping or testing code.
4 # Copy this example and modify as needed.
5 
6 import IMP
7 import sys
8 
9 IMP.setup_from_argv(sys.argv, "Optimizer state")
10 
11 
12 class MyOptimizerState(IMP.OptimizerState):
13  "An optimizer state which prints out the last scores of some restraints"
14 
15  def __init__(self, rs):
16  super().__init__(rs[0].get_model(), "MyOptimizerState%1%")
17  self.rs = rs
18 
19  def update(self):
20  for r in self.rs:
21  print(r.get_name(), r.get_last_score())
22 
23 
24 # some code to create and evaluate it
25 k = IMP.FloatKey("a key")
26 m = IMP.Model()
27 # we don't have any real restraints in the kernel
28 r0 = IMP._ConstRestraint(m, [], 1)
29 r0.set_name("restraint 0")
30 
31 r1 = IMP._ConstRestraint(m, [], 2)
32 r1.set_name("restraint 1")
33 
34 rs = IMP.RestraintSet([r0, r1], 1.0)
35 sf = rs.create_scoring_function()
36 
37 os = MyOptimizerState([r0, r1])
38 os.set_name("Python optimizer state")
39 # we don't have any optimizers either
40 co = IMP._ConstOptimizer(m)
41 co.set_scoring_function(sf)
42 co.add_optimizer_state(os)
43 print(co.optimize(100))
44 
45 # this is needed to clean up memory properly for some reason
46 co.remove_optimizer_state(os)
47 del os
48 del m