IMP logo
IMP Reference Guide  2.10.1
The Integrative Modeling Platform
kernel/write_an_optimizer_state.py

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