IMP logo
IMP Reference Guide  2.17.0
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"
14 #include <IMP/Optimizer.h>
15 #include <IMP/container_macros.h>
16 #include <IMP/internal/container_helpers.h>
18 #include <IMP/Configuration.h>
19 
20 #include <boost/random/uniform_real.hpp>
21 
22 IMPCORE_BEGIN_NAMESPACE
23 
24 /** Allow code to test for the changes in MC interface.*/
25 #define IMP_CORE_HAS_MONTE_CARLO_MOVER 1
26 
27 //! A Monte Carlo optimizer.
28 /** The optimizer uses a set of Mover objects to propose steps. At
29  each sampling iteration, all Movers added to MonteCarlo are called to
30  generate a new proposed configuration.
31 
32  The movers propose some modification, which is then accepted or
33  rejected based on the Metropolis criterion. Optionally, a number
34  of local optimization steps are taken before the MonteCarlo step
35  is accepted or rejected.
36 
37  If you want to sequentially call one mover at every iteration, wrap
38  all movers into a SerialMover first, and then add the SerialMover to
39  MonteCarlo.
40 
41  By default, the lowest score state encountered is returned.
42 
43  \see Mover
44  */
45 class IMPCOREEXPORT MonteCarlo : public Optimizer {
46  public:
47  MonteCarlo(Model *m);
48 
49  protected:
50  ParticleIndexes reset_pis_;
51  virtual Float do_optimize(unsigned int max_steps) override;
53  public:
54  /** By default, the optimizer returns the lowest scoring state
55  found so far. If, instead, you wish to return the last accepted
56  state, set return best to false.
57  */
58  void set_return_best(bool tf) { return_best_ = tf; }
59 
60  //! If set true (default false), only rescore moved particles
61  /** By default, on each move the score of the entire system is
62  calculated. If it is guaranteed that only Movers and ScoreStates
63  move the system, then the score can potentially be calculated
64  more quickly by caching the scores on parts of the system that
65  don't move. This is still experimental.
66 
67  \see IMP::ScoringFunction::evaluate_moved
68 
69  \note Some MonteCarlo subclasses do local optimization after each
70  move, which can move more particles than the Movers touched.
71  In this case the guarantee does not hold and this optimization
72  should probably not be used.
73  */
74  void set_score_moved(bool mv) { score_moved_ = mv; }
75 
76  /** \name kT
77  The kT value has to be on the same scale as the differences
78  in energy between good and bad states (and so the default is
79  likely to not be a good choice).
80  @{
81  */
82  void set_kt(Float t) {
83  IMP_INTERNAL_CHECK(t >= 0, "Temperature must not be negative");
84  temp_ = t;
85  }
86  Float get_kt() const { return temp_; }
87  /** @} */
88  //! Return the energy of the last accepted state.
89  double get_last_accepted_energy() const { return last_energy_; }
90 
91  //! If return best is on, returns the best energy found so far.
92  double get_best_accepted_energy() const {
93  IMP_USAGE_CHECK(return_best_, "Getting the best energy"
94  << " requires return best being on.");
95  return best_energy_;
96  }
97  /** \name Statistics
98  @{
99  */
100  //! Return how many times the optimizer has stepped to lower score
101  unsigned int get_number_of_downward_steps() const {
102  return stat_downward_steps_taken_;
103  }
104  //! Return how many times the optimizer has stepped to higher score
105  unsigned int get_number_of_upward_steps() const {
106  return stat_upward_steps_taken_;
107  }
108  //! Get number of proposed moves
109  unsigned int get_number_of_proposed_steps() const {
110  return stat_downward_steps_taken_ + stat_upward_steps_taken_ +
111  stat_num_failures_;
112  }
113  //! Get number of accepted moves
114  unsigned int get_number_of_accepted_steps() const {
115  return stat_downward_steps_taken_ + stat_upward_steps_taken_;
116  }
117  void reset_statistics() {
118  stat_downward_steps_taken_ = 0;
119  stat_upward_steps_taken_ = 0;
120  stat_num_failures_ = 0;
121  }
122 
123  /** @} */
124 
125  //! Set the score threshold.
126  //* An optimization is terminated if the score drops below this value. */
127  void set_score_threshold(double s) { min_score_ = s; }
128 
129  //! Get the score threshold.
130  double get_score_threshold() const { return min_score_; }
131 
132  /** Computations can be accelerated by throwing out
133  the tails of the distribution of accepted moves. To
134  do this, specify a maximum acceptable difference
135  between the before and after scores.
136  */
137  void set_maximum_difference(double d) { max_difference_ = d; }
138 
139  double get_maximum_difference() const { return max_difference_; }
140  /** @name Movers
141 
142  The following methods are used to manipulate the list of Movers.
143  Each mover is called at each optimization step, giving it a chance
144  to change the current configuration.
145  @{
146  */
147  IMP_LIST_ACTION(public, Mover, Movers, mover, movers, MonteCarloMover *,
148  MonteCarloMovers, {}, {}, {});
149  /** @} */
150 
151  /** Set whether to use incremental evaluate or evaluate all restraints
152  each time. This cannot be changed during optimization.
153 
154  \deprecated_at{2.17} Use set_score_moved() instead
155  */
156  IMPCORE_DEPRECATED_METHOD_DECL(2.17)
157  void set_incremental_scoring_function(IncrementalScoringFunction *isf);
158 
159  bool get_use_incremental_scoring_function() const { return isf_; }
160 
161  IncrementalScoringFunction *get_incremental_scoring_function() const {
162  return isf_;
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 (isf_) {
200  isf_->set_moved_particles(moved);
201  }
202  if (get_maximum_difference() < NO_MAX) {
203  if (score_moved_ && !force_full_score) {
204  return get_scoring_function()->evaluate_moved_if_below(
205  false, moved, reset_pis_, last_energy_ + max_difference_);
206  } else {
207  return get_scoring_function()->evaluate_if_below(
208  false, last_energy_ + max_difference_);
209  }
210  } else {
211  if (score_moved_ && !force_full_score) {
212  return get_scoring_function()->evaluate_moved(false, moved, reset_pis_);
213  } else {
214  return get_scoring_function()->evaluate(false);
215  }
216  }
217  }
218 
219  private:
220  double temp_;
221  double last_energy_;
222  double best_energy_;
223  double max_difference_;
224  unsigned int stat_downward_steps_taken_;
225  unsigned int stat_upward_steps_taken_;
226  unsigned int stat_num_failures_;
227  bool return_best_;
228  bool score_moved_;
229  double min_score_;
231  ::boost::uniform_real<> rand_;
232 
234 };
235 
236 //! This variant of Monte Carlo that relaxes after each move
237 class IMPCOREEXPORT MonteCarloWithLocalOptimization : public MonteCarlo {
239  unsigned int num_local_;
240 
241  public:
242  MonteCarloWithLocalOptimization(Optimizer *opt, unsigned int steps);
243 
244  unsigned int get_number_of_steps() const { return num_local_; }
245 
246  Optimizer *get_local_optimizer() const { return opt_; }
247 
248  protected:
249  virtual void do_step() override;
251 };
252 
253 //! This variant of Monte Carlo uses basis hopping
254 /** Basin hopping is where, after a move, a local optimizer is used to relax
255  the model before the energy computation. However, the pre-relaxation state
256  of the model is used as the starting point for the next step. The idea
257  is that models are accepted or rejected based on the score of the nearest
258  local minima, but they can still climb the barriers in between as the model
259  is not reset to the minima after each step.
260  */
261 class IMPCOREEXPORT MonteCarloWithBasinHopping
263  public:
264  MonteCarloWithBasinHopping(Optimizer *opt, unsigned int ns);
265 
266  protected:
267  virtual void do_step() override;
269 };
270 
271 IMPCORE_END_NAMESPACE
272 
273 #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:45
unsigned int get_number_of_upward_steps() const
Return how many times the optimizer has stepped to higher score.
Definition: MonteCarlo.h:105
Score model efficiently when a small number of particles are changed.
double get_score_threshold() const
Get the score threshold.
Definition: MonteCarlo.h:130
const double NO_MAX
Use this value when you want to turn off maximum for restraint evaluation.
IMP::Vector< IMP::Pointer< MonteCarloMover > > MonteCarloMovers
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:137
#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:89
void set_score_moved(bool mv)
If set true (default false), only rescore moved particles.
Definition: MonteCarlo.h:74
Base class for all optimizers.
void set_score_threshold(double s)
Set the score threshold.
Definition: MonteCarlo.h:127
Macros to define containers of objects.
A smart pointer to a reference counted object.
Definition: Pointer.h:87
#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:73
This variant of Monte Carlo uses basis hopping.
Definition: MonteCarlo.h:261
unsigned int get_number_of_downward_steps() const
Return how many times the optimizer has stepped to lower score.
Definition: MonteCarlo.h:101
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:46
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:114
A smart pointer to a ref-counted Object that is a class member.
Definition: Pointer.h:146
This variant of Monte Carlo that relaxes after each move.
Definition: MonteCarlo.h:237
double get_best_accepted_energy() const
If return best is on, returns the best energy found so far.
Definition: MonteCarlo.h:92
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.
unsigned int get_number_of_proposed_steps() const
Get number of proposed moves.
Definition: MonteCarlo.h:109
ScoringFunction * get_scoring_function() const
Return the scoring function that is being used.
Definition: Optimizer.h:93