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 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
use{
crate::{*, rewl::*},
rand::{Rng, SeedableRng, Error},
rayon::prelude::*,
std::{
marker::PhantomData,
num::NonZeroUsize,
sync::*
}
};
#[cfg(feature = "serde_support")]
use serde::{Serialize, Deserialize};
/// # Use this to create a replica exchange wang landau simulation
/// * Tipp: Use shorthand `RewlBuilder`
/// ## Notes
/// * Don't be intimidated by the number of trait bounds an generic parameters.
/// You should very rarely have to explicitly write the types, as Rust will infer them for you.
#[derive(Debug,Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct ReplicaExchangeWangLandauBuilder<Ensemble, Hist, S, Res>
{
walker_per_interval: NonZeroUsize,
ensembles: Vec<Ensemble>,
hists: Vec<Hist>,
finished: Vec<bool>,
log_f_threshold: f64,
sweep_size: Vec<NonZeroUsize>,
step_size: Vec<usize>,
res: PhantomData<Res>,
s: PhantomData<S>
}
/// # Short for `ReplicaExchangeWangLandauBuilder`
pub type RewlBuilder<Ensemble, Hist, S, Res> = ReplicaExchangeWangLandauBuilder<Ensemble, Hist, S, Res>;
/// # Errors
/// that can arise during the construction of RewlBuilder
#[derive(Debug)]
pub enum RewlBuilderErr{
/// * The threshold for `log_f` needs to be a normal number.
/// * That basically means: the number is neither zero, infinite, subnormal, or NaN.
/// For more info, see the [Documentation](`std::primitive::f64::is_normal`)
NonNormalThreshold,
/// log_f_threshold must not be negative
Negative,
/// Histogram vector needs to contain at least one entry.
Empty,
/// Each histogram needs to have **at least** two bins. Though more than two bins are
/// strongly recommended
HistBinCount,
/// Unable to seed random number generator
SeedError(Error),
/// Length of histogram vector and ensemble vector has to be the same!
LenMissmatch
}
impl<Ensemble, Hist, S, Res> RewlBuilder<Ensemble, Hist, S, Res>
where Hist: Histogram,
Ensemble: MarkovChain<S, Res> + Sized + Sync + Send + Clone,
Hist: Sized + Sync + Send + Clone,
S: Send + Sync,
Res: Sync + Send
{
/// # Fraction of finished intervals
/// * which fraction of the intervals has found valid starting configurations?
/// ## Note
/// * even if every interval has a valid configuration directly after using one of
/// the `from_…` methods, it fill show a fraction of 0.0 - the fraction
/// will only be correct after calling one of the `…build` methods (on the Error of the result)
pub fn finished_fraction(&self) -> f64
{
let done = self.finished
.iter()
.filter(|&&f| f)
.count();
done as f64 / self.finished.len() as f64
}
/// # Is the interval in a valid starting configuration?
/// Check which intervals have valid starting points
/// ## Note
/// * in the beginning the RewlBuilder has no way of knowing, if the intervals have
/// valid starting configuration - as it does not know the energy function yet.
/// Therefore this will only be correct after calling one of the `…build` methods
/// (on the Error of the result)
pub fn finished_slice(&self) -> &[bool]
{
&self.finished
}
/// # Read access to histograms
pub fn hists(&self) -> &[Hist]
{
&self.hists
}
/// # Read access to the ensembles
pub fn ensembles(&self) -> &[Ensemble]
{
&self.ensembles
}
/// Access step sizes of individual intervals
pub fn step_sizes(&self) -> &[usize]
{
&self.step_size
}
/// # Change step size of individual intervals
/// * change step size of intervals
pub fn step_sizes_mut(&mut self) -> &mut [usize]
{
&mut self.step_size
}
/// Accesss sweep size of individual intervals
pub fn sweep_sizes(&self) -> &[NonZeroUsize]
{
&self.sweep_size
}
/// # Change sweep size of individual intervals
/// * change sweep size of intervals
pub fn sweep_sizes_mut(&mut self) -> &mut [NonZeroUsize]
{
&mut self.sweep_size
}
/// # new rewl builder
/// * used to create a **R**eplica **e**xchange **w**ang **l**andau simulation.
/// * use this method, if you want to have fine control over each walker, i.e., if you can
/// provide ensembles, who's energy is already inside the corresponding intervals `hists`
/// * you might want to use [from_ensemble](crate::ReplicaExchangeWangLandauBuilder::from_ensemble) or
/// [from_ensemble_tuple](crate::ReplicaExchangeWangLandauBuilder::from_ensemble_tuple) instead
///
/// | Parameter | meaning |
/// |-----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|
/// | `ensembles` | a vector of ensembles, one for each interval. Corresponds to the `hists` entries. |
/// | `hists` | Overlapping intervals for the wang landau walkers. Should be sorted according to their respective left bins. |
/// | `step_size` | step_size for the markov steps, which will be performed |
/// | `sweep_size` | How many steps will be performed until the replica exchanges are proposed |
/// | `walker_per_interval` | How many walkers should be used for each interval (entry of `hists`) |
/// | `log_f_threshold` | Threshold for the logarithm of the factor f (see paper). Rewl Simulation is finished, when all(!) walkers have a factor log_f smaller than this threshold |
///
/// ## Notes
/// * for proper statistics, you should seed the random number generators (used for the markov chain) of all ensembles
/// differently!
/// * `log_f_threshold` has to be a [normal](`std::primitive::f64::is_normal`) and non negative number
/// * each entry of `ensembles` will be cloned `walker_per_interval - 1` times and their respective rngs will be
/// seeded via the `HasRng` trait
pub fn from_ensemble_vec(
ensembles: Vec<Ensemble>,
hists: Vec<Hist>,
step_size: usize,
sweep_size: NonZeroUsize,
walker_per_interval: NonZeroUsize,
log_f_threshold: f64
) -> Result<Self, RewlBuilderErr>
{
if !log_f_threshold.is_normal(){
return Err(RewlBuilderErr::NonNormalThreshold);
}
if log_f_threshold < 0.0 {
return Err(RewlBuilderErr::Negative);
}
if hists.is_empty()
{
return Err(RewlBuilderErr::Empty);
}
if hists.len() != ensembles.len()
{
return Err(RewlBuilderErr::LenMissmatch);
}
if hists.iter().any(|v| v.bin_count() < 2)
{
return Err(RewlBuilderErr::HistBinCount);
}
let step_size = (0..ensembles.len())
.map(|_| step_size)
.collect();
let mut sweep_size_vec = Vec::with_capacity(ensembles.len());
sweep_size_vec.extend(
(0..ensembles.len())
.map(|_| sweep_size)
);
let finished = vec![false; hists.len()];
Ok(
Self{
ensembles,
step_size,
sweep_size: sweep_size_vec,
walker_per_interval,
hists,
log_f_threshold,
s: PhantomData::<S>,
res: PhantomData::<Res>,
finished
}
)
}
/// # Create a builder to create a replica exchange wang landau (Rewl) simulation
/// * creates vector of ensembles and (re)seeds their respective rngs (by using the `HasRng` trait)
/// * calls [`Self::from_ensemble_vec(…)`](`crate::ReplicaExchangeWangLandauBuilder::from_ensemble_vec`) afterwards,
/// look there for more information about the parameter
pub fn from_ensemble<R>(
ensemble: Ensemble,
hists: Vec<Hist>,
step_size: usize,
sweep_size: NonZeroUsize,
walker_per_interval: NonZeroUsize,
log_f_threshold: f64,
) -> Result<Self,RewlBuilderErr>
where Ensemble: HasRng<R> + Clone,
R: Rng + SeedableRng
{
let len = NonZeroUsize::new(hists.len())
.ok_or(RewlBuilderErr::Empty)?;
let ensembles = Self::clone_and_seed_ensembles(ensemble, len)?;
Self::from_ensemble_vec(ensembles, hists, step_size, sweep_size, walker_per_interval, log_f_threshold)
}
fn clone_and_seed_ensembles<R>(mut ensemble: Ensemble, size: NonZeroUsize) -> Result<Vec<Ensemble>, RewlBuilderErr>
where Ensemble: Clone + HasRng<R>,
R: SeedableRng + Rng
{
let mut ensembles = (1..size.get())
.map(|_| {
let mut e = ensemble.clone();
let mut rng = R::from_rng(ensemble.rng())?;
e.swap_rng(&mut rng);
Ok(e)
})
.collect::<Result<Vec<_>,Error>>()
.map_err(RewlBuilderErr::SeedError)?;
ensembles.push(ensemble);
Ok(ensembles)
}
/// # Create a builder to create a replica exchange wang landau (Rewl) simulation
/// * creates vector of ensembles and (re)seeds their respective rngs (by using the `HasRng` trait).
/// The vector is created by cloning `ensemble_tuple.0` for everything up to the middle of the vector and
/// `ensemble_tuple.1` for the rest. The length of the vector will be the same as `hists.len()`.
/// If It is an uneven number, the middle element will be a clone of `ensemble_tuple.1`
/// * calls [`Self::from_ensemble_vec(…)`](`crate::ReplicaExchangeWangLandauBuilder::from_ensemble_vec`) afterwards,
/// look there for more information about the parameter
/// * use this, if you know configurations, that would be good starting points for finding
/// configurations at either end of the intervals.
pub fn from_ensemble_tuple<R>(
ensemble_tuple: (Ensemble, Ensemble),
hists: Vec<Hist>,
step_size: usize,
sweep_size: NonZeroUsize,
walker_per_interval: NonZeroUsize,
log_f_threshold: f64,
) -> Result<Self,RewlBuilderErr>
where Ensemble: HasRng<R> + Clone,
R: Rng + SeedableRng
{
let len = NonZeroUsize::new(hists.len())
.ok_or(RewlBuilderErr::Empty)?;
if len < unsafe{NonZeroUsize::new_unchecked(2)} {
return Err(RewlBuilderErr::LenMissmatch);
}
let (left, mut right) = ensemble_tuple;
let mut ensembles = Vec::with_capacity(len.get());
let mid = len.get() / 2;
for _ in 1..mid {
let mut e = left.clone();
let mut rng = R::from_rng(right.rng())
.map_err(RewlBuilderErr::SeedError)?;
e.swap_rng(&mut rng);
ensembles.push(e);
}
ensembles.push(left);
for _ in mid..len.get()-1
{
let mut e = right.clone();
let mut rng = R::from_rng(right.rng())
.map_err(RewlBuilderErr::SeedError)?;
e.swap_rng(&mut rng);
ensembles.push(e);
}
ensembles.push(right);
Self::from_ensemble_vec(ensembles, hists, step_size, sweep_size, walker_per_interval, log_f_threshold)
}
fn build<Energy, R, R2>
(
container: Vec<(Hist, Ensemble, Option<Energy>)>,
walker_per_interval: NonZeroUsize,
log_f_threshold: f64,
step_size: Vec<usize>,
sweep_size: Vec<NonZeroUsize>,
finished: Vec<bool>
) -> Result<Rewl<Ensemble, R, Hist, Energy, S, Res>, Self>
where Energy: Clone,
R2: Rng + SeedableRng,
Ensemble: HasRng<R2>,
R: SeedableRng + Rng + Send + Sync,
walker::RewlWalker<R, Hist, Energy, S, Res>: Send + Sync,
Hist: HistogramVal<Energy>,
Energy: Send + Sync
{
if container.iter().any(|(_, _, e)| e.is_none()){
let (hists, ensembles) = container.into_iter()
.map(|(h, e, _)| (h, e))
.unzip();
return Err(
Self{
ensembles,
hists,
walker_per_interval,
s: PhantomData::<S>,
res: PhantomData::<Res>,
log_f_threshold,
step_size,
sweep_size,
finished
}
);
}
let mut ensembles_rw_lock = Vec::with_capacity(container.len() * walker_per_interval.get());
let mut walker = Vec::with_capacity(walker_per_interval.get() * container.len());
let mut counter = 0;
for (((mut h, mut e, energy), step_size), sweep_size) in container.into_iter()
.zip(step_size.into_iter())
.zip(sweep_size.into_iter())
{
let energy = energy.unwrap();
h.reset();
for _ in 0..walker_per_interval.get()-1 {
let mut ensemble = e.clone();
let mut rng = R2::from_rng(e.rng())
.expect("unable to seed Rng");
ensemble.swap_rng(&mut rng);
ensembles_rw_lock.push(RwLock::new(ensemble));
let rng = R::from_rng(e.rng())
.expect("unable to seed Rng");
walker.push(
RewlWalker::<R, Hist, Energy, S, Res>::new(
counter,
rng,
h.clone(),
sweep_size,
step_size,
energy.clone()
)
);
counter += 1;
}
let rng = R::from_rng(e.rng())
.expect("unable to seed Rng");
walker.push(
RewlWalker::new(
counter,
rng,
h,
sweep_size,
step_size,
energy
)
);
counter += 1;
ensembles_rw_lock.push(RwLock::new(e));
}
let last_extreme_interval_visited = vec![ExtremeInterval::None; walker.len()];
let roundtrip_halves = vec![0; walker.len()];
let mut res = Rewl{
ensembles: ensembles_rw_lock,
replica_exchange_mode: true,
chunk_size: walker_per_interval,
walker,
log_f_threshold,
last_extreme_interval_visited,
roundtrip_halfes: roundtrip_halves
};
res.update_roundtrips();
Ok(
res
)
}
/// # Create `Rewl`, i.e., Replica exchange wang landau simulation
/// * uses a greedy heuristic to find valid configurations, meaning configurations that
/// are within the required intervals, i.e., histograms
/// ## Note
/// * Depending on how complex your energy landscape is, this can take a very long time,
/// maybe not even terminating at all.
/// * You can use `self.try_greedy_choose_rng_build` to limit the time of the search
pub fn greedy_build<R, F, Energy>(self, energy_fn: F) -> Rewl<Ensemble, R, Hist, Energy, S, Res>
where Hist: HistogramVal<Energy>,
Ensemble: HasRng<R> + Sized,
R: Rng + SeedableRng + Send + Sync,
F: Fn(&mut Ensemble) -> Option::<Energy> + Copy + Send + Sync,
Energy: Sync + Send + Clone,
walker::RewlWalker<R, Hist, Energy, S, Res>: Send,
{
match Self::try_greedy_choose_rng_build(self, energy_fn, || true){
Ok(result) => result,
_ => unreachable!()
}
}
/// # Create `Rewl`, i.e., Replica exchange wang landau simulation
/// * similar to [`greedy_build`](`crate::ReplicaExchangeWangLandauBuilder::greedy_build`)
/// * `condition` can be used to limit the time of the search - it will end when `condition`
/// returns false.
/// ##Note
/// * condition will only be checked once every sweep, i.e., every `sweep_size` markov steps
pub fn try_greedy_build<R, F, C, Energy>(self, energy_fn: F, condition: C) -> Result<Rewl<Ensemble, R, Hist, Energy, S, Res>, Self>
where Hist: HistogramVal<Energy>,
Ensemble: HasRng<R> + Sized,
R: Rng + SeedableRng + Send + Sync,
F: Fn(&mut Ensemble) -> Option::<Energy> + Copy + Send + Sync,
C: Fn() -> bool + Copy + Send + Sync,
Energy: Sync + Send + Clone,
walker::RewlWalker<R, Hist, Energy, S, Res>: Send,
{
Self::try_greedy_choose_rng_build(self, energy_fn, condition)
}
/// # Create `Rewl`, i.e., Replica exchange wang landau simulation
/// * similar to [`greedy_build`](`crate::ReplicaExchangeWangLandauBuilder::greedy_build`)
/// * Difference: You can choose a different `Rng` for the Wang Landau walkers (i.e., the
/// acceptance of the replica exchange moves etc.)
/// * usage: `self.greedy_choose_rng_build::<RNG,_,_,_>(energy_fn)`
pub fn greedy_choose_rng_build<R, R2, F, Energy>(self, energy_fn: F) -> Rewl<Ensemble, R, Hist, Energy, S, Res>
where Hist: HistogramVal<Energy>,
R: Rng + SeedableRng + Send + Sync,
Ensemble: HasRng<R2> + Sized,
R2: Rng + SeedableRng,
F: Fn(&mut Ensemble) -> Option::<Energy> + Copy + Send + Sync,
Energy: Sync + Send + Clone,
walker::RewlWalker<R, Hist, Energy, S, Res>: Send,
{
match self.try_greedy_choose_rng_build(energy_fn, || true)
{
Ok(result) => result,
_ => unreachable!()
}
}
/// # Create `Rewl`, i.e., Replica exchange wang landau simulation
/// * similar to [`try_greedy_build`](`crate::ReplicaExchangeWangLandauBuilder::try_greedy_build`)
/// * Difference: You can choose a different `Rng` for the Wang Landau walkers (i.e., the
/// acceptance of the replica exchange moves etc.)
/// * usage: `self.try_greedy_choose_rng_build::<RNG,_,_,_,_>(energy_fn, condition)`
pub fn try_greedy_choose_rng_build<R, R2, F, C, Energy>(self, energy_fn: F, condition: C) -> Result<Rewl<Ensemble, R, Hist, Energy, S, Res>, Self>
where Hist: HistogramVal<Energy>,
R: Rng + SeedableRng + Send + Sync,
Ensemble: HasRng<R2> + Sized,
R2: Rng + SeedableRng,
F: Fn(&mut Ensemble) -> Option::<Energy> + Copy + Send + Sync,
C: Fn() -> bool + Copy + Send + Sync,
Energy: Sync + Send + Clone,
walker::RewlWalker<R, Hist, Energy, S, Res>: Send,
{
let mut container = Vec::with_capacity(self.hists.len());
let ensembles = self.ensembles;
let hists = self.hists;
let step_size = self.step_size;
let sweep_size = self.sweep_size;
let mut finished = self.finished;
ensembles.into_par_iter()
.zip(hists.into_par_iter())
.zip(step_size.par_iter())
.zip(finished.par_iter_mut())
.zip(sweep_size.par_iter())
.map(
|((((mut e, h), &step_size), finished), sweep_size)|
{
let mut energy = 'outer: loop
{
for _ in 0..sweep_size.get(){
if let Some(energy) = energy_fn(&mut e){
break 'outer energy;
}
e.m_steps_quiet(step_size);
}
if !condition(){
return (h, e, None);
}
};
if !h.is_inside(&energy) {
let mut distance = h.distance(&energy);
let mut steps = Vec::with_capacity(step_size);
'outer2: loop
{
for _ in 0..sweep_size.get()
{
e.m_steps(step_size, &mut steps);
let current_energy = if let Some(energy) = energy_fn(&mut e)
{
energy
} else {
e.steps_rejected(&steps);
e.undo_steps_quiet(&steps);
continue;
};
let new_distance = h.distance(¤t_energy);
if new_distance <= distance {
e.steps_accepted(&steps);
energy = current_energy;
distance = new_distance;
if distance == 0.0 {
break 'outer2;
}
}else {
e.steps_rejected(&steps);
e.undo_steps_quiet(&steps);
}
}
if !condition()
{
return (h, e, None);
}
}
}
*finished = true;
(h, e, Some(energy))
}
).collect_into_vec(&mut container);
Self::build(
container,
self.walker_per_interval,
self.log_f_threshold,
step_size,
sweep_size,
finished
)
}
/// # Create `Rewl`, i.e., Replica exchange wang landau simulation
/// * uses an interval heuristic to find valid configurations, meaning configurations that
/// are within the required intervals, i.e., histograms
/// * Uses overlapping intervals. Accepts a step, if the resulting ensemble is in the same interval as before,
/// or it is in an interval closer to the target interval.
/// Take a look at the [`HistogramIntervalDistance` trait](`crate::HistogramIntervalDistance`)
/// * `overlap` should smaller than the number of bins in your histogram. E.g. `overlap = 3` if you have 200 bins
///
/// ## Note
/// * Depending on how complex your energy landscape is, this can take a very long time,
/// maybe not even terminating at all.
/// * You can use [`try_interval_heuristik_build`](`crate::ReplicaExchangeWangLandauBuilder::try_interval_heuristik_build`) to limit the time of the search
pub fn interval_heuristik_build<R, R2, F, Energy>
(
self,
energy_fn: F,
overlap: NonZeroUsize
) -> Rewl<Ensemble, R, Hist, Energy, S, Res>
where Hist: HistogramVal<Energy> + HistogramIntervalDistance<Energy>,
R: Rng + SeedableRng + Send + Sync,
Ensemble: HasRng<R> + Sized,
F: Fn(&mut Ensemble) -> Option::<Energy> + Copy + Send + Sync,
Energy: Sync + Send + Clone,
walker::RewlWalker<R, Hist, Energy, S, Res>: Send,
{
match Self::try_interval_heuristik_build(self, energy_fn, || true, overlap){
Ok(result) => result,
_ => unreachable!()
}
}
/// # Create `Rewl`, i.e., Replica exchange wang landau simulation
/// * similar to [`interval_heuristik_build`](`crate::ReplicaExchangeWangLandauBuilder::interval_heuristik_build`)
/// * `condition` can be used to limit the time of the search - it will end when `condition`
/// returns false.
/// ##Note
/// * condition will only be checked once every sweep, i.e., every `sweep_size` markov steps
pub fn try_interval_heuristik_build<R, F, C, Energy>
(
self,
energy_fn: F,
condition: C,
overlap: NonZeroUsize
) -> Result<Rewl<Ensemble, R, Hist, Energy, S, Res>, Self>
where Hist: HistogramVal<Energy> + HistogramIntervalDistance<Energy>,
R: Rng + SeedableRng + Send + Sync,
Ensemble: HasRng<R> + Sized,
F: Fn(&mut Ensemble) -> Option::<Energy> + Copy + Send + Sync,
C: Fn() -> bool + Copy + Send + Sync,
Energy: Sync + Send + Clone,
walker::RewlWalker<R, Hist, Energy, S, Res>: Send,
{
Self::try_interval_heuristik_choose_rng_build(self, energy_fn, condition, overlap)
}
/// # Create `Rewl`, i.e., Replica exchange wang landau simulation
/// * similar to [`try_interval_heuristik_build`](`crate::ReplicaExchangeWangLandauBuilder::try_interval_heuristik_build`)
/// * Difference: You can choose a different `Rng` for the Wang Landau walkers (i.e., the
/// acceptance of the replica exchange moves etc.)
/// * usage: `self.try_interval_heuristik_build::<RNG,_,_,_,_>(energy_fn, overlap)`
pub fn interval_heuristik_choose_rng_build<R, R2, F, Energy>
(
self,
energy_fn: F,
overlap: NonZeroUsize
) -> Rewl<Ensemble, R, Hist, Energy, S, Res>
where Hist: HistogramVal<Energy> + HistogramIntervalDistance<Energy>,
R: Rng + SeedableRng + Send + Sync,
Ensemble: HasRng<R2> + Sized,
R2: Rng + SeedableRng,
F: Fn(&mut Ensemble) -> Option::<Energy> + Copy + Send + Sync,
Energy: Sync + Send + Clone,
walker::RewlWalker<R, Hist, Energy, S, Res>: Send,
{
match self.try_interval_heuristik_choose_rng_build(energy_fn, || true, overlap) {
Ok(result) => result,
_ => unreachable!()
}
}
/// # Create `Rewl`, i.e., Replica exchange wang landau simulation
/// * similar to [`interval_heuristik_choose_rng_build`](`crate::ReplicaExchangeWangLandauBuilder::interval_heuristik_choose_rng_build`)
/// * Difference: You can choose the Random number generator used for the Rewl Walkers, i.e., for
/// accepting or rejecting the markov steps and replica exchanges.
/// * usage: `self.try_interval_heuristik_choose_rng_build<RNG, _,_,_,_>(energy_fn, condition, overlap)]
pub fn try_interval_heuristik_choose_rng_build<R, R2, F, C, Energy>
(
self,
energy_fn: F,
condition: C,
overlap: NonZeroUsize
) -> Result<Rewl<Ensemble, R, Hist, Energy, S, Res>, Self>
where Hist: HistogramVal<Energy> + HistogramIntervalDistance<Energy>,
R: Rng + SeedableRng + Send + Sync,
Ensemble: HasRng<R2> + Sized,
R2: Rng + SeedableRng,
F: Fn(&mut Ensemble) -> Option::<Energy> + Copy + Send + Sync,
C: Fn() -> bool + Copy + Send + Sync,
Energy: Sync + Send + Clone,
walker::RewlWalker<R, Hist, Energy, S, Res>: Send,
{
let mut container = Vec::with_capacity(self.hists.len());
let ensembles = self.ensembles;
let hists = self.hists;
let step_size = self.step_size;
let sweep_size = self.sweep_size;
let mut finished = self.finished;
ensembles.into_par_iter()
.zip(hists.into_par_iter())
.zip(step_size.par_iter())
.zip(finished.par_iter_mut())
.zip(sweep_size.par_iter())
.map(
|((((mut e, h), &step_size), finished), sweep_size)|
{
let mut energy = 'outer: loop
{
for _ in 0..sweep_size.get(){
if let Some(energy) = energy_fn(&mut e){
break 'outer energy;
}
e.m_steps_quiet(step_size);
}
if !condition(){
return (h, e, None);
}
};
if !h.is_inside(&energy) {
let mut distance = h.interval_distance_overlap(&energy, overlap);
let mut steps = Vec::with_capacity(step_size);
'outer2: loop
{
for _ in 0..sweep_size.get()
{
e.m_steps(step_size, &mut steps);
let current_energy = if let Some(energy) = energy_fn(&mut e)
{
energy
} else {
e.undo_steps_quiet(&steps);
continue;
};
let new_distance = h.interval_distance_overlap(¤t_energy, overlap);
if new_distance <= distance {
energy = current_energy;
distance = new_distance;
if distance == 0 {
break 'outer2;
}
}else {
e.undo_steps_quiet(&steps);
}
}
if !condition()
{
return (h, e, None);
}
}
}
*finished = true;
(h, e, Some(energy))
}
).collect_into_vec(&mut container);
Self::build(
container,
self.walker_per_interval,
self.log_f_threshold,
step_size,
sweep_size,
finished
)
}
/// # Create `Rewl`, i.e., Replica exchange wang landau simulation
/// * alternates between interval-heuristik and greedy-heuristik
/// * The interval heuristik uses overlapping intervals. Accepts a step, if the resulting ensemble is in the same interval as before,
/// or it is in an interval closer to the target interval.
/// Take a look at the [`HistogramIntervalDistance` trait](`crate::HistogramIntervalDistance`)
/// * `overlap` should smaller than the number of bins in your histogram. E.g. `overlap = 3` if you have 200 bins
///
///
/// * greedy_steps: How many steps to perform with greedy heuristik before switching to interval heuristik?
/// * interval_steps: How many steps to perform with interval heuristik before switching back to greedy heuristik?
/// ## Note
/// * Depending on how complex your energy landscape is, this can take a very long time,
/// maybe not even terminating at all.
/// * You can use [`try_mixed_heuristik_build`](`crate::ReplicaExchangeWangLandauBuilder::try_mixed_heuristik_build`) to limit the time of the search
pub fn mixed_heuristik_build<R, F, Energy>
(
self,
energy_fn: F,
overlap: NonZeroUsize,
greedy_steps: NonZeroUsize,
interval_steps: NonZeroUsize
) -> Rewl<Ensemble, R, Hist, Energy, S, Res>
where Hist: HistogramVal<Energy> + HistogramIntervalDistance<Energy>,
R: Rng + SeedableRng + Send + Sync,
Ensemble: HasRng<R> + Sized,
F: Fn(&mut Ensemble) -> Option::<Energy> + Copy + Send + Sync,
Energy: Sync + Send + Clone,
walker::RewlWalker<R, Hist, Energy, S, Res>: Send,
{
match Self::try_mixed_heuristik_choose_rng_build(self, energy_fn, || true, overlap, greedy_steps, interval_steps){
Ok(result) => result,
Err(_) => unreachable!()
}
}
/// # Create `Rewl`, i.e., Replica exchange wang landau simulation
/// * alternates between interval-heuristik and greedy-heuristik
/// * The interval heuristik uses overlapping intervals. Accepts a step, if the resulting ensemble is in the same interval as before,
/// or it is in an interval closer to the target interval.
/// Take a look at the [`HistogramIntervalDistance` trait](`crate::HistogramIntervalDistance`)
/// * `overlap` should smaller than the number of bins in your histogram. E.g. `overlap = 3` if you have 200 bins
///
/// * greedy_steps: How many steps to perform with greedy heuristik before switching to interval heuristik?
/// * interval_steps: How many steps to perform with interval heuristik before switching back to greedy heuristik?
///
/// ## Note
/// * `condition` can be used to limit the time of the search - it will end when `condition`
/// returns false (or a valid solution is found)
/// * condition will be checked each time the heuristik switches between greedy and interval heuristik
pub fn try_mixed_heuristik_build<R, F, C, Energy>
(
self,
energy_fn: F,
condition: C,
overlap: NonZeroUsize,
greedy_steps: NonZeroUsize,
interval_steps: NonZeroUsize
) -> Result<Rewl<Ensemble, R, Hist, Energy, S, Res>, Self>
where Hist: HistogramVal<Energy> + HistogramIntervalDistance<Energy>,
R: Rng + SeedableRng + Send + Sync,
Ensemble: HasRng<R> + Sized,
F: Fn(&mut Ensemble) -> Option::<Energy> + Copy + Send + Sync,
C: Fn() -> bool + Copy + Send + Sync,
Energy: Sync + Send + Clone,
walker::RewlWalker<R, Hist, Energy, S, Res>: Send,
{
Self::try_mixed_heuristik_choose_rng_build(self, energy_fn, condition, overlap, greedy_steps, interval_steps)
}
/// # Create `Rewl`, i.e., Replica exchange wang landau simulation
/// * similar to [`try_mixed_heuristik_build`](`crate::ReplicaExchangeWangLandauBuilder::try_mixed_heuristik_build`)
/// * difference: Lets you choose the rng type for the Rewl simulation, i.e., the rng used for
/// accepting or rejecting markov steps and replica exchange moves
/// * usage: `self.try_mixed_heuristik_choose_rng_build<RNG_TYPE, _, _, _, _>(energy_fn, condition, overlap, greedy_steps, interval_steps)`
///
/// * greedy_steps: How many steps to perform with greedy heuristik before switching to interval heuristik?
/// * interval_steps: How many steps to perform with interval heuristik before switching back to greedy heuristik?
///
/// ## Note
/// * condition will be checked each time the heuristik switches between greedy and interval heuristik
pub fn try_mixed_heuristik_choose_rng_build<R, R2, F, C, Energy>
(
self,
energy_fn: F,
condition: C,
overlap: NonZeroUsize,
greedy_steps: NonZeroUsize,
interval_steps: NonZeroUsize
) -> Result<Rewl<Ensemble, R, Hist, Energy, S, Res>, Self>
where Hist: HistogramVal<Energy> + HistogramIntervalDistance<Energy>,
R: Rng + SeedableRng + Send + Sync,
Ensemble: HasRng<R2> + Sized,
R2: Rng + SeedableRng,
F: Fn(&mut Ensemble) -> Option::<Energy> + Copy + Send + Sync,
C: Fn() -> bool + Copy + Send + Sync,
Energy: Sync + Send + Clone,
walker::RewlWalker<R, Hist, Energy, S, Res>: Send,
{
let mut container = Vec::with_capacity(self.hists.len());
let ensembles = self.ensembles;
let hists = self.hists;
let step_size = self.step_size;
let sweep_size = self.sweep_size;
let mut finished = self.finished;
ensembles.into_par_iter()
.zip(hists.into_par_iter())
.zip(step_size.par_iter())
.zip(finished.par_iter_mut())
.zip(sweep_size.par_iter())
.map(
|((((mut e, h), &step_size), finished), sweep_size)|
{
let mut energy = 'outer: loop
{
for _ in 0..sweep_size.get(){
if let Some(energy) = energy_fn(&mut e){
break 'outer energy;
}
e.m_steps_quiet(step_size);
}
if !condition(){
return (h, e, None);
}
};
if !h.is_inside(&energy) {
let mut distance_interval;
let mut distance;
let mut steps = Vec::with_capacity(step_size);
'outer2: loop
{
distance = h.distance(&energy);
for _ in 0..greedy_steps.get()
{
e.m_steps(step_size, &mut steps);
let current_energy = if let Some(energy) = energy_fn(&mut e)
{
energy
} else {
e.undo_steps_quiet(&steps);
continue;
};
let new_distance = h.distance(¤t_energy);
if new_distance <= distance {
energy = current_energy;
distance = new_distance;
if distance == 0.0 {
break 'outer2;
}
}else {
e.undo_steps_quiet(&steps);
}
}
if !condition()
{
return (h, e, None);
}
distance_interval = h.interval_distance_overlap(&energy, overlap);
for _ in 0..interval_steps.get()
{
e.m_steps(step_size, &mut steps);
let current_energy = if let Some(energy) = energy_fn(&mut e)
{
energy
} else {
e.undo_steps_quiet(&steps);
continue;
};
let new_distance = h.interval_distance_overlap(¤t_energy, overlap);
if new_distance <= distance_interval {
energy = current_energy;
distance_interval = new_distance;
if distance_interval == 0 {
break 'outer2;
}
}else {
e.undo_steps_quiet(&steps);
}
}
if !condition()
{
return (h, e, None);
}
}
}
*finished = true;
(h, e, Some(energy))
}
).collect_into_vec(&mut container);
Self::build(
container,
self.walker_per_interval,
self.log_f_threshold,
step_size,
sweep_size,
finished
)
}
}