1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
use crate::sampling::MetropolisState; /// # Create a markov chain by doing markov steps pub trait MarkovChain<S, Res> { /// * undo a markov step, return result-state /// * if you want to undo more than one step /// see [`undo_steps`](#method.undo_steps) fn undo_step(&mut self, step: S) -> Res; /// * undo a markov, **panic** on invalid result state /// * for undoing multiple steps see [`undo_steps_quiet`](#method.undo_steps_quiet) fn undo_step_quiet(&mut self, step: S); /// # Markov step /// * use this to perform a markov step step /// * for doing multiple markov steps at once, use [`m_steps`](#method.m_steps) fn m_step(&mut self) -> S; /// # Markov steps /// * use this to perform multiple markov steps at once /// * result `Vec<S>` can be used to undo the steps with `self.undo_steps(result)` fn m_steps(&mut self, count: usize) -> Vec<S> { let mut vec = Vec::with_capacity(count); for _ in 0..count { vec.push( self.m_step() ); } vec } /// # Undo markov steps /// * Note: uses undo_step in correct order and returns result /// ## Important: /// * look at specific implementation of `undo_step`, every thing mentioned there applies to each step fn undo_steps(&mut self, steps: Vec<S>) -> Vec<Res> { steps.into_iter() .rev() .map(|step| self.undo_step(step)) .collect() } /// # Undo markov steps /// * Note: uses `undo_step_quiet` in correct order /// ## Important: /// * look at specific implementation of `undo_step_quiet`, every thing mentioned there applies to each step fn undo_steps_quiet(&mut self, steps: Vec<S>) { let iter = steps.into_iter() .rev(); for step in iter { self.undo_step_quiet(step); } } } /// Use the metropolis algorithm pub trait Metropolis<S, Res>: MarkovChain<S, Res> { /// # Metropolis algorithm /// **panics**: `stepsize = 0` is not allowed and will result in a panic /// /// | | meaning | /// |---------------|------------------------------------------------------------------------------| /// | `rng` | the Rng used to decide, if a state should be accepted or rejected | /// | `temperature` | used in metropolis probability | /// | `stepsize` | is used for each markov step, i.e., `self.m_steps(stepsize)` is called | /// | `steps` | is the number of steps with size `stepsize`, that this method should perform | /// | `valid_self` | checks, if the markov steps produced a valid state | /// | `energy` | should calculate the "energy" of the system used for acceptance probability | /// | `measure` | called after each step | /// /// **Important**: if possible, treat `energy(&mut Self)` as `energy(&Self)`. This will be safer. /// /// **Note**: instead of the `temperature` T the literature sometimes uses β. The relation between them is: /// β = T⁻¹ /// /// **Note**: If `valid_self` returns `false`, the state will be rejected. If you do not need this, /// use `|_| true` /// /// **`measure`**: function is intended for storing measurable quantities etc. /// Is called at the end of each iteration. As for the parameter: /// /// | type | name suggestion | description | /// |-------------|------------------|----------------------------------------------------------------------------------------------------------------------------------------------| /// | `&mut Self` | `current_state` | current `self`. After stepping and accepting/rejecting | /// | `usize` | `i` | counter, starts at 0, each step counter increments by 1 | /// | `f64` | `current_energy` | `energy(&mut self)`. Assumes that `energy` of a state deterministic and invariant under: `let steps = self.steps(n); self.undo_steps(steps);`| /// | `bool` | `rejected` | `true` if last step was rejected. That should mean, that the current state is the same as the last state. | /// /// Citation see, e.g, /// > M. E. J. Newman and G. T. Barkema, "Monte Carlo Methods in Statistical Physics" /// *Clarendon Press*, 1999, ISBN: 978-0-19-8517979 /// /// # Explanation /// * Performes markov chain using the markov chain trait /// /// Let the current state of the system be S(i) with corresponding energy `E(i) = energy(S(i))`. /// Now perform a markov step, such that the new system is Snew with energy Enew. /// The new state will be accepted (meaning S(i+1) = Snew) with probability: /// `min[1.0, exp{-1/T * (Enew - E(i))}]` /// otherwise the new state will be rejected, meaning S(i + 1) = S(i). /// Afterwards, `measure` is called. #[allow(clippy::clippy::too_many_arguments)] fn metropolis<Rng, F, G, H>( &mut self, rng: Rng, temperature: f64, stepsize: usize, steps: usize, valid_self: F, energy: G, measure: H, ) -> MetropolisState<Rng> where F: FnMut(&mut Self) -> bool, G: FnMut(&mut Self) -> f64, H: FnMut(&mut Self, usize, f64, bool), Rng: rand::Rng { self.metropolis_while( rng, temperature, stepsize, steps, valid_self, energy, measure, |_, _| false ) } /// same as `metropolis`, but checks function `break_if(current_state, counter)` after each step and /// stops if `true` is returned. #[allow(clippy::clippy::too_many_arguments)] fn metropolis_while<Rng, F, G, H, B>( &mut self, mut rng: Rng, temperature: f64, stepsize: usize, steps: usize, mut valid_self: F, mut energy: G, mut measure: H, mut brake_if: B, ) -> MetropolisState<Rng> where F: FnMut(&mut Self) -> bool, G: FnMut(&mut Self) -> f64, H: FnMut(&mut Self, usize, f64, bool), B: FnMut(&Self, usize) -> bool, Rng: rand::Rng { assert!( stepsize > 0, "StepSize 0 is not allowed!" ); let mut old_energy = energy(self); let mut current_energy = old_energy; let mut last_steps: Vec<_>; let mut a_prob: f64; let m_beta = -1.0 / temperature; for i in 0..steps { last_steps = self.m_steps(stepsize); // calculate acceptance probability let mut rejected = !valid_self(self); if !rejected { current_energy = energy(self); // I only have to calculate this for a valid state a_prob = 1.0_f64.min((m_beta * (current_energy - old_energy)).exp()); rejected = rng.gen::<f64>() > a_prob; } // if step is NOT accepted if rejected { self.undo_steps_quiet(last_steps); current_energy = old_energy; } else { old_energy = current_energy; } measure(self, i, current_energy, rejected); #[cold] if brake_if(self, i) { return MetropolisState::new(stepsize, steps, m_beta, rng, current_energy, i + 1); } } MetropolisState::new(stepsize, steps, m_beta, rng, current_energy, steps) } /// # resume the metropolis /// continues metropolis_while from a specific state. /// /// Note: this is intended to be used after loading a savestate, e.g., from a file. /// You have to store both the MetropolisState and the ensemble /// /// * asserts, that the `energy(self)` matches the energy stored in `state`. Can be turned of /// with `ignore_energy_missmatch = true` /// /// # Example: /// ``` /// use net_ensembles::sampling::{MetropolisSave, MetropolisState}; /// use net_ensembles::sampling::traits::{Metropolis, SimpleSample}; /// use net_ensembles::{ErEnsembleC, EmptyNode}; /// use net_ensembles::traits::MeasurableGraphQuantities; /// // as an alternative to the above, you can use the import from the next line /// // use net_ensembles::{*, sampling::*}; /// /// use net_ensembles::rand::SeedableRng; // reexported /// use rand_pcg::Pcg64; /// use serde_json; /// use std::fs::File; /// /// // first init an ensemble, which implements MarkovChain /// let rng = Pcg64::seed_from_u64(7567526); /// let mut ensemble = ErEnsembleC::<EmptyNode, _>::new(300, 4.0, rng); /// /// // ensure that inital state is valid /// while !ensemble.is_connected().unwrap() { /// ensemble.randomize(); /// } /// /// // now perform metropolis /// // in this example the simulation will be interrupted, when the counter hits 20: /// // break_if = |_, counter| counter == 20 /// let metropolis_rng = Pcg64::seed_from_u64(77526); /// let state = ensemble.metropolis_while( /// metropolis_rng, // rng /// -10.0, // temperature /// 30, // stepsize /// 100, // steps /// |ensemble| ensemble.is_connected().unwrap(), // valid_self /// |ensemble| ensemble.diameter().unwrap() as f64, // energy /// |ensemble, counter, energy, rejected| { // measure /// // of cause, you can store it in a file instead /// println!("{}, {}, {}, {}", counter, rejected, energy, ensemble.leaf_count()); /// }, /// |_, counter| counter == 20, // break_if /// ); /// /// // NOTE: You will likely not need the cfg part /// // I only need it, because the example has to work with and without serde_support /// #[cfg(feature = "serde_support")] /// { /// // saving /// let save_file = File::create("metropolis.save") /// .expect("Unable to create file"); /// /// let save = MetropolisSave::new(ensemble, state); /// serde_json::to_writer_pretty(save_file, &save) /// .unwrap(); /// /// /// // loading /// let reader = File::open("metropolis.save") /// .expect("Unable to open file"); /// /// let save: MetropolisSave::<ErEnsembleC::<EmptyNode, Pcg64>, Pcg64> /// = serde_json::from_reader(reader).unwrap(); /// /// let (mut loaded_ensemble, loaded_state) = save.unpack(); /// /// // resume the simulation /// loaded_ensemble.continue_metropolis_while( /// loaded_state, /// false, // asserting that current energy equals stored energy /// |ensemble| ensemble.is_connected().unwrap(), // valid_self /// |ensemble| ensemble.diameter().unwrap() as f64, // energy /// |ensemble, counter, energy, rejected| { // measure /// // of cause, you could store it in a file instead /// // and you could use the `rejected` variable to only calculate other /// // quantities, if something actually changed /// println!("{}, {}, {}, {}", counter, rejected, energy, ensemble.leaf_count()); /// }, /// |_, _| false, // break_if /// ); /// } /// ``` #[allow(clippy::clippy::too_many_arguments)] fn continue_metropolis_while<Rng, F, G, H, B>( &mut self, state: MetropolisState<Rng>, ignore_energy_missmatch: bool, mut valid_self: F, mut energy: G, mut measure: H, mut brake_if: B, ) -> MetropolisState<Rng> where F: FnMut(&mut Self) -> bool, G: FnMut(&mut Self) -> f64, H: FnMut(&mut Self, usize, f64, bool), B: FnMut(&Self, usize) -> bool, Rng: rand::Rng { let mut old_energy = energy(self); if !ignore_energy_missmatch { assert_eq!( old_energy, state.current_energy(), "Energy missmatch!" ); } let mut current_energy = old_energy; let mut last_steps: Vec<_>; let mut a_prob: f64; let m_beta = state.m_beta(); let steps = state.step_target(); let stepsize = state.stepsize(); let counter = state.counter(); let mut rng = state.to_rng(); for i in counter..steps { last_steps = self.m_steps(stepsize); // calculate acceptance probability let mut rejected = !valid_self(self); if !rejected { // I only have to calculate this for a valid state current_energy = energy(self); a_prob = 1.0_f64.min((m_beta * (current_energy - old_energy)).exp()); rejected = rng.gen::<f64>() > a_prob; } // if step is NOT accepted if rejected { self.undo_steps_quiet(last_steps); current_energy = old_energy; } else { old_energy = current_energy; } measure(self, i, current_energy, rejected); #[cold] if brake_if(self, i) { return MetropolisState::new(stepsize, steps, m_beta, rng, current_energy, i + 1); } } MetropolisState::new(stepsize, steps, m_beta, rng, current_energy, steps) } /// same as `continue_metropolis_while`, but without the `brake_if` fn continue_metropolis<Rng, F, G, H>( &mut self, state: MetropolisState<Rng>, ignore_energy_missmatch: bool, valid_self: F, energy: G, measure: H, ) -> MetropolisState<Rng> where F: FnMut(&mut Self) -> bool, G: FnMut(&mut Self) -> f64, H: FnMut(&mut Self, usize, f64, bool), Rng: rand::Rng { self.continue_metropolis_while( state, ignore_energy_missmatch, valid_self, energy, measure, |_, _| false ) } } impl<S, Res, A> Metropolis<S, Res> for A where A: MarkovChain<S, Res> { } /// For easy sampling of your ensemble pub trait SimpleSample{ /// # Randomizes self according to model /// * this is intended for creation of initial sample /// * used in [`simple_sample`](#method.simple_sample) /// and [`simple_sample_vec`](#method.simple_sample_vec) fn randomize(&mut self); /// # do the following `times` times: /// 1) `f(self)` /// 2) `self.randomize()` fn simple_sample<F>(&mut self, times: usize, mut f: F) where F: FnMut(&Self) -> () { for _ in 0..times { f(self); self.randomize(); } } /// # do the following `times` times: /// 1) `res = f(self)` /// 2) `self.randomize()` /// ## res is collected into Vector fn simple_sample_vec<F, G>(&mut self, times: usize, mut f: F) -> Vec<G> where F: FnMut(&Self) -> G { let mut vec = Vec::with_capacity(times); for _ in 0..times { vec.push(f(self)); self.randomize(); } vec } }