1 """@namespace IMP.pmi.samplers
2 Sampling of the system.
10 class _SerialReplicaExchange:
11 """Dummy replica exchange class used in non-MPI builds.
12 It should act similarly to IMP.mpi.ReplicaExchange
13 on a single processor.
18 def get_number_of_replicas(self):
21 def create_temperatures(self, tmin, tmax, nrep):
24 def get_my_index(self):
27 def set_my_parameter(self, key, val):
28 self.__params[key] = val
30 def get_my_parameter(self, key):
31 return self.__params[key]
33 def get_friend_index(self, step):
36 def get_friend_parameter(self, key, findex):
37 return self.get_my_parameter(key)
39 def do_exchange(self, myscore, fscore, findex):
42 def set_was_used(self, was_used):
43 self.was_used = was_used
47 """Sample using Monte Carlo"""
56 def __init__(self, model, objects=None, temp=1.0, filterbyname=None,
58 """Setup Monte Carlo sampling
59 @param model The IMP Model
60 @param objects What to sample (a list of Movers)
61 @param temp The MC temperature
62 @param filterbyname Not used
63 @param score_moved If True, attempt to speed up sampling by
64 caching scoring function terms on particles that didn't move
73 self.simulated_annealing =
False
74 self.selfadaptive =
False
90 self.mc.set_scoring_function(get_restraint_set(self.model))
91 self.mc.set_return_best(
False)
92 self.mc.set_score_moved(score_moved)
93 self.mc.set_kt(self.temp)
94 self.mc.add_mover(self.smv)
96 def set_kt(self, temp):
103 def set_scoring_function(self, objectlist):
105 for ob
in objectlist:
106 rs.add_restraint(ob.get_restraint())
108 self.mc.set_scoring_function(sf)
110 def set_simulated_annealing(
116 self.simulated_annealing =
True
117 self.tempmin = min_temp
118 self.tempmax = max_temp
119 self.timemin = min_temp_time
120 self.timemax = max_temp_time
122 def set_self_adaptive(self, isselfadaptive=True):
123 self.selfadaptive = isselfadaptive
127 Return a dictionary with the mover parameters for nuisance parameters
130 for i
in range(self.get_number_of_movers()):
131 mv = self.smv.get_mover(i)
133 if "Nuisances" in name:
134 stepsize = IMP.core.NormalMover.get_from(mv).get_sigma()
135 output[name] = stepsize
138 def get_number_of_movers(self):
139 return len(self.smv.get_movers())
141 def get_particle_types(self):
144 def optimize(self, nstep):
146 self.mc.optimize(nstep * self.get_number_of_movers())
149 if self.simulated_annealing:
150 self.temp = self.temp_simulated_annealing()
151 self.mc.set_kt(self.temp)
154 if self.selfadaptive:
155 for i, mv
in enumerate(self.mvs):
157 mvacc = mv.get_number_of_accepted()
158 mvprp = mv.get_number_of_proposed()
159 if mv
not in self.movers_data:
160 accept = float(mvacc) / float(mvprp)
161 self.movers_data[mv] = (mvacc, mvprp)
163 oldmvacc, oldmvprp = self.movers_data[mv]
164 accept = float(mvacc-oldmvacc) / float(mvprp-oldmvprp)
165 self.movers_data[mv] = (mvacc, mvprp)
172 stepsize = mv.get_sigma()
173 if 0.4 > accept
or accept > 0.6:
174 mv.set_sigma(stepsize * 2 * accept)
177 stepsize = mv.get_radius()
178 if 0.4 > accept
or accept > 0.6:
179 mv.set_radius(stepsize * 2 * accept)
182 mr = mv.get_maximum_rotation()
183 mt = mv.get_maximum_translation()
184 if 0.4 > accept
or accept > 0.6:
185 mv.set_maximum_rotation(mr * 2 * accept)
186 mv.set_maximum_translation(mt * 2 * accept)
189 mr = mv.get_maximum_rotation()
190 mt = mv.get_maximum_translation()
191 if 0.4 > accept
or accept > 0.6:
192 mv.set_maximum_rotation(mr * 2 * accept)
193 mv.set_maximum_translation(mt * 2 * accept)
197 if 0.4 > accept
or accept > 0.6:
198 mv.set_radius(mr * 2 * accept)
200 def get_nuisance_movers(self, nuisances, maxstep):
202 for nuisance
in nuisances:
203 print(nuisance, maxstep)
210 def get_rigid_body_movers(self, rbs, maxtrans, maxrot):
217 def get_super_rigid_body_movers(self, rbs, maxtrans, maxrot):
224 if isinstance(rb[2], tuple)
and len(rb[2]) == 3 \
225 and isinstance(rb[2][0], float) \
226 and isinstance(rb[2][1], float) \
227 and isinstance(rb[2][2], float):
234 "Setting up a super rigid body with wrong parameters")
238 srbm.add_xyz_particle(xyz)
240 srbm.add_rigid_body_particle(rb)
244 def get_floppy_body_movers(self, fbs, maxtrans):
253 fb.set_is_optimized(fk,
True)
263 def get_X_movers(self, fbs, maxtrans):
269 raise ValueError(
"particle is part of a rigid body")
275 def get_weight_movers(self, weights, maxstep):
277 for weight
in weights:
278 if weight.get_number_of_weights() > 1:
282 def get_surface_movers(self, surfaces, maxtrans, maxrot, refprob):
284 for surface
in surfaces:
289 def temp_simulated_annealing(self):
290 if self.nframe % (self.timemin + self.timemax) < self.timemin:
294 temp = self.tempmin + (self.tempmax - self.tempmin) * value
297 def set_label(self, label):
300 def get_frame_number(self):
303 def get_output(self):
305 for i, mv
in enumerate(self.smv.get_movers()):
306 mvname = mv.get_name()
307 mvacc = mv.get_number_of_accepted()
308 mvprp = mv.get_number_of_proposed()
310 mvacr = float(mvacc) / float(mvprp)
313 output[
"MonteCarlo_Acceptance_" +
314 mvname +
"_" + str(i)] = str(mvacr)
315 if "Nuisances" in mvname:
316 output[
"MonteCarlo_StepSize_" + mvname +
"_" + str(i)] = \
317 str(IMP.core.NormalMover.get_from(mv).get_sigma())
318 if "Weights" in mvname:
319 output[
"MonteCarlo_StepSize_" + mvname +
"_" + str(i)] = \
320 str(IMP.isd.WeightMover.get_from(mv).get_radius())
321 output[
"MonteCarlo_Temperature"] = str(self.mc.get_kt())
322 output[
"MonteCarlo_Nframe"] = str(self.nframe)
327 """Sample using molecular dynamics"""
329 def __init__(self, model, objects, kt, gamma=0.01, maximum_time_step=1.0,
332 @param model The IMP Model
333 @param objects What to sample. Use flat list of particles
334 @param kt Temperature
335 @param gamma Viscosity parameter
336 @param maximum_time_step MD max time step
343 psamp = obj.get_particles_to_sample()
344 to_sample = psamp[
'Floppy_Bodies_SimplifiedModel'][0]
349 self.model, to_sample, kt/0.0019872041, gamma)
351 self.md.set_maximum_time_step(maximum_time_step)
353 self.md.set_scoring_function(sf)
355 self.md.set_scoring_function(get_restraint_set(self.model))
356 self.md.add_optimizer_state(self.ltstate)
357 self.simulated_annealing =
False
360 def set_kt(self, kt):
361 temp = kt/0.0019872041
362 self.ltstate.set_temperature(temp)
363 self.md.assign_velocities(temp)
365 def set_simulated_annealing(self, min_temp, max_temp, min_temp_time,
367 self.simulated_annealing =
True
368 self.tempmin = min_temp
369 self.tempmax = max_temp
370 self.timemin = min_temp_time
371 self.timemax = max_temp_time
373 def temp_simulated_annealing(self):
374 if self.nframe % (self.timemin + self.timemax) < self.timemin:
378 temp = self.tempmin + (self.tempmax - self.tempmin) * value
381 def set_gamma(self, gamma):
382 self.ltstate.set_gamma(gamma)
384 def optimize(self, nsteps):
387 if self.simulated_annealing:
388 self.temp = self.temp_simulated_annealing()
389 self.set_kt(self.temp)
390 self.md.optimize(nsteps)
392 def get_output(self):
394 output[
"MolecularDynamics_KineticEnergy"] = \
395 str(self.md.get_kinetic_energy())
400 """Sample using conjugate gradients"""
402 def __init__(self, model, objects):
406 self.cg.set_scoring_function(get_restraint_set(self.model))
408 def set_label(self, label):
411 def get_frame_number(self):
414 def optimize(self, nstep):
416 self.cg.optimize(nstep)
418 def set_scoring_function(self, objectlist):
420 for ob
in objectlist:
421 rs.add_restraint(ob.get_restraint())
423 self.cg.set_scoring_function(sf)
425 def get_output(self):
427 output[
"ConjugatedGradients_Nframe"] = str(self.nframe)
432 """Sample using replica exchange"""
434 def __init__(self, model, tempmin, tempmax, samplerobjects, test=True,
435 replica_exchange_object=
None):
437 samplerobjects can be a list of MonteCarlo or MolecularDynamics
441 self.samplerobjects = samplerobjects
443 self.TEMPMIN_ = tempmin
444 self.TEMPMAX_ = tempmax
446 if replica_exchange_object
is None:
450 print(
'ReplicaExchange: MPI was found. '
451 'Using Parallel Replica Exchange')
454 print(
'ReplicaExchange: Could not find MPI. '
455 'Using Serial Replica Exchange')
456 self.rem = _SerialReplicaExchange()
460 print(
'got existing rex object')
461 self.rem = replica_exchange_object
464 nproc = self.rem.get_number_of_replicas()
466 if nproc % 2 != 0
and not test:
468 "number of replicas has to be even. "
469 "set test=True to run with odd number of replicas.")
471 temp = self.rem.create_temperatures(
476 self.temperatures = temp
478 myindex = self.rem.get_my_index()
480 self.rem.set_my_parameter(
"temp", [self.temperatures[myindex]])
481 for so
in self.samplerobjects:
482 so.set_kt(self.temperatures[myindex])
488 def get_temperatures(self):
489 return self.temperatures
491 def get_my_temp(self):
492 return self.rem.get_my_parameter(
"temp")[0]
494 def get_my_index(self):
495 return self.rem.get_my_index()
497 def swap_temp(self, nframe, score=None):
499 score = self.model.evaluate(
False)
501 _ = self.rem.get_my_index()
502 mytemp = self.rem.get_my_parameter(
"temp")[0]
504 if mytemp == self.TEMPMIN_:
507 if mytemp == self.TEMPMAX_:
511 myscore = score / mytemp
514 findex = self.rem.get_friend_index(nframe)
515 ftemp = self.rem.get_friend_parameter(
"temp", findex)[0]
517 fscore = score / ftemp
520 flag = self.rem.do_exchange(myscore, fscore, findex)
525 for so
in self.samplerobjects:
529 def get_output(self):
531 if self.nattempts != 0:
532 output[
"ReplicaExchange_SwapSuccessRatio"] = str(
533 float(self.nsuccess) / self.nattempts)
534 output[
"ReplicaExchange_MinTempFrequency"] = str(
535 float(self.nmintemp) / self.nattempts)
536 output[
"ReplicaExchange_MaxTempFrequency"] = str(
537 float(self.nmaxtemp) / self.nattempts)
539 output[
"ReplicaExchange_SwapSuccessRatio"] = str(0)
540 output[
"ReplicaExchange_MinTempFrequency"] = str(0)
541 output[
"ReplicaExchange_MaxTempFrequency"] = str(0)
542 output[
"ReplicaExchange_CurrentTemp"] = str(self.get_my_temp())
547 def __init__(self, replica_exchange_object=None):
548 """Query values (ie score, and others)
549 from a set of parallel jobs"""
551 if replica_exchange_object
is None:
555 print(
'MPI_values: MPI was found. '
556 'Using Parallel Replica Exchange')
559 print(
'MPI_values: Could not find MPI. '
560 'Using Serial Replica Exchange')
561 self.rem = _SerialReplicaExchange()
565 print(
'got existing rex object')
566 self.rem = replica_exchange_object
568 def set_value(self, name, value):
569 self.rem.set_my_parameter(name, [value])
571 def get_values(self, name):
573 for i
in range(self.rem.get_number_of_replicas()):
574 v = self.rem.get_friend_parameter(name, i)[0]
578 def get_percentile(self, name):
579 value = self.rem.get_my_parameter(name)[0]
580 values = sorted(self.get_values(name))
581 ind = values.index(value)
582 percentile = float(ind)/len(values)
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.
Create a scoring function on a list of restraints.
Move continuous particle variables by perturbing them within a ball.
Modify a surface orientation.
static FloatKeys get_internal_coordinate_keys()
Object used to hold a set of restraints.
Simple molecular dynamics simulator.
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 ...