IMP logo
IMP Reference Guide  develop.02fce3ae61,2026/01/08
The Integrative Modeling Platform
MonteCarlo.h
Go to the documentation of this file.
1 /**
2  * \file IMP/core/MonteCarlo.h \brief Simple Monte Carlo optimizer.
3  *
4  * Copyright 2007-2022 IMP Inventors. All rights reserved.
5  *
6  */
7 
8 #ifndef IMPCORE_MONTE_CARLO_H
9 #define IMPCORE_MONTE_CARLO_H
10 
11 #include <IMP/core/core_config.h>
12 #include "MonteCarloMover.h"
13 #include <IMP/Optimizer.h>
14 #include <IMP/container_macros.h>
15 #include <IMP/internal/container_helpers.h>
17 #include <IMP/Configuration.h>
18 
19 #include <boost/random/uniform_real_distribution.hpp>
20 
21 IMPCORE_BEGIN_NAMESPACE
22 
23 /** Allow code to test for the changes in MC interface.*/
24 #define IMP_CORE_HAS_MONTE_CARLO_MOVER 1
25 
26 //! A Monte Carlo optimizer.
27 /** The optimizer uses a set of Mover objects to propose steps. At
28  each sampling iteration, all Movers added to MonteCarlo are called to
29  generate a new proposed configuration.
30 
31  The movers propose some modification, which is then accepted or
32  rejected based on the Metropolis criterion. Optionally, a number
33  of local optimization steps are taken before the MonteCarlo step
34  is accepted or rejected.
35 
36  If you want to sequentially call one mover at every iteration, wrap
37  all movers into a SerialMover first, and then add the SerialMover to
38  MonteCarlo.
39 
40  By default, the lowest score state encountered is returned.
41 
42  \see Mover
43  */
44 class IMPCOREEXPORT MonteCarlo : public Optimizer {
45  public:
46  MonteCarlo(Model *m);
47 
48  protected:
49  ParticleIndexes reset_pis_;
50  virtual Float do_optimize(unsigned int max_steps) override;
52  public:
53  /** By default, the optimizer returns the lowest scoring state
54  found so far. If, instead, you wish to return the last accepted
55  state, set return best to false.
56  */
57  void set_return_best(bool tf) { return_best_ = tf; }
58 
59  bool get_return_best() const { return return_best_; }
60 
61  //! If set true (default false), only rescore moved particles
62  /** By default, on each move the score of the entire system is
63  calculated. If it is guaranteed that only Movers and ScoreStates
64  move the system, then the score can potentially be calculated
65  more quickly by caching the scores on parts of the system that
66  don't move. This is still experimental.
67 
68  \see IMP::ScoringFunction::evaluate_moved
69 
70  \note Some MonteCarlo subclasses do local optimization after each
71  move, which can move more particles than the Movers touched.
72  In this case the guarantee does not hold and this optimization
73  should probably not be used.
74  */
75  void set_score_moved(bool mv) { score_moved_ = mv; }
76 
77  /** \name kT
78  The kT value has to be on the same scale as the differences
79  in energy between good and bad states (and so the default is
80  likely to not be a good choice).
81  @{
82  */
83  void set_kt(Float t) {
84  IMP_INTERNAL_CHECK(t >= 0, "Temperature must not be negative");
85  temp_ = t;
86  }
87  Float get_kt() const { return temp_; }
88  /** @} */
89  //! Return the energy of the last accepted state.
90  double get_last_accepted_energy() const { return last_energy_; }
91 
92  void set_last_accepted_energy(double energy) { last_energy_ = energy; }
93 
94  //! If return best is on, returns the best energy found so far.
95  double get_best_accepted_energy() const {
96  IMP_USAGE_CHECK(return_best_, "Getting the best energy"
97  << " requires return best being on.");
98  return best_energy_;
99  }
100  void set_best_accepted_energy(double energy) { best_energy_ = energy; }
101 
102  /** \name Statistics
103  @{
104  */
105  //! Return how many times the optimizer has stepped to lower score
106  unsigned int get_number_of_downward_steps() const {
107  return stat_downward_steps_taken_;
108  }
109  //! Return how many times the optimizer has stepped to higher score
110  unsigned int get_number_of_upward_steps() const {
111  return stat_upward_steps_taken_;
112  }
113  //! Get number of proposed moves
114  unsigned int get_number_of_proposed_steps() const {
115  return stat_downward_steps_taken_ + stat_upward_steps_taken_ +
116  stat_num_failures_;
117  }
118  //! Get number of accepted moves
119  unsigned int get_number_of_accepted_steps() const {
120  return stat_downward_steps_taken_ + stat_upward_steps_taken_;
121  }
122  void set_number_of_downward_steps(unsigned int nsteps) {
123  stat_downward_steps_taken_ = nsteps;
124  }
125  void set_number_of_upward_steps(unsigned int nsteps) {
126  stat_upward_steps_taken_ = nsteps;
127  }
128  void set_number_of_rejected_steps(unsigned int nsteps) {
129  stat_num_failures_ = nsteps;
130  }
131  void reset_statistics() {
132  stat_downward_steps_taken_ = 0;
133  stat_upward_steps_taken_ = 0;
134  stat_num_failures_ = 0;
135  }
136 
137  /** @} */
138 
139  //! Set the score threshold.
140  //* An optimization is terminated if the score drops below this value. */
141  void set_score_threshold(double s) { min_score_ = s; }
142 
143  //! Get the score threshold.
144  double get_score_threshold() const { return min_score_; }
145 
146  /** Computations can be accelerated by throwing out
147  the tails of the distribution of accepted moves. To
148  do this, specify a maximum acceptable difference
149  between the before and after scores.
150  */
151  void set_maximum_difference(double d) { max_difference_ = d; }
152 
153  double get_maximum_difference() const { return max_difference_; }
154  /** @name Movers
155 
156  The following methods are used to manipulate the list of Movers.
157  Each mover is called at each optimization step, giving it a chance
158  to change the current configuration.
159  @{
160  */
161  IMP_LIST_ACTION(public, Mover, Movers, mover, movers, MonteCarloMover *,
162  MonteCarloMovers, {}, {}, {});
163  /** @} */
164 
165  protected:
166  /** Get all movable particles (those that can be moved by the current
167  movers.*/
168  ParticleIndexes get_movable_particles() const;
169  /** Note that if return best is true, this will save the current
170  state of the model. Also, if the move is accepted, the
171  optimizer states will be updated.
172  */
173  bool do_accept_or_reject_move(double score, double last,
174  const MonteCarloMoverResult &moved);
175 
176  bool do_accept_or_reject_move(double score,
177  const MonteCarloMoverResult &moved) {
178  return do_accept_or_reject_move(score, get_last_accepted_energy(), moved);
179  }
180 
181  MonteCarloMoverResult do_move();
182  //! a class that inherits from this should override this method
183  virtual void do_step();
184  //! Get the current energy
185  /** By default it just calls
186  Optimizer::get_scoring_function()->evaluate(false). However,
187  if an incremental scoring function is used, the list of moved
188  particles will be used to evaluate the score more efficiently.
189  Also, if there is a maximum allowed difference in scores
190  Optimizer::get_scoring_function()->evaluate_if_below()
191  will be called instead, allowing more efficient evaluation.
192  Classes which override this method should be similarly aware for
193  efficiency.
194 
195  The list of moved particles is passed.
196  */
197  virtual double do_evaluate(const ParticleIndexes &moved,
198  bool force_full_score) const {
199  if (get_maximum_difference() < NO_MAX) {
200  if (score_moved_ && !force_full_score) {
201  return get_scoring_function()->evaluate_moved_if_below(
202  false, moved, reset_pis_, last_energy_ + max_difference_);
203  } else {
204  return get_scoring_function()->evaluate_if_below(
205  false, last_energy_ + max_difference_);
206  }
207  } else {
208  if (score_moved_ && !force_full_score) {
209  return get_scoring_function()->evaluate_moved(false, moved, reset_pis_);
210  } else {
211  return get_scoring_function()->evaluate(false);
212  }
213  }
214  }
215 
216  private:
217  double temp_;
218  double last_energy_;
219  double best_energy_;
220  double max_difference_;
221  unsigned int stat_downward_steps_taken_;
222  unsigned int stat_upward_steps_taken_;
223  unsigned int stat_num_failures_;
224  bool return_best_;
225  bool score_moved_;
226  double min_score_;
228  ::boost::random::uniform_real_distribution<> rand_;
229 };
230 
231 //! This variant of Monte Carlo that relaxes after each move
232 class IMPCOREEXPORT MonteCarloWithLocalOptimization : public MonteCarlo {
234  unsigned int num_local_;
235 
236  public:
237  MonteCarloWithLocalOptimization(Optimizer *opt, unsigned int steps);
238 
239  unsigned int get_number_of_steps() const { return num_local_; }
240 
241  Optimizer *get_local_optimizer() const { return opt_; }
242 
243  protected:
244  virtual void do_step() override;
246 };
247 
248 //! This variant of Monte Carlo uses basis hopping
249 /** Basin hopping is where, after a move, a local optimizer is used to relax
250  the model before the energy computation. However, the pre-relaxation state
251  of the model is used as the starting point for the next step. The idea
252  is that models are accepted or rejected based on the score of the nearest
253  local minima, but they can still climb the barriers in between as the model
254  is not reset to the minima after each step.
255  */
256 class IMPCOREEXPORT MonteCarloWithBasinHopping
258  public:
259  MonteCarloWithBasinHopping(Optimizer *opt, unsigned int ns);
260 
261  protected:
262  virtual void do_step() override;
264 };
265 
266 IMPCORE_END_NAMESPACE
267 
268 #endif /* IMPCORE_MONTE_CARLO_H */
double get_kt(double T)
Return kT for a given temperature in units of [kcal/mol].
A Monte Carlo optimizer.
Definition: MonteCarlo.h:44
unsigned int get_number_of_upward_steps() const
Return how many times the optimizer has stepped to higher score.
Definition: MonteCarlo.h:110
double get_score_threshold() const
Get the score threshold.
Definition: MonteCarlo.h:144
const double NO_MAX
Use this value when you want to turn off maximum for restraint evaluation.
virtual double do_evaluate(const ParticleIndexes &moved, bool force_full_score) const
Get the current energy.
Definition: MonteCarlo.h:197
void set_maximum_difference(double d)
Definition: MonteCarlo.h:151
#define IMP_OBJECT_METHODS(Name)
Define the basic things needed by any Object.
Definition: object_macros.h:25
double get_last_accepted_energy() const
Return the energy of the last accepted state.
Definition: MonteCarlo.h:90
void set_score_moved(bool mv)
If set true (default false), only rescore moved particles.
Definition: MonteCarlo.h:75
Base class for all optimizers.
void set_score_threshold(double s)
Set the score threshold.
Definition: MonteCarlo.h:141
Macros to define containers of objects.
#define IMP_INTERNAL_CHECK(expr, message)
An assertion to check for internal errors in IMP. An IMP::ErrorException will be thrown.
Definition: check_macros.h:139
virtual void do_step()
a class that inherits from this should override this method
Class for storing model, its restraints, constraints, and particles.
Definition: Model.h:86
This variant of Monte Carlo uses basis hopping.
Definition: MonteCarlo.h:256
unsigned int get_number_of_downward_steps() const
Return how many times the optimizer has stepped to lower score.
Definition: MonteCarlo.h:106
virtual double do_optimize(unsigned int ns)=0
override this function to do actual optimization
virtual void do_step() override
a class that inherits from this should override this method
Base class for all optimizers.
Definition: Optimizer.h:48
The base class for movers for Monte Carlo optimization.
unsigned int get_number_of_accepted_steps() const
Get number of accepted moves.
Definition: MonteCarlo.h:119
A smart pointer to a ref-counted Object that is a class member.
Definition: Pointer.h:143
This variant of Monte Carlo that relaxes after each move.
Definition: MonteCarlo.h:232
double get_best_accepted_energy() const
If return best is on, returns the best energy found so far.
Definition: MonteCarlo.h:95
double evaluate_moved(bool derivatives, const ParticleIndexes &moved_pis, const ParticleIndexes &reset_pis)
Score when some particles have moved.
double Float
Basic floating-point value (could be float, double...)
Definition: types.h:19
#define IMP_USAGE_CHECK(expr, message)
A runtime test for incorrect usage of a class or method.
Definition: check_macros.h:168
Store a set of configurations of the model.
Functions to search over vectors.
double evaluate(bool derivatives)
Evaluate and return the score for the current state of the model.
unsigned int get_number_of_proposed_steps() const
Get number of proposed moves.
Definition: MonteCarlo.h:114
ScoringFunction * get_scoring_function() const
Return the scoring function that is being used.
Definition: Optimizer.h:106