1 """@namespace IMP.pmi.samplers
2 Sampling of the system.
5 from __future__
import print_function
10 class _SerialReplicaExchange(object):
11 """Dummy replica exchange class used in non-MPI builds.
12 It should act similarly to IMP.mpi.ReplicaExchange on a single processor.
16 def get_number_of_replicas(self):
18 def create_temperatures(self, tmin, tmax, nrep):
20 def get_my_index(self):
22 def set_my_parameter(self, key, val):
23 self.__params[key] = val
24 def get_my_parameter(self, key):
25 return self.__params[key]
26 def get_friend_index(self, step):
28 def get_friend_parameter(self, key, findex):
29 return self.get_my_parameter(key)
30 def do_exchange(self, myscore, fscore, findex):
32 def set_was_used(self,was_used):
33 self.was_used = was_used
37 """Sample using Monte Carlo"""
46 def __init__(self, m, objects=None, temp=1.0, filterbyname=None):
47 """Setup Monte Carlo sampling
48 @param m The IMP Model
49 @param objects What to sample. Use flat list of particles or
50 (deprecated) 'MC Sample Objects' from PMI1
51 @param temp The MC temperature
52 @param filterbyname Not used
61 self.simulated_annealing =
False
62 self.selfadaptive =
False
72 gather_objects =
False
74 objects[0].get_particles_to_sample()
81 pts = ob.get_particles_to_sample()
84 if "Rigid_Bodies" in k:
85 mvs = self.get_rigid_body_movers(
95 mvs = self.get_super_rigid_body_movers(
103 if "Floppy_Bodies" in k:
104 mvs = self.get_floppy_body_movers(pts[k][0], pts[k][1])
110 mvs = self.get_X_movers(pts[k][0], pts[k][1])
116 if not self.isd_available:
117 raise ValueError(
"isd module needed to use nuisances")
118 mvs = self.get_nuisance_movers(pts[k][0], pts[k][1])
124 if not self.isd_available:
125 raise ValueError(
"isd module needed to use weights")
126 mvs = self.get_weight_movers(pts[k][0], pts[k][1])
132 mvs = self.get_surface_movers(
145 self.mc.set_scoring_function(get_restraint_set(self.m))
146 self.mc.set_return_best(
False)
147 self.mc.set_kt(self.temp)
148 self.mc.add_mover(self.smv)
150 def set_kt(self, temp):
157 def set_scoring_function(self, objectlist):
159 for ob
in objectlist:
160 rs.add_restraint(ob.get_restraint())
162 self.mc.set_scoring_function(sf)
164 def set_simulated_annealing(
170 self.simulated_annealing =
True
171 self.tempmin = min_temp
172 self.tempmax = max_temp
173 self.timemin = min_temp_time
174 self.timemax = max_temp_time
176 def set_self_adaptive(self, isselfadaptive=True):
177 self.selfadaptive = isselfadaptive
181 Return a dictionary with the mover parameters for nuisance parameters
184 for i
in range(self.get_number_of_movers()):
185 mv = self.smv.get_mover(i)
187 if "Nuisances" in name:
188 stepsize = IMP.core.NormalMover.get_from(mv).get_sigma()
189 output[name] = stepsize
192 def get_number_of_movers(self):
193 return len(self.smv.get_movers())
195 def get_particle_types():
198 def optimize(self, nstep):
200 self.mc.optimize(nstep * self.get_number_of_movers())
203 if self.simulated_annealing:
204 self.temp = self.temp_simulated_annealing()
205 self.mc.set_kt(self.temp)
208 if self.selfadaptive:
209 for i, mv
in enumerate(self.smv.get_movers()):
212 if "Nuisances" in name:
213 mvacc = mv.get_number_of_accepted()
214 mvprp = mv.get_number_of_proposed()
215 accept = float(mvacc) / float(mvprp)
216 nmv = IMP.core.NormalMover.get_from(mv)
217 stepsize = nmv.get_sigma()
219 if 0.4 > accept
or accept > 0.6:
220 nmv.set_sigma(stepsize * 2 * accept)
223 nmv.set_sigma(stepsize * 2 * accept)
226 nmv.set_sigma(stepsize * 2 * accept)
228 if "Weights" in name:
230 mvacc = mv.get_number_of_accepted()
231 mvprp = mv.get_number_of_proposed()
232 accept = float(mvacc) / float(mvprp)
233 wmv = IMP.isd.WeightMover.get_from(mv)
234 stepsize = wmv.get_radius()
236 if 0.4 > accept
or accept > 0.6:
237 wmv.set_radius(stepsize * 2 * accept)
240 wmv.set_radius(stepsize * 2 * accept)
243 wmv.set_radius(stepsize * 2 * accept)
246 def run(self, *args, **kwargs):
247 self.optimize(*args, **kwargs)
249 def get_nuisance_movers(self, nuisances, maxstep):
251 for nuisance
in nuisances:
252 print(nuisance, maxstep)
259 def get_rigid_body_movers(self, rbs, maxtrans, maxrot):
266 def get_super_rigid_body_movers(self, rbs, maxtrans, maxrot):
273 if type(rb[2]) == tuple
and type(rb[2][0]) == float \
274 and type(rb[2][1]) == float
and type(rb[2][2]) == float \
292 print(
"Setting up a super rigid body with wrong parameters")
296 srbm.add_xyz_particle(xyz)
298 srbm.add_rigid_body_particle(rb)
302 def get_floppy_body_movers(self, fbs, maxtrans):
310 fb.set_is_optimized(fk,
True)
320 def get_X_movers(self, fbs, maxtrans):
326 raise ValueError(
"particle is part of a rigid body")
332 def get_weight_movers(self, weights, maxstep):
334 for weight
in weights:
335 if(weight.get_number_of_states() > 1):
339 def get_surface_movers(self, surfaces, maxtrans, maxrot, refprob):
341 for surface
in surfaces:
346 def temp_simulated_annealing(self):
347 if self.nframe % (self.timemin + self.timemax) < self.timemin:
351 temp = self.tempmin + (self.tempmax - self.tempmin) * value
354 def set_label(self, label):
357 def get_frame_number(self):
360 def get_output(self):
363 for i, mv
in enumerate(self.smv.get_movers()):
364 mvname = mv.get_name()
365 mvacc = mv.get_number_of_accepted()
366 mvprp = mv.get_number_of_proposed()
368 mvacr = float(mvacc) / float(mvprp)
371 output[
"MonteCarlo_Acceptance_" +
372 mvname +
"_" + str(i)] = str(mvacr)
373 if "Nuisances" in mvname:
374 output[
"MonteCarlo_StepSize_" + mvname +
"_" +
375 str(i)] = str(IMP.core.NormalMover.get_from(mv).get_sigma())
376 if "Weights" in mvname:
377 output[
"MonteCarlo_StepSize_" + mvname +
"_" +
378 str(i)] = str(IMP.isd.WeightMover.get_from(mv).get_radius())
379 output[
"MonteCarlo_Temperature"] = str(self.mc.get_kt())
380 output[
"MonteCarlo_Nframe"] = str(self.nframe)
385 """Sample using molecular dynamics"""
387 def __init__(self,m,objects,kt,gamma=0.01,maximum_time_step=1.0,sf=None):
389 @param m The IMP Model
390 @param objects What to sample. Use flat list of particles or (deprecated) 'MD Sample Objects' from PMI1
391 @param kt Temperature
392 @param gamma Viscosity parameter
393 @param maximum_time_step MD max time step
400 to_sample=obj.get_particles_to_sample()[
'Floppy_Bodies_SimplifiedModel'][0]
408 self.md.set_maximum_time_step(maximum_time_step)
410 self.md.set_scoring_function(sf)
412 self.md.set_scoring_function(get_restraint_set(self.m))
413 self.md.add_optimizer_state(self.ltstate)
414 self.simulated_annealing =
False
418 self.ltstate.set_temperature(temp)
419 self.md.assign_velocities(temp)
421 def set_simulated_annealing(self, min_temp, max_temp, min_temp_time,
423 self.simulated_annealing =
True
424 self.tempmin = min_temp
425 self.tempmax = max_temp
426 self.timemin = min_temp_time
427 self.timemax = max_temp_time
429 def temp_simulated_annealing(self):
430 if self.nframe % (self.timemin + self.timemax) < self.timemin:
434 temp = self.tempmin + (self.tempmax - self.tempmin) * value
437 def set_gamma(self,gamma):
438 self.ltstate.set_gamma(gamma)
440 def optimize(self,nsteps):
443 if self.simulated_annealing:
444 self.temp = self.temp_simulated_annealing()
445 self.set_kt(self.temp)
446 self.md.optimize(nsteps)
448 def get_output(self):
450 output[
"MolecularDynamics_KineticEnergy"]=str(self.md.get_kinetic_energy())
454 """Sample using conjugate gradients"""
456 def __init__(self, m, objects):
460 self.cg.set_scoring_function(get_restraint_set(self.m))
462 def set_label(self, label):
465 def get_frame_number(self):
469 def run(self, *args, **kwargs):
470 self.optimize(*args, **kwargs)
472 def optimize(self, nstep):
474 self.cg.optimize(nstep)
476 def set_scoring_function(self, objectlist):
478 for ob
in objectlist:
479 rs.add_restraint(ob.get_restraint())
481 self.cg.set_scoring_function(sf)
483 def get_output(self):
486 output[
"ConjugatedGradients_Nframe"] = str(self.nframe)
491 """Sample using replica exchange"""
500 replica_exchange_object=
None):
502 samplerobjects can be a list of MonteCarlo or MolecularDynamics
507 self.samplerobjects = samplerobjects
509 self.TEMPMIN_ = tempmin
510 self.TEMPMAX_ = tempmax
512 if replica_exchange_object
is None:
516 print(
'ReplicaExchange: MPI was found. Using Parallel Replica Exchange')
519 print(
'ReplicaExchange: Could not find MPI. Using Serial Replica Exchange')
520 self.rem = _SerialReplicaExchange()
524 print(
'got existing rex object')
525 self.rem = replica_exchange_object
528 nproc = self.rem.get_number_of_replicas()
530 if nproc % 2 != 0
and test ==
False:
531 raise Exception(
"number of replicas has to be even. set test=True to run with odd number of replicas.")
533 temp = self.rem.create_temperatures(
538 self.temperatures = temp
540 myindex = self.rem.get_my_index()
542 self.rem.set_my_parameter(
"temp", [self.temperatures[myindex]])
543 for so
in self.samplerobjects:
544 so.set_kt(self.temperatures[myindex])
550 def get_temperatures(self):
551 return self.temperatures
553 def get_my_temp(self):
554 return self.rem.get_my_parameter(
"temp")[0]
556 def get_my_index(self):
557 return self.rem.get_my_index()
559 def swap_temp(self, nframe, score=None):
561 score = self.m.evaluate(
False)
563 myindex = self.rem.get_my_index()
564 mytemp = self.rem.get_my_parameter(
"temp")[0]
566 if mytemp == self.TEMPMIN_:
569 if mytemp == self.TEMPMAX_:
573 myscore = score / mytemp
576 findex = self.rem.get_friend_index(nframe)
577 ftemp = self.rem.get_friend_parameter(
"temp", findex)[0]
579 fscore = score / ftemp
582 flag = self.rem.do_exchange(myscore, fscore, findex)
587 for so
in self.samplerobjects:
591 def get_output(self):
594 if self.nattempts != 0:
595 output[
"ReplicaExchange_SwapSuccessRatio"] = str(
596 float(self.nsuccess) / self.nattempts)
597 output[
"ReplicaExchange_MinTempFrequency"] = str(
598 float(self.nmintemp) / self.nattempts)
599 output[
"ReplicaExchange_MaxTempFrequency"] = str(
600 float(self.nmaxtemp) / self.nattempts)
602 output[
"ReplicaExchange_SwapSuccessRatio"] = str(0)
603 output[
"ReplicaExchange_MinTempFrequency"] = str(0)
604 output[
"ReplicaExchange_MaxTempFrequency"] = str(0)
605 output[
"ReplicaExchange_CurrentTemp"] = str(self.get_my_temp())
609 class PyMCMover(object):
612 def __init__(self, representation, mcchild, n_mc_steps):
617 self.rbs = representation.get_rigid_bodies()
620 self.n_mc_steps = n_mc_steps
622 def store_move(self):
625 for copy
in self.rbs:
628 crd.append(rb.get_reference_frame())
629 self.oldcoords.append(crd)
631 def propose_move(self, prob):
632 self.mc.run(self.n_mc_steps)
634 def reset_move(self):
636 for copy, crd
in zip(self.rbs, self.oldcoords):
637 for rb, ref
in zip(copy, crd):
638 rb.set_reference_frame(ref)
640 def get_number_of_steps(self):
641 return self.n_mc_steps
643 def set_number_of_steps(self, nsteps):
644 self.n_mc_steps = nsteps
654 self.restraints =
None
655 self.first_call =
True
658 def add_mover(self, mv):
661 def set_kt(self, kT):
664 def set_return_best(self, thing):
667 def set_move_probability(self, thing):
670 def get_energy(self):
672 pot = sum([r.evaluate(
False)
for r
in self.restraints])
674 pot = self.m.evaluate(
False)
677 def metropolis(self, old, new):
679 print(
": old %f new %f deltaE %f new_epot: %f" % (old, new, deltaE,
686 return exp(-deltaE / kT) > random.uniform(0, 1)
688 def optimize(self, nsteps):
691 print(
"=== new MC call")
695 self.first_call =
False
696 for i
in range(nsteps):
697 print(
"MC step %d " % i, end=
' ')
699 old = self.get_energy()
701 self.mv.propose_move(1)
703 new = self.get_energy()
704 if self.metropolis(old, new):
714 def get_number_of_forward_steps(self):
717 def set_restraints(self, restraints):
718 self.restraints = restraints
720 def set_scoring_function(self, objects):
724 rs.add_restraint(ob.get_restraint())
725 self.set_restraints([rs])
727 def get_output(self):
730 output[
"PyMC_Temperature"] = str(self.kT)
731 output[
"PyMC_Nframe"] = str(self.nframe)
def __init__
samplerobjects can be a list of MonteCarlo or MolecularDynamics
A class to implement Hamiltonian Replica Exchange.
Maintains temperature during molecular dynamics.
Sample using molecular dynamics.
def get_nuisance_movers_parameters
Return a dictionary with the mover parameters for nuisance parameters.
Modify the transformation of a rigid body.
Simple conjugate gradients optimizer.
Sample using conjugate gradients.
Move continuous particle variables by perturbing them within a ball.
Modify a surface orientation.
Object used to hold a set of restraints.
Simple molecular dynamics optimizer.
def deprecated_method
Python decorator to mark a method as deprecated.
Code that uses the MPI parallel library.
A mover that perturbs a Weight particle.
def __init__
Setup Monte Carlo sampling.
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.
Sample using Monte Carlo.
The general base class for IMP exceptions.
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.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
Sample using replica exchange.
Inferential scoring building on methods developed as part of the Inferential Structure Determination ...