IMP logo
IMP Reference Guide  develop.7482b7c7af, 2026/12/05
The Integrative Modeling Platform
replica_exchange.py
1#!/usr/bin/env python3
2
3import sys
4import os
5import errno
6import atexit
7import random
8
9# Comment either this line or the following to attain different communication schemes:
10# to start pyro
11try:
12 from IMP.isd.PyroGrid import PyroGrid as Grid
13# from IMP.isd.FileBasedGrid import FileBasedGrid as Grid
14except ImportError:
15 print("This example needs the Python Pyro module", file=sys.stderr)
16 sys.exit(0)
17from IMP.isd.hosts import create_host_list
18import IMP.atom
19import IMP.container
20import IMP.isd
21from IMP.isd.Replica import ReplicaTracker
22
23import _shared_functions as sf
24
25IMP.set_log_level(IMP.NONE)
26
27# simulation settings
28# where to output files
29outfolder = os.path.join(os.getcwd(), 'results')
30# temp dir
31tmpdir = os.path.join(os.getcwd(), 'tmp')
32# number of replicas / hosts
33nreps = 8
34# lambda scaling distribution
35kB = (1.381 * 6.02214) / 4184.0
36lambda_1 = 1.0
37lambda_N = 0.8
38lambdas = [lambda_N * (lambda_1 / lambda_N) ** ((float(nreps) - k) / (nreps - 1))
39 for k in xrange(1, nreps + 1)]
40# thermostat coupling constant (berendsen, in fs)
41tau = [500.0] * nreps
42# stat_rate is the rate at which to print out traj statistics
43#(in units of gibbs sampling steps)
44stat_rate = [1] * nreps
45# list of files relative to the current dir to copy over to all nodes
46initpdb = IMP.isd.get_example_path("generated2.pdb")
47charmmtop = IMP.isd.get_example_path("top.lib")
48charmmpar = IMP.isd.get_example_path("par.lib")
49restraints = IMP.isd.get_example_path("NOE_HN-full_7A_sparse100.tbl")
50sequence = IMP.isd.get_example_path('sequence.dat')
51# export the files in a local tmp directory
52# add whatever you want
53filelist = [initpdb, charmmtop, charmmpar, sequence,
54 restraints, IMP.isd.get_example_path('_shared_functions.py')]
55# prefix of output files
56nums = [os.path.join(outfolder, 'r%02d' % (i + 1)) for i in xrange(nreps)]
57# thermalization (mc parameters stay fixed)
58n_therm = 100 # number of loops, where temperatures are scaled to target value
59n_hmc_therm = 10 # number of steps per loop
60# number of gibbs sampling steps in the first temperature relaxation
61n_gibbs1 = 100
62# number of gibbs sampling steps in the second temperature relaxation
63n_gibbs2 = 100
64# number of gibbs sampling steps in the production temperature relaxation
65n_gibbs3 = 10000
66# number of md steps
67n_md = 1000
68# number of mc steps (not < 50 because adaptive)
69n_mc = 100
70# where to run sims
71hostlist = ['localhost'] * nreps
72#qsub or ssh
73grid_method = 'ssh'
74# "-now no -cwd -q -j y -N 'slave' -S /bin/bash"
75qsub_config = "-inherit $HOSTNAME"
76# replica exchange scheme
77rex_scheme = 'standard'
78# replica exchange exchange method
79rex_xchg = 'random'
80# whether to use TuneRex to tune temperatures
81tune_temps = True
82tune_data = {'rate': 100, # temp optimization rate, in rex steps.
83 'method': 'ar',
84 # either "ar" acceptance ratio optimization, or "flux"
85 # optimization
86 'alpha': 0.05} # type I error on the estimates
87templog = os.path.join(outfolder, 'temps.txt')
88rexlog = os.path.join(outfolder, 'replicanums.txt')
89
90# misc
91
92imppy = os.path.abspath(
93 os.path.join(os.getenv('IMP_ISD_DATA'), '../../tools/imppy.sh'))
94src_path = os.path.abspath(
95 os.path.join(os.getenv('IMP_ISD_DATA'), '../lib/IMP/isd'))
96showX11 = False
97grid_debug = False
98grid_verbose = False
99X11_delay = 1.0
100window_size = '80x25'
101# pyroGrid
102shared_temp_path = True
103terminate_during_publish = False
104nshost = None
105
106
107def mkdir_p(path):
108 "mkdir -p, taken from stackoverflow"
109 try:
110 os.makedirs(path)
111 except OSError as exc:
112 if exc.errno == errno.EEXIST:
113 pass
114 else:
115 raise
116
117
118def launch_grid():
119 hosts = create_host_list(hostlist, tmpdir)
120 for host in hosts:
121 # ugly hack
122 host.init_cmd = imppy + ' !'
123
124 # pyro grid
125 grid = Grid(hosts, src_path, showX11, X11_delay, grid_debug,
126 grid_verbose, shared_temp_path, nshost, terminate_during_publish,
127 method=grid_method, qsub_config=qsub_config)
128
129 # uncomment the following lines and comments the two previous ones to use file based grid
130 # file based grid
131 # grid = Grid(hosts, src_path, showX11, X11_delay, grid_debug,
132 # grid_verbose)
133 #grid.shared_temp_path = shared_temp_path
134 if showX11:
135 grid.window_size = window_size
136 grid.copy_files('./', filelist)
137 # grid.copy_files(src_path,["_shared_functions.py"])
138
139 # start grid on all nodes
140 grid.start()
141 return grid
142
143
144def main():
145
146 # launch grid
147 print("launching grid")
148 grid = launch_grid()
149
150 # publish the shared object
151 print("publishing sfo")
152 sfo = sf.sfo()
153 sfo_id = grid.publish(sfo)
154
155 print("communication test")
156 # get a worker to do a task
157 #proxy = grid.acquire_service(sfo_id)
158 # print proxy.hello().get()
159 # grid.release_service(proxy)
160
161 print("broadcast test")
162 print(grid.gather(grid.broadcast(sfo_id, 'hello')))
163
164 # call init on all nodes
165 print("initializing model")
166 mkdir_p(tmpdir)
167 mkdir_p(outfolder)
168 requests = grid.broadcast(
169 sfo_id,
170 'init_model',
171 tmpdir,
172 sequence,
173 initpdb,
174 restraints)
175 # wait til init is done
176 results = grid.gather(requests)
177
178 # turn off verbose noise (works because IMP.NONE is picklable, being
179 # an int.
180 grid.gather(grid.broadcast(sfo_id, 'set_checklevel', IMP.NONE))
181 grid.gather(grid.broadcast(sfo_id, 'set_loglevel', IMP.NONE))
182
183 # evaluate the score of the whole system (without derivatives, False flag)
184 print("initial energy")
185 grid.gather(grid.broadcast(sfo_id, 'm', 'evaluate', False))
186
187 # berendsen 300K tau=0.5ps
188 # perform two independent MC moves for sigma and gamma
189 print("initializing simulation and statistics")
190 grid.gather(grid.scatter(sfo_id, 'init_simulation',
191 zip(lambdas, tau)))
192 grid.gather(grid.scatter(sfo_id, 'init_stats', zip(nums, stat_rate)))
193 replica = ReplicaTracker(nreps, lambdas, grid, sfo_id,
194 rexlog=rexlog,
195 scheme=rex_scheme, xchg=rex_xchg,
196 tune_temps=tune_temps, tune_data=tune_data, templog=templog)
197
198 print("thermalization")
199 for i in range(n_therm):
200 print("\rgibbs step %d" % i, end=' ')
201 sys.stdout.flush()
202 grid.gather(grid.scatter(sfo_id, 'set_inv_temp',
203 [n_therm / float(i + 1) * l for l in lambdas]))
204 grid.gather(grid.broadcast(sfo_id, 'do_md', n_hmc_therm))
205 grid.gather(grid.broadcast(sfo_id, 'write_stats'))
206
207 print("start gibbs sampling loop: first relaxation")
208 for i in range(n_gibbs1):
209 print("\rgibbs step %d" % i, end=' ')
210 sys.stdout.flush()
211 # print " md"
212 grid.gather(grid.broadcast(sfo_id, 'do_md', n_md))
213 # print " mc"
214 grid.gather(grid.broadcast(sfo_id, 'do_mc', n_mc))
215 grid.gather(grid.broadcast(sfo_id, 'write_stats'))
216 # print " swaps"
217 replica.tune_data['dumb_scale'] = 0.5
218 replica.replica_exchange()
219 # print " stats"
220 replica.write_rex_stats()
221
222 print("start gibbs sampling loop: second relaxation")
223 for i in range(n_gibbs2):
224 print("\rgibbs step %d" % i, end=' ')
225 sys.stdout.flush()
226 # print " md"
227 grid.gather(grid.broadcast(sfo_id, 'do_md', n_md))
228 # print " mc"
229 grid.gather(grid.broadcast(sfo_id, 'do_mc', n_mc))
230 grid.gather(grid.broadcast(sfo_id, 'write_stats'))
231 # print " swaps"
232 replica.tune_data['dumb_scale'] = 0.2
233 replica.replica_exchange()
234 # print " stats"
235 replica.write_rex_stats()
236
237 print("start gibbs sampling loop: production")
238 for i in range(n_gibbs3):
239 print("\rgibbs step %d" % i, end=' ')
240 sys.stdout.flush()
241 # print " md"
242 grid.gather(grid.broadcast(sfo_id, 'do_md', n_md))
243 # print " mc"
244 grid.gather(grid.broadcast(sfo_id, 'do_mc', n_mc))
245 grid.gather(grid.broadcast(sfo_id, 'write_stats'))
246 # print " swaps"
247 replica.tune_temps = False
248 replica.replica_exchange()
249 # print " stats"
250 replica.write_rex_stats()
251
252 print("terminating grid")
253 grid.terminate()
254 print("done.")
255
256
257if __name__ == '__main__':
258
259 main()
Functionality for loading, creating, manipulating and scoring atomic structures.
Various classes to hold sets of particles.
IMP::isd.Replica
Definition Replica.py:1
Inferential scoring building on methods developed as part of the Inferential Structure Determination ...
std::string get_example_path(std::string file_name)
Return the full path to one of this module's example files.
void set_log_level(LogLevel l)
Set the current global log level.