1 """@namespace IMP.pmi.samplers
2 Sampling of the system.
8 class _SerialReplicaExchange(object):
9 """Dummy replica exchange class used in non-MPI builds.
10 It should act similarly to IMP.mpi.ReplicaExchange on a single processor.
14 def get_number_of_replicas(self):
16 def create_temperatures(self, tmin, tmax, nrep):
18 def get_my_index(self):
20 def set_my_parameter(self, key, val):
21 self.__params[key] = val
22 def get_my_parameter(self, key):
23 return self.__params[key]
24 def get_friend_index(self, step):
26 def get_friend_parameter(self, key, findex):
27 return self.get_my_parameter(key)
28 def do_exchange(self, myscore, fscore, findex):
32 class MonteCarlo(object):
41 def __init__(self, m, objects, temp, filterbyname=None):
43 check that the objects containts get_particles_to_sample methods
44 and the particle type is supported
45 list of particles to sample self.losp
54 self.simulated_annealing =
False
55 self.selfadaptive =
False
66 ob.get_particles_to_sample()
68 print "MonteCarlo: object ", ob,
" doesn't have get_particles_to_sample() method"
70 pts = ob.get_particles_to_sample()
73 if "Rigid_Bodies" in k:
74 mvs = self.get_rigid_body_movers(
84 mvs = self.get_super_rigid_body_movers(
92 if "Floppy_Bodies" in k:
93 mvs = self.get_floppy_body_movers(pts[k][0], pts[k][1])
99 mvs = self.get_X_movers(pts[k][0], pts[k][1])
105 if not self.isd_available:
106 raise ValueError(
"isd module needed to use nuisances")
107 mvs = self.get_nuisance_movers(pts[k][0], pts[k][1])
113 if not self.isd_available:
114 raise ValueError(
"isd module needed to use weights")
115 mvs = self.get_weight_movers(pts[k][0], pts[k][1])
124 self.mc.set_return_best(
False)
125 self.mc.set_kt(self.temp)
126 self.mc.add_mover(self.smv)
128 def set_kt(self, temp):
135 def set_scoring_function(self, objectlist):
137 for ob
in objectlist:
138 rs.add_restraint(ob.get_restraint())
140 self.mc.set_scoring_function(sf)
142 def set_simulated_annealing(
148 self.simulated_annealing =
True
149 self.tempmin = min_temp
150 self.tempmax = max_temp
151 self.timemin = min_temp_time
152 self.timemax = max_temp_time
154 def set_self_adaptive(self, isselfadaptive=True):
155 self.selfadaptive = isselfadaptive
157 def get_nuisance_movers_parameters(self):
158 '''returns a dictionary with the mover parameters
159 for nuisance parameters'''
161 for i
in range(self.get_number_of_movers()):
162 mv = self.smv.get_mover(i)
164 if "Nuisances" in name:
165 stepsize = IMP.core.NormalMover.get_from(mv).get_sigma()
166 output[name] = stepsize
169 def get_number_of_movers(self):
170 return len(self.smv.get_movers())
172 def get_particle_types():
175 def optimize(self, nstep):
177 self.mc.optimize(nstep * self.get_number_of_movers())
180 if self.simulated_annealing:
181 self.temp = self.temp_simulated_annealing()
182 self.mc.set_kt(self.temp)
185 if self.selfadaptive:
186 for i, mv
in enumerate(self.smv.get_movers()):
189 if "Nuisances" in name:
190 mvacc = mv.get_number_of_accepted()
191 mvprp = mv.get_number_of_proposed()
192 accept = float(mvacc) / float(mvprp)
193 nmv = IMP.core.NormalMover.get_from(mv)
194 stepsize = nmv.get_sigma()
196 if 0.4 > accept
or accept > 0.6:
197 nmv.set_sigma(stepsize * 2 * accept)
200 nmv.set_sigma(stepsize * 2 * accept)
203 nmv.set_sigma(stepsize * 2 * accept)
205 if "Weights" in name:
207 mvacc = mv.get_number_of_accepted()
208 mvprp = mv.get_number_of_proposed()
209 accept = float(mvacc) / float(mvprp)
210 wmv = IMP.isd.WeightMover.get_from(mv)
211 stepsize = wmv.get_radius()
213 if 0.4 > accept
or accept > 0.6:
214 wmv.set_radius(stepsize * 2 * accept)
217 wmv.set_radius(stepsize * 2 * accept)
220 wmv.set_radius(stepsize * 2 * accept)
222 def run(self, *args, **kwargs):
223 IMP.pmi.tools.print_deprecation_warning(
225 "MonteCarlo.optimize")
226 self.optimize(*args, **kwargs)
228 def get_nuisance_movers(self, nuisances, maxstep):
230 for nuisance
in nuisances:
231 print nuisance, maxstep
238 def get_rigid_body_movers(self, rbs, maxtrans, maxrot):
244 def get_super_rigid_body_movers(self, rbs, maxtrans, maxrot):
258 srbm.add_xyz_particle(xyz)
260 srbm.add_rigid_body_particle(rb)
264 def get_floppy_body_movers(self, fbs, maxtrans):
272 fb.set_is_optimized(fk,
True)
282 def get_X_movers(self, fbs, maxtrans):
288 raise ValueError(
"particle is part of a rigid body")
294 def get_weight_movers(self, weights, maxstep):
296 for weight
in weights:
297 if(weight.get_number_of_states() > 1):
301 def temp_simulated_annealing(self):
302 if self.nframe % (self.timemin + self.timemax) < self.timemin:
306 temp = self.tempmin + (self.tempmax - self.tempmin) * value
309 def set_label(self, label):
312 def get_frame_number(self):
315 def get_output(self):
318 for i, mv
in enumerate(self.smv.get_movers()):
319 mvname = mv.get_name()
320 mvacc = mv.get_number_of_accepted()
321 mvprp = mv.get_number_of_proposed()
323 mvacr = float(mvacc) / float(mvprp)
326 output[
"MonteCarlo_Acceptance_" +
327 mvname +
"_" + str(i)] = str(mvacr)
328 if "Nuisances" in mvname:
329 output[
"MonteCarlo_StepSize_" + mvname +
"_" +
330 str(i)] = str(IMP.core.NormalMover.get_from(mv).get_sigma())
331 if "Weights" in mvname:
332 output[
"MonteCarlo_StepSize_" + mvname +
"_" +
333 str(i)] = str(IMP.isd.WeightMover.get_from(mv).get_radius())
334 output[
"MonteCarlo_Temperature"] = str(self.mc.get_kt())
335 output[
"MonteCarlo_Nframe"] = str(self.nframe)
339 class MolecularDynamics(object):
340 def __init__(self,m,objects,kt,gamma=0.01,maximum_time_step=1.0):
344 to_sample+=obj.get_particles_to_sample()[
'Floppy_Bodies_SimplifiedModel'][0]
349 self.md.set_maximum_time_step(maximum_time_step)
350 self.md.add_optimizer_state(self.ltstate)
351 self.simulated_annealing =
False
355 self.ltstate.set_temperature(temp)
356 self.md.assign_velocities(temp)
358 def set_simulated_annealing(
364 self.simulated_annealing =
True
365 self.tempmin = min_temp
366 self.tempmax = max_temp
367 self.timemin = min_temp_time
368 self.timemax = max_temp_time
370 def temp_simulated_annealing(self):
371 if self.nframe % (self.timemin + self.timemax) < self.timemin:
375 temp = self.tempmin + (self.tempmax - self.tempmin) * value
378 def set_gamma(self,gamma):
379 self.ltstate.set_gamma(gamma)
381 def optimize(self,nsteps):
383 if self.simulated_annealing:
384 self.temp = self.temp_simulated_annealing()
385 self.set_kt(self.temp)
386 self.md.optimize(nsteps)
388 def get_output(self):
390 output[
"MolecularDynamics_KineticEnergy"]=str(self.md.get_kinetic_energy())
393 class ConjugateGradients(object):
395 def __init__(self, m, objects):
400 def set_label(self, label):
403 def get_frame_number(self):
406 def run(self, nstep):
408 self.cg.optimize(nstep)
410 def set_scoring_function(self, objectlist):
412 for ob
in objectlist:
413 rs.add_restraint(ob.get_restraint())
415 self.cg.set_scoring_function(sf)
417 def get_output(self):
420 output[
"ConjugatedGradients_Nframe"] = str(self.nframe)
424 class ReplicaExchange(object):
433 replica_exchange_object=
None):
435 samplerobjects can be a list of MonteCarlo or MolecularDynamics
440 self.samplerobjects = samplerobjects
442 self.TEMPMIN_ = tempmin
443 self.TEMPMAX_ = tempmax
445 if replica_exchange_object
is None:
451 self.rem = _SerialReplicaExchange()
455 print 'got existing rex object'
456 self.rem = replica_exchange_object
459 nproc = self.rem.get_number_of_replicas()
461 if nproc % 2 != 0
and test ==
False:
462 raise Exception,
"number of replicas has to be even. set test=True to run with odd number of replicas."
464 temp = self.rem.create_temperatures(
469 self.temperatures = temp
471 myindex = self.rem.get_my_index()
473 self.rem.set_my_parameter(
"temp", [self.temperatures[myindex]])
474 for so
in self.samplerobjects:
475 so.set_kt(self.temperatures[myindex])
481 def get_temperatures(self):
482 return self.temperatures
484 def get_my_temp(self):
485 return self.rem.get_my_parameter(
"temp")[0]
487 def get_my_index(self):
488 return self.rem.get_my_index()
490 def swap_temp(self, nframe, score=None):
492 score = self.m.evaluate(
False)
494 myindex = self.rem.get_my_index()
495 mytemp = self.rem.get_my_parameter(
"temp")[0]
497 if mytemp == self.TEMPMIN_:
500 if mytemp == self.TEMPMAX_:
504 myscore = score / mytemp
507 findex = self.rem.get_friend_index(nframe)
508 ftemp = self.rem.get_friend_parameter(
"temp", findex)[0]
510 fscore = score / ftemp
513 flag = self.rem.do_exchange(myscore, fscore, findex)
518 for so
in self.samplerobjects:
522 def get_output(self):
525 if self.nattempts != 0:
526 output[
"ReplicaExchange_SwapSuccessRatio"] = str(
527 float(self.nsuccess) / self.nattempts)
528 output[
"ReplicaExchange_MinTempFrequency"] = str(
529 float(self.nmintemp) / self.nattempts)
530 output[
"ReplicaExchange_MaxTempFrequency"] = str(
531 float(self.nmaxtemp) / self.nattempts)
533 output[
"ReplicaExchange_SwapSuccessRatio"] = str(0)
534 output[
"ReplicaExchange_MinTempFrequency"] = str(0)
535 output[
"ReplicaExchange_MaxTempFrequency"] = str(0)
536 output[
"ReplicaExchange_CurrentTemp"] = str(self.get_my_temp())
540 class PyMCMover(object):
543 def __init__(self, representation, mcchild, n_mc_steps):
548 self.rbs = representation.get_rigid_bodies()
551 self.n_mc_steps = n_mc_steps
553 def store_move(self):
556 for copy
in self.rbs:
559 crd.append(rb.get_reference_frame())
560 self.oldcoords.append(crd)
562 def propose_move(self, prob):
563 self.mc.run(self.n_mc_steps)
565 def reset_move(self):
567 for copy, crd
in zip(self.rbs, self.oldcoords):
568 for rb, ref
in zip(copy, crd):
569 rb.set_reference_frame(ref)
571 def get_number_of_steps(self):
572 return self.n_mc_steps
574 def set_number_of_steps(self, nsteps):
575 self.n_mc_steps = nsteps
580 def __init__(self, model):
585 self.restraints =
None
586 self.first_call =
True
589 def add_mover(self, mv):
592 def set_kt(self, kT):
595 def set_return_best(self, thing):
598 def set_move_probability(self, thing):
601 def get_energy(self):
603 pot = sum([r.evaluate(
False)
for r
in self.restraints])
605 pot = self.m.evaluate(
False)
608 def metropolis(self, old, new):
610 print ": old %f new %f deltaE %f new_epot: %f" % (old, new, deltaE,
617 return exp(-deltaE / kT) > random.uniform(0, 1)
619 def optimize(self, nsteps):
622 print "=== new MC call"
626 self.first_call =
False
627 for i
in xrange(nsteps):
628 print "MC step %d " % i,
630 old = self.get_energy()
632 self.mv.propose_move(1)
634 new = self.get_energy()
635 if self.metropolis(old, new):
645 def get_number_of_forward_steps(self):
648 def set_restraints(self, restraints):
649 self.restraints = restraints
651 def set_scoring_function(self, objects):
655 rs.add_restraint(ob.get_restraint())
656 self.set_restraints([rs])
658 def get_output(self):
661 output[
"PyMC_Temperature"] = str(self.kT)
662 output[
"PyMC_Nframe"] = str(self.nframe)
A class to implement Hamiltonian Replica Exchange.
Maintains temperature during molecular dynamics.
Object used to hold a set of restraints.
Modify the transformation of a rigid body.
Simple conjugate gradients optimizer.
Modify a set of continuous variables by perturbing them within a ball.
static bool get_is_setup(const IMP::kernel::ParticleAdaptor &p)
Simple molecular dynamics optimizer.
Code that uses the MPI parallel library.
Modify the transformation of a rigid body.
Modify a set of continuous variables using a normal distribution.
Basic functionality that is expected to be used by a wide variety of IMP users.
static const FloatKeys & get_xyz_keys()
Get a vector containing the keys for x,y,z.
Applies a list of movers one at a time.
Inferential scoring building on methods developed as part of the Inferential Structure Determination ...