This commit is contained in:
danijoo
2018-10-03 19:07:41 +02:00
commit d190cd07da
21 changed files with 32498 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
target

231
Cargo.lock generated Normal file
View File

@@ -0,0 +1,231 @@
[[package]]
name = "aho-corasick"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ansi_term"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "atty"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "bitflags"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "cfg-if"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "clap"
version = "2.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",
"atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
"bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
"strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"textwrap 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
"vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)",
"yaml-rust 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "lazy_static"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "libc"
version = "0.2.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "memchr"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "redox_syscall"
version = "0.1.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "redox_termios"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "regex"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"aho-corasick 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)",
"memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"regex-syntax 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
"thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
"utf8-ranges 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "regex-syntax"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"ucd-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "scan_fmt"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"regex 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "strsim"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "termion"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
"redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "textwrap"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "thread_local"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ucd-util"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "unicode-width"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "utf8-ranges"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "vec_map"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "version_check"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "wham"
version = "0.1.0"
dependencies = [
"clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)",
"scan_fmt 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "winapi"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "yaml-rust"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
[metadata]
"checksum aho-corasick 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)" = "68f56c7353e5a9547cbd76ed90f7bb5ffc3ba09d4ea9bd1d8c06c8b1142eeb5a"
"checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"
"checksum atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "9a7d5b8723950951411ee34d271d99dddcc2035a16ab25310ea2c8cfd4369652"
"checksum bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12"
"checksum cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "0c4e7bb64a8ebb0d856483e1e682ea3422f883c5f5615a90d51a2c82fe87fdd3"
"checksum clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b957d88f4b6a63b9d70d5f454ac8011819c6efa7727858f458ab71c756ce2d3e"
"checksum lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ca488b89a5657b0a2ecd45b95609b3e848cf1755da332a0da46e2b2b1cb371a7"
"checksum libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)" = "76e3a3ef172f1a0b9a9ff0dd1491ae5e6c948b94479a3021819ba7d860c8645d"
"checksum memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4b3629fe9fdbff6daa6c33b90f7c08355c1aca05a3d01fa8063b822fcf185f3b"
"checksum redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "c214e91d3ecf43e9a4e41e578973adeb14b474f2bee858742d127af75a0112b1"
"checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76"
"checksum regex 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "9329abc99e39129fcceabd24cf5d85b4671ef7c29c50e972bc5afe32438ec384"
"checksum regex-syntax 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "7d707a4fa2637f2dca2ef9fd02225ec7661fe01a53623c1e6515b6916511f7a7"
"checksum scan_fmt 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8b87497427f9fbe539ee6b9626f5a5e899331fdf1c1d62f14c637a462969db30"
"checksum strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb4f380125926a99e52bc279241539c018323fab05ad6368b56f93d9369ff550"
"checksum termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "689a3bdfaab439fd92bc87df5c4c78417d3cbe537487274e9b0b2dce76e92096"
"checksum textwrap 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "307686869c93e71f94da64286f9a9524c0f308a9e1c87a583de8e9c9039ad3f6"
"checksum thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b"
"checksum ucd-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fd2be2d6639d0f8fe6cdda291ad456e23629558d466e2789d2c3e9892bda285d"
"checksum unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "882386231c45df4700b275c7ff55b6f3698780a650026380e72dabe76fa46526"
"checksum utf8-ranges 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fd70f467df6810094968e2fce0ee1bd0e87157aceb026a8c083bcf5e25b9efe4"
"checksum vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a"
"checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd"
"checksum winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "92c1eb33641e276cfa214a0522acad57be5c56b10cb348b3c5117db75f3ac4b0"
"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
"checksum yaml-rust 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e66366e18dc58b46801afbf2ca7661a9f59cc8c5962c29892b6039b4f86fa992"

8
Cargo.toml Normal file
View File

@@ -0,0 +1,8 @@
[package]
name = "wham"
version = "0.1.0"
authors = ["danijoo <danijob88@googlemail.com>"]
[dependencies]
clap = {version="2.32.0", features=['yaml']}
scan_fmt = "0.1.3"

4502
data/COLVAR_0.2 Normal file

File diff suppressed because it is too large Load Diff

4502
data/COLVAR_0.25 Normal file

File diff suppressed because it is too large Load Diff

4502
data/COLVAR_0.3 Normal file

File diff suppressed because it is too large Load Diff

4502
data/COLVAR_0.35 Normal file

File diff suppressed because it is too large Load Diff

4502
data/COLVAR_0.4 Normal file

File diff suppressed because it is too large Load Diff

4502
data/COLVAR_0.45 Normal file

File diff suppressed because it is too large Load Diff

4502
data/COLVAR_0.5 Normal file

File diff suppressed because it is too large Load Diff

7
data/metadata.dat Normal file
View File

@@ -0,0 +1,7 @@
data/COLVAR_0.2 0.2 100000
data/COLVAR_0.25 0.25 100000
data/COLVAR_0.3 0.3 100000
data/COLVAR_0.35 0.35 100000
data/COLVAR_0.4 0.4 100000
data/COLVAR_0.45 0.45 100000
data/COLVAR_0.5 0.5 100000

1
pymbar Submodule

Submodule pymbar added at 727233fea9

57
src/cli.yml Normal file
View File

@@ -0,0 +1,57 @@
name: wham
version: "0.1.0"
author: D. Bauer <bauer@cbs.tu-darmstadt.de>
about: WHAM analysis
args:
- metadata:
short: f
long: file
value_name: METADATA
help: Sets the metadata file
takes_value: true
required: true
- min_hist:
long: min
value_name: HIST_MIN
takes_value: true
required: true
allow_hyphen_values: true
- max_hist:
long: max
value_name: HIST_MAX
takes_value: true
required: true
allow_hyphen_values: true
- bins:
short: b
long: bins
value_name: BINS
takes_value: true
required: true
- tolerance:
short: t
long: tolerance
value_name: TOLERANCE
takes_value: true
required: false
- iterations:
short: i
long: iterations
value_name: ITERATIONS
takes_value: true
required: false
- pbc:
long: pbc
help: Apply periodic conditions (Not implemented yet.)
- verbose:
short: v
long: verbose
help: Enables verbose output.
takes_value: false
- temperature:
short: T
long: temperature
help: WHAM temperature in Kelvin
takes_value: true
required: true

109
src/histogram.rs Normal file
View File

@@ -0,0 +1,109 @@
use std::fmt;
// One histogram
#[derive(Debug)]
pub struct Histogram {
// offset of this histogram bins from the global histogram
pub first: usize,
// offset of the last element of the histogram. TODO required?
pub last: usize,
// total number of data points stored in the histogram
pub num_points: u32,
// histogram bins
pub bins: Vec<f32>
}
impl Histogram {
pub fn new(first: usize, last: usize, num_points: u32, bins: Vec<f32>) -> Histogram {
Histogram {first, last, num_points, bins}
}
// Returns the value of a bin if the bin is present in this
// histogram
pub fn get_bin_count(&self, bin: usize) -> Option<f32> {
if bin < self.first || bin > self.last {
None
} else {
Some(self.bins[bin-self.first])
}
}
}
// a set of histograms
#[derive(Debug)]
pub struct HistogramSet {
// number of histogram windows (number of simulations)
pub num_windows: usize,
// number of global histogram bins
pub num_bins: usize,
// min value of the histogram
pub hist_min: f32,
// max value of the histogram
pub hist_max: f32,
// width of a bin in unit of x
pub bin_width: f32,
// locations of biases
pub bias_x0: Vec<f32>,
// force constants of biases
pub bias_fc: Vec<f32>,
// value of kT
pub kT: f32,
// histogram for each window
pub histograms: Vec<Histogram>
}
impl HistogramSet {
pub fn new(num_bins: usize, bin_width: f32, hist_min: f32, hist_max: f32, bias_x0: Vec<f32>, bias_fc: Vec<f32>, kT: f32, histograms: Vec<Histogram>) -> HistogramSet {
let num_windows = histograms.len();
HistogramSet{num_windows, num_bins, bin_width, hist_min, hist_max, bias_x0, bias_fc, kT, histograms}
}
}
impl fmt::Display for HistogramSet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut datapoints: u32 = 0;
for h in &self.histograms {
datapoints += h.num_points;
}
write!(f, "{} windows and {} bins ranging from {} to {} (bin width: {}).\nDatapoints: {}",
self.num_windows, self.num_bins, self.hist_min, self.hist_max, self.bin_width, datapoints)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn build_hist() -> Histogram {
Histogram{
first: 5,
last: 7,
num_points: 5,
bins: vec![1.0,1.0,3.0]
}
}
#[test]
fn get_bin_count() {
let h = build_hist();
assert_eq!(3.0, h.get_bin_count(7).unwrap());
assert_eq!(3.0, h.get_bin_count(7).unwrap()); // twice for borrow
assert_eq!(1.0, h.get_bin_count(5).unwrap());
assert_eq!(None, h.get_bin_count(4));
assert_eq!(None, h.get_bin_count(8));
}
}

169
src/io.rs Normal file
View File

@@ -0,0 +1,169 @@
use super::histogram::HistogramSet;
use super::histogram::Histogram;
use super::Config;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use k_B;
use std::process;
use std::option::Option;
// Read input data into a histogram set by iterating over input files
// given in the metadata file
pub fn read_data(cfg: &Config) -> Option<HistogramSet> {
let mut bias_x0: Vec<f32> = Vec::new();
let mut bias_fc: Vec<f32> = Vec::new();
let mut histograms: Vec<Histogram> = Vec::new();
let kT = cfg.temperature * k_B;
let f = File::open(&cfg.metadata_file).unwrap_or_else(|x| {
eprintln!("Failed to read metadata from {}. {}", &cfg.metadata_file, x);
process::exit(1)
});
let buf = BufReader::new(&f);
for l in buf.lines() {
let line = l.unwrap();
// skip comments and empty lines
if line.starts_with("#") || line.len() == 0 {
continue;
}
let (path, x0, k) = scan_fmt!(&line, "{} {} {}", String, f32, f32);
let path = path.unwrap();
match read_window_file(&path, cfg) {
Some(h) => {
histograms.push(h);
if cfg.verbose {
println!("File: {}, {} Data points added.", &path, histograms.last().unwrap().num_points);
}
},
None => {
eprintln!("No data points inside histogram boundaries: {}", &path);
continue; // goto next iteration and skip adding bias values
}
}
bias_x0.push(x0.unwrap_or_else(|| {
eprintln!("Failed to read coordinate from: {}", &line);
process::exit(1)
}));
bias_fc.push(k.unwrap_or_else(|| {
eprintln!("Failed to read bias value from: {}", &line);
process::exit(1)
}));
}
if histograms.len() > 0 {
let bin_width = (cfg.hist_max - cfg.hist_min)/(cfg.num_bins as f32);
Some(HistogramSet::new(cfg.num_bins, bin_width, cfg.hist_min, cfg.hist_max, bias_x0, bias_fc, kT, histograms))
} else {
None
}
}
// parse a timeseries file into a histogram
fn read_window_file(window_file: &str, cfg: &Config) -> Option<Histogram> {
let f = File::open(window_file).unwrap_or_else(|x| {
eprintln!("Failed to read sample data from {}. {}", window_file, x);
process::exit(1)
});
let buf = BufReader::new(&f);
let mut global_hist = vec![0.0; cfg.num_bins];
let mut num_points: u32 = 0;
let mut max_bin: usize = 0;
let mut min_bin: usize =(cfg.num_bins-1) as usize;
let bin_width = (cfg.hist_max - cfg.hist_min)/(cfg.num_bins as f32);
for l in buf.lines() {
let line = l.unwrap();
// skip comments and empty lines
if line.starts_with("#") || line.starts_with("@") || line.len() == 0 {
continue;
}
let (_, x) = scan_fmt!(&line, "{} {}", f32, f32);
match x {
Some(x) => {
if x > cfg.hist_min && x < cfg.hist_max {
let bin_ndx = ((x-cfg.hist_min) / bin_width) as usize;
global_hist[bin_ndx] += 1.0;
num_points += 1;
if bin_ndx > max_bin {
max_bin = bin_ndx
}
if bin_ndx < min_bin {
min_bin = bin_ndx
}
}
}
None => {
eprintln!("{}, Failed to read datapoint from line: {}", &window_file, &line);
process::exit(1);
}
}
}
global_hist.truncate(max_bin+1);
if global_hist.len() > 1 || global_hist[0] != 0.0 {
global_hist.drain(..min_bin);
Some(Histogram::new(min_bin, max_bin, num_points, global_hist))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cfg() -> Config {
Config{
metadata_file: "tests/data/metadata.dat".to_string(),
hist_min: 0.0,
hist_max: 3.0,
num_bins: 30,
verbose: false,
tolerance: 0.0,
max_iterations: 0,
temperature: 300.0
}
}
#[test]
fn read_window_file() {
let f = "tests/data/window_0.0.dat";
let cfg = cfg();
let h = super::read_window_file(&f, &cfg).unwrap();
println!("{:?}", h);
assert_eq!(1, h.first);
assert_eq!(6, h.last);
assert_eq!(11, h.num_points);
assert_eq!(2.0, h.bins[0]);
assert_eq!(2.0, h.bins[2]);
assert_eq!(2.0, h.bins[4]);
assert_eq!(1.0, h.bins[5]);
}
#[test]
fn read_data() {
let cfg = cfg();
let hs = super::read_data(&cfg);
assert!(hs.is_some());
let hs = hs.unwrap();
println!("{:?}", hs);
assert_eq!(2, hs.num_windows);
assert_eq!(cfg.num_bins, hs.num_bins);
assert_eq!(cfg.hist_min, hs.hist_min);
assert_eq!(cfg.hist_max, hs.hist_max);
let expected_bin_width = (cfg.hist_max - cfg.hist_min)/cfg.num_bins as f32;
assert_eq!(expected_bin_width, hs.bin_width);
assert_eq!(vec![0.0, 1.0], hs.bias_x0);
assert_eq!(vec![100.0, 200.0], hs.bias_fc);
assert_eq!(cfg.temperature * k_B, hs.kT);
assert_eq!(2, hs.histograms.len())
}
}

325
src/lib.rs Normal file
View File

@@ -0,0 +1,325 @@
#![allow(non_snake_case)]
#[macro_use]
extern crate scan_fmt;
pub mod io;
pub mod histogram;
use std::error::Error;
use std::result::Result;
use histogram::{HistogramSet,Histogram};
use std::f32;
use std::fmt;
#[allow(non_upper_case_globals)]
static k_B: f32 = 0.0083144621; // kJ/mol*K
// Application config
#[derive(Debug)]
pub struct Config {
pub metadata_file: String,
pub hist_min: f32,
pub hist_max: f32,
pub num_bins: usize,
pub verbose: bool,
pub tolerance: f32,
pub max_iterations: usize,
pub temperature: f32,
}
impl fmt::Display for Config {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Metadata={}, hist_min={}, hist_max={}, bins={}\nverbose={}, tolerance={}, iterations={}, temperature={}" , self.metadata_file, self.hist_min,
self.hist_max, self.num_bins, self.verbose, self.tolerance,
self.max_iterations, self.temperature)
}
}
// Checks for convergence between two WHAM iterations. WHAM is considered as
// converged if the absolute difference for the calculated bias offset is
// smaller then a tolerance value for each simulation window
fn is_converged(old_F: &Vec<f32>, new_F: &Vec<f32>, tolerance: f32) -> bool {
for i in 0..old_F.len() {
let error = (new_F[i] - old_F[i]).abs();
if error > tolerance {
return false
}
}
true
}
// Harmonic bias calculation: bias = 0.5*k(dx)^2
fn calc_bias(k: f32, x0: f32, x: f32) -> f32 {
let dx = (x-x0).abs();
0.5*k*dx*dx
}
// get center x value for a bin
fn get_x_for_bin(bin: usize, min: f32, width: f32) -> f32 {
min + width * ((bin as f32) + 0.5)
}
// estimate the probability of a bin of the histogram set based on F values
// This evaluates the first WHAM equation for each bin
fn calc_bin_probability(bin: usize, hs: &HistogramSet, F: &Vec<f32>) -> f32 {
let mut denom_sum = 0.0;
let mut bin_count = 0.0;
let x = get_x_for_bin(bin, hs.hist_min, hs.bin_width);
for window in 0..hs.num_windows {
let h: &Histogram = &hs.histograms[window];
if let Some(count) = h.get_bin_count(bin) {
bin_count += count;
}
let bias = calc_bias(hs.bias_fc[window], hs.bias_x0[window], x);
let bias_offset = ((F[window] - bias) / hs.kT).exp();
denom_sum += (h.num_points as f32) * bias_offset;
}
bin_count / denom_sum
}
// estimate the bias offset F of the histogram based on given probabilities
// This evaluates the second WHAM equation for each window
fn calc_window_F(window: usize, hs: &HistogramSet, P: &Vec<f32>) -> f32 {
let mut ln_sum = 0.0;
for bin in 0..hs.num_bins {
let x = get_x_for_bin(bin, hs.hist_min, hs.bin_width);
let bias = calc_bias(hs.bias_fc[window], hs.bias_x0[window], x);
ln_sum += P[bin] * (-bias/hs.kT).exp()
}
-hs.kT * ln_sum.ln()
}
// One full WHAM iteration includes calculation of new probabilities P and
// new bias offsets F based on previous bias offsets F_prev. This updates
// the values in vectors F and P
fn perform_wham_iteration(hs: &HistogramSet, F_prev: &Vec<f32>,F: &mut Vec<f32>, P: &mut Vec<f32>) {
// reset bias offsets
for window in 0..hs.num_windows {
F[window] = 0.0;
}
// evaluate first WHAM equation for each bin to
// estimage probabilities based on previous offsets (F_prev)
for bin in 0..hs.num_bins {
P[bin] = calc_bin_probability(bin, hs, F_prev);
}
// evaluate second WHAM equation for each window to
// estimate new bias offsets from propabilities
for window in 0..hs.num_windows {
F[window] = calc_window_F(window, hs, P);
}
}
// get average difference between two bias offset sets
fn diff_avg(F: &Vec<f32>, F_prev: &Vec<f32>) -> f32 {
let mut F_sum = 0.0;
for i in 0..F.len() {
F_sum += (F[i]-F_prev[i]).abs()
}
F_sum / F.len() as f32
}
// calculate the normalized free energy from normalized probability values
fn free_energy(hs: &HistogramSet, P: &mut Vec<f32>, A: &mut Vec<f32>) {
// Normalize P
let mut P_sum = 0.0;
for bin in 0..hs.num_bins {
P_sum += P[bin];
}
for bin in 0..hs.num_bins {
P[bin] /= P_sum;
}
// Free energy calculation
for bin in 0..hs.num_bins {
A[bin] = -hs.kT*P[bin].ln();
}
// find min value
let mut min: f32 = f32::MAX;
for bin in 0..hs.num_bins {
if A[bin] < min {
min = A[bin]
}
}
// normalize A
for bin in 0..hs.num_bins {
A[bin] -= min;
}
}
pub fn run(cfg: &Config) -> Result<(), Box<Error>>{
println!("{}", &cfg);
// read input data into the histograms object
let histograms = io::read_data(&cfg).unwrap();
println!("Input consists of {}",&histograms);
// allocate data arrays for performance
let mut F_prev = vec![f32::INFINITY; histograms.num_windows];
let mut F = vec![0.0; histograms.num_windows];
let mut P = vec![f32::NAN; histograms.num_bins];
let mut A = vec![f32::NAN; histograms.num_bins];
// perform WHAM until convergence
let mut iteration = 0;
while !is_converged(&F_prev, &F, cfg.tolerance) && iteration < cfg.max_iterations {
iteration += 1;
// store F values before the next iteration
F_prev.copy_from_slice(&F[..]);
// perform wham iteration and update F
perform_wham_iteration(&histograms, &F_prev, &mut F, &mut P);
// output some stats during calculation
if iteration % 100 == 0 {
println!("Iteration {}: dF={}", &iteration, &diff_avg(&F_prev, &F));
}
// Dump free energy and bias offsets
if iteration % 1000 == 0 {
free_energy(&histograms, &mut P, &mut A);
println!("#PMF");
println!("#x\t\tFree Energy\t\tP(x)");
for bin in 0..histograms.num_bins {
let x = get_x_for_bin(bin, histograms.hist_min, histograms.bin_width);
println!("{:9.5}\t{:9.5}\t{:9.5}", x, A[bin], P[bin]);
}
println!("#Bias offsets");
println!("#Window\t\tF\t\tdF");
for window in 0..histograms.num_windows {
println!("{}\t{:9.5}\t{:8.8}", window, F[window], (F[window]-F_prev[window]).abs());
}
}
}
if iteration == cfg.max_iterations {
println!("!!!!! WHAM not converged! (max iterations reached) !!!!!");
}
// println!("#Window\t\t F");
// for window in 0..histograms.num_windows {
// println!("#{}\t\t{}", window, F[window]);
// }
// let mut free_energy = vec![0.0; histograms.num_bins];
// for bin in 0..histograms.num_bins {
// let P = calc_bin_probability(bin, &histograms, &F);
// free_energy[bin] = -histograms.kT * P.ln();
// }
// let mut min = &f32::MAX;
// for bin in 0..histograms.num_bins {
// if &free_energy[bin] < min {
// min = &free_energy[bin]
// }
// }
// println!("#x\t\tFree energy");
// for bin in 0..histograms.num_bins {
// let x = get_x_for_bin(bin, histograms.hist_min, histograms.bin_width);
// let free_normalized = free_energy[bin] - min;
// println!("{}\t\t{}", x, free_normalized);
// }
Ok(())
}
#[cfg(test)]
mod tests {
use super::histogram::{HistogramSet,Histogram};
use std::f32;
#[test]
fn is_converged() {
let new = vec![1.0,1.0];
let old = vec![0.95, 1.0];
let tolerance = 0.1;
let converged = super::is_converged(&old, &new, tolerance);
assert!(converged);
let old = vec![0.8, 1.0];
let converged = super::is_converged(&old, &new, tolerance);
assert!(!converged);
}
#[test]
fn calc_bias() {
let x0 = 10.0;
let x = 5.0;
let k = 500.0;
assert_eq!(6250.0, super::calc_bias(k, x0, x));
}
fn create_test_hs() -> HistogramSet {
let h1 = Histogram::new(0, 2, 10, vec![3.0, 4.0, 3.0]);
let h2 = Histogram::new(0, 3, 20, vec![3.0, 2.0, 5.0, 10.0]);
HistogramSet::new(4, 1.0, 0.0, 4.0, vec![1.0, 2.0], vec![10.0, 10.0], 2.479, vec![h1, h2])
}
fn assert_near(a: f32, b: f32, tolerance: f32) {
let d = (a-b).abs();
assert!(d <= tolerance, "Values are not close: {}, {}, d={}", &a, &b, &d);
}
#[test]
fn calc_bias_offset() {
let hs = create_test_hs();
let probability = vec!(0.959, 0.331, 0.656, 46.750);
let expected = vec!(0.596, -0.250);
for window in 0..hs.num_windows {
let F = super::calc_window_F(window, &hs, &probability);
assert_near(expected[window], F, 0.001);
}
}
#[test]
fn calc_bin_probability() {
let hs = create_test_hs();
let F = vec!(0.0, 0.0);
let expected = vec!(0.959, 0.331, 0.656, 46.750);
for b in 0..4 {
let p = super::calc_bin_probability(b, &hs, &F);
assert_near(expected[b], p, 0.001);
}
let F = vec!(1.0, 1.0);
let expected = vec!(0.641, 0.221, 0.439, 31.232);
for b in 0..4 {
let p = super::calc_bin_probability(b, &hs, &F);
assert_near(expected[b], p, 0.001);
}
}
#[test]
fn get_x_for_bin() {
let min = 0.0;
let width = 1.0;
let expected = vec!(0.5, 1.5, 2.5, 3.5, 4.5);
for i in 0..5 {
let x = super::get_x_for_bin(i, min, width);
assert_eq!(expected[i], x);
}
}
#[test]
fn test_perform_wham_iteration() {
let hs = create_test_hs();
let prev_F = vec![0.0; hs.num_windows];
let mut F = vec![0.0; hs.num_windows];
let mut P = vec![f32::NAN; hs.num_bins];
super::perform_wham_iteration(&hs, &prev_F, &mut F, &mut P);
let expected_F = vec!(0.596, -0.250);
let expected_P = vec!(0.959, 0.331, 0.656, 46.750);
for bin in 0..hs.num_bins {
assert_near(expected_P[bin], P[bin], 0.01)
}
for window in 0..hs.num_windows {
assert_near(expected_F[window], F[window], 0.01)
}
}
}

45
src/main.rs Normal file
View File

@@ -0,0 +1,45 @@
extern crate wham;
#[macro_use]
extern crate clap;
use clap::App;
use wham::Config;
use std::error::Error;
use std::result::Result;
use std::process;
use std::env;
// Parse command line arguments into a Config struct
fn cli() -> Result<Config, Box<Error>> {
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
let metadata_file = matches.value_of("metadata").unwrap().to_string();
let hist_min: f32 = matches.value_of("min_hist").unwrap().parse()?;
let hist_max: f32 = matches.value_of("max_hist").unwrap().parse()?;
let num_bins: usize = matches.value_of("bins").unwrap().parse()?;
let verbose: bool = matches.is_present("verbose");
let temperature: f32 = matches.value_of("temperature").unwrap().parse()?;
let tolerance: f32;
if matches.is_present("tolerance") {
tolerance = matches.value_of("tolerance").unwrap().parse()?;
} else {
tolerance = std::f32::MIN_POSITIVE;
}
let max_iterations: usize;
if matches.is_present("iterations") {
max_iterations = matches.value_of("iterations").unwrap().parse()?;
} else {
max_iterations = std::usize::MAX;
}
Ok(wham::Config{metadata_file, hist_min, hist_max, num_bins,
verbose, tolerance, max_iterations, temperature})
}
fn main() {
let cfg = cli().expect("Failed to parse CLI.");
match wham::run(&cfg) {
Err(_) => process::exit(1),
_ => {}
}
}

4
tests/data/metadata.dat Normal file
View File

@@ -0,0 +1,4 @@
# a comment
tests/data/window_0.0.dat 0.0 100
tests/data/window_1.0.dat 1.0 200
tests/data/window_99.0.dat 99.0 600

12
tests/data/window_0.0.dat Normal file
View File

@@ -0,0 +1,12 @@
1 0.1
2 0.15
3 0.2
4 0.25
5 0.3
6 0.35
7 0.4
8 0.45
9 0.5
1 0.55
11 0.6
12 99

10
tests/data/window_1.0.dat Normal file
View File

@@ -0,0 +1,10 @@
1 1.0
2 1.0
3 1.0
4 1.0
5 1.0
6 1.0
7 1.0
8 1.0
9 1.0
1 1.0

View File

@@ -0,0 +1,5 @@
1 99.0
2 99.0
3 99.0
4 99.0
5 99.0