33//! Simplistic MCMC ensemble sampler based on [emcee](https://emcee.readthedocs.io/), the MCMC hammer
44//!
55//! ```
6- //! use hammer_and_sample::{sample, MinChainLen, Model, Serial};
6+ //! use hammer_and_sample::{sample, MinChainLen, Model, Serial, Stretch };
77//! use rand::{Rng, SeedableRng};
88//! use rand_pcg::Pcg64;
99//!
3939//! ([p], rng)
4040//! });
4141//!
42- //! let (chain, _accepted) = sample(&model, walkers, MinChainLen(10 * 1000), Serial);
42+ //! let (chain, _accepted) = sample(&model, &Stretch::default(), walkers, MinChainLen(10 * 1000), Serial);
4343//!
4444//! // 100 iterations of 10 walkers as burn-in
4545//! let chain = &chain[10 * 100..];
4848//! }
4949//! ```
5050use std:: ops:: ControlFlow ;
51+ use std:: ptr;
5152
5253use rand:: {
5354 distr:: { Distribution , StandardUniform , Uniform } ,
5455 Rng ,
5556} ;
57+ use rand_distr:: {
58+ weighted:: { AliasableWeight , WeightedAliasIndex } ,
59+ Normal ,
60+ } ;
5661#[ cfg( feature = "rayon" ) ]
5762use rayon:: iter:: { IntoParallelRefMutIterator , ParallelExtend , ParallelIterator } ;
5863
@@ -117,6 +122,169 @@ impl Params for Box<[f64]> {
117122 }
118123}
119124
125+ /// TODO
126+ pub trait Move < M >
127+ where
128+ M : Model ,
129+ {
130+ /// TODO
131+ fn propose < ' a , O , R > ( & self , self_ : & ' a M :: Params , other : O , rng : & mut R ) -> ( M :: Params , f64 )
132+ where
133+ O : FnMut ( & mut R ) -> & ' a M :: Params ,
134+ R : Rng ;
135+ }
136+
137+ /// TODO
138+ pub struct Stretch {
139+ scale : f64 ,
140+ }
141+
142+ impl Stretch {
143+ /// TODO
144+ pub fn new ( scale : f64 ) -> Self {
145+ Self { scale }
146+ }
147+ }
148+
149+ impl Default for Stretch {
150+ fn default ( ) -> Self {
151+ Self :: new ( 2. )
152+ }
153+ }
154+
155+ impl < M > Move < M > for Stretch
156+ where
157+ M : Model ,
158+ {
159+ fn propose < ' a , O , R > ( & self , self_ : & ' a M :: Params , mut other : O , rng : & mut R ) -> ( M :: Params , f64 )
160+ where
161+ O : FnMut ( & mut R ) -> & ' a M :: Params ,
162+ R : Rng ,
163+ {
164+ let other = other ( rng) ;
165+
166+ let z = ( ( self . scale - 1. ) * gen_unit ( rng) + 1. ) . powi ( 2 ) / self . scale ;
167+
168+ let new_state = M :: Params :: collect (
169+ self_
170+ . values ( )
171+ . zip ( other. values ( ) )
172+ . map ( |( self_, other) | other - z * ( other - self_) ) ,
173+ ) ;
174+
175+ let factor = ( new_state. dimension ( ) - 1 ) as f64 * z. ln ( ) ;
176+
177+ ( new_state, factor)
178+ }
179+ }
180+
181+ /// TODO
182+ pub struct DifferentialEvolution {
183+ gamma : Normal < f64 > ,
184+ }
185+
186+ impl DifferentialEvolution {
187+ /// TODO
188+ pub fn new ( sigma : f64 , gamma0 : f64 ) -> Self {
189+ Self {
190+ gamma : Normal :: new ( gamma0, sigma) . unwrap ( ) ,
191+ }
192+ }
193+ }
194+
195+ impl < M > Move < M > for DifferentialEvolution
196+ where
197+ M : Model ,
198+ {
199+ fn propose < ' a , O , R > ( & self , self_ : & ' a M :: Params , mut other : O , rng : & mut R ) -> ( M :: Params , f64 )
200+ where
201+ O : FnMut ( & mut R ) -> & ' a M :: Params ,
202+ R : Rng ,
203+ {
204+ let first_other = other ( rng) ;
205+ let mut second_other = other ( rng) ;
206+
207+ while ptr:: eq ( first_other, second_other) {
208+ second_other = other ( rng) ;
209+ }
210+
211+ let gamma = self . gamma . sample ( rng) ;
212+
213+ let new_state = M :: Params :: collect (
214+ self_
215+ . values ( )
216+ . zip ( first_other. values ( ) )
217+ . zip ( second_other. values ( ) )
218+ . map ( |( ( self_, first_other) , second_other) | {
219+ self_ + gamma * ( first_other - second_other)
220+ } ) ,
221+ ) ;
222+
223+ ( new_state, 0. )
224+ }
225+ }
226+
227+ /// TODO
228+ pub struct Mixture < W , M > ( WeightedAliasIndex < W > , M )
229+ where
230+ W : AliasableWeight ;
231+
232+ macro_rules! impl_mixture {
233+ ( $( $types: ident @ $weights: ident) ,+ ) => {
234+ impl <W , $( $types ) ,+> From <( $( ( $types, W ) ) ,+ ) > for Mixture <W , ( $( $types ) ,+ ) > where W : AliasableWeight {
235+ #[ allow( non_snake_case) ]
236+ fn from( ( $( ( $types, $weights ) ) ,+ ) : ( $( ( $types, W ) ) ,+ ) ) -> Self {
237+ let index = WeightedAliasIndex :: new( vec![ $( $weights ) ,+] ) . unwrap( ) ;
238+
239+ Self ( index, ( $( $types ) ,+ ) )
240+ }
241+ }
242+
243+ impl <W , $( $types ) ,+, M > Move <M > for Mixture <W , ( $( $types ) ,+ ) >
244+ where
245+ W : AliasableWeight ,
246+ M : Model ,
247+ $( $types: Move <M > ) ,+
248+ {
249+ #[ allow( non_snake_case) ]
250+ fn propose<' a, O , R >( & self , self_: & ' a M :: Params , other: O , rng: & mut R ) -> ( M :: Params , f64 )
251+ where
252+ O : FnMut ( & mut R ) -> & ' a M :: Params ,
253+ R : Rng ,
254+ {
255+ let Self ( index, ( $( $types ) ,+ ) ) = self ;
256+
257+ let chosen_index = index. sample( rng) ;
258+
259+ let mut index = 0 ;
260+
261+ $(
262+
263+ #[ allow( unused_assignments) ]
264+ if index == chosen_index {
265+ return $types. propose( self_, other, rng)
266+ } else {
267+ index += 1 ;
268+ }
269+
270+ ) +
271+
272+ unreachable!( )
273+ }
274+ }
275+ } ;
276+ }
277+
278+ impl_mixture ! ( A @ a, B @ b) ;
279+ impl_mixture ! ( A @ a, B @ b, C @ c) ;
280+ impl_mixture ! ( A @ a, B @ b, C @ c, D @ d) ;
281+ impl_mixture ! ( A @ a, B @ b, C @ c, D @ d, E @ e) ;
282+ impl_mixture ! ( A @ a, B @ b, C @ c, D @ d, E @ e, F @ f) ;
283+ impl_mixture ! ( A @ a, B @ b, C @ c, D @ d, E @ e, F @ f, G @ g) ;
284+ impl_mixture ! ( A @ a, B @ b, C @ c, D @ d, E @ e, F @ f, G @ g, H @ h) ;
285+ impl_mixture ! ( A @ a, B @ b, C @ c, D @ d, E @ e, F @ f, G @ g, H @ h, I @ i) ;
286+ impl_mixture ! ( A @ a, B @ b, C @ c, D @ d, E @ e, F @ f, G @ g, H @ h, I @ i, J @ j) ;
287+
120288/// Models are defined by the type of their parameters and their probability functions
121289pub trait Model : Send + Sync {
122290 /// Type used to store the model parameters, e.g. `[f64; N]` or `Vec<f64>`
@@ -126,9 +294,6 @@ pub trait Model: Send + Sync {
126294 ///
127295 /// The sampler will only ever consider differences of these values, i.e. any addititive constant that does _not_ depend on `state` can be omitted when computing them.
128296 fn log_prob ( & self , state : & Self :: Params ) -> f64 ;
129-
130- /// Scale parameter for stretch moves
131- const SCALE : f64 = 2. ;
132297}
133298
134299/// Runs the sampler on the given [`model`][Model] using the chosen [`schedule`][Schedule] and [`execution`][Execution] strategy
@@ -138,17 +303,19 @@ pub trait Model: Send + Sync {
138303/// The number of walkers must be non-zero, even and at least twice the number of parameters.
139304///
140305/// A vector of samples and the number of accepted moves are returned.
141- pub fn sample < M , W , R , S , E > (
142- model : & M ,
306+ pub fn sample < MD , MV , W , R , S , E > (
307+ model : & MD ,
308+ move_ : & MV ,
143309 walkers : W ,
144310 mut schedule : S ,
145311 execution : E ,
146- ) -> ( Vec < M :: Params > , usize )
312+ ) -> ( Vec < MD :: Params > , usize )
147313where
148- M : Model ,
149- W : Iterator < Item = ( M :: Params , R ) > ,
314+ MD : Model ,
315+ MV : Move < MD > + Send + Sync ,
316+ W : Iterator < Item = ( MD :: Params , R ) > ,
150317 R : Rng + Send + Sync ,
151- S : Schedule < M :: Params > ,
318+ S : Schedule < MD :: Params > ,
152319 E : Execution ,
153320{
154321 let mut walkers = walkers
@@ -166,10 +333,8 @@ where
166333
167334 let random_index = Uniform :: new ( 0 , half) . unwrap ( ) ;
168335
169- let update_walker = move |walker : & mut Walker < M , R > , other_walkers : & [ Walker < M , R > ] | {
170- let other = & other_walkers[ random_index. sample ( & mut walker. rng ) ] ;
171-
172- walker. move_ ( model, other)
336+ let update_walker = move |walker : & mut Walker < MD , R > , other_walkers : & [ Walker < MD , R > ] | {
337+ walker. move_ ( model, move_, |rng| & other_walkers[ random_index. sample ( rng) ] )
173338 } ;
174339
175340 while schedule. next_step ( & chain) . is_continue ( ) {
@@ -187,22 +352,22 @@ where
187352 ( chain, accepted)
188353}
189354
190- struct Walker < M , R >
355+ struct Walker < MD , R >
191356where
192- M : Model ,
357+ MD : Model ,
193358{
194- state : M :: Params ,
359+ state : MD :: Params ,
195360 log_prob : f64 ,
196361 rng : R ,
197362 accepted : usize ,
198363}
199364
200- impl < M , R > Walker < M , R >
365+ impl < MD , R > Walker < MD , R >
201366where
202- M : Model ,
367+ MD : Model ,
203368 R : Rng ,
204369{
205- fn new ( model : & M , state : M :: Params , rng : R ) -> Self {
370+ fn new ( model : & MD , state : MD :: Params , rng : R ) -> Self {
206371 let log_prob = model. log_prob ( & state) ;
207372
208373 Self {
@@ -213,20 +378,17 @@ where
213378 }
214379 }
215380
216- fn move_ ( & mut self , model : & M , other : & Self ) -> M :: Params {
217- let z = ( ( M :: SCALE - 1. ) * gen_unit ( & mut self . rng ) + 1. ) . powi ( 2 ) / M :: SCALE ;
218-
219- let mut new_state = M :: Params :: collect (
220- self . state
221- . values ( )
222- . zip ( other. state . values ( ) )
223- . map ( |( self_, other) | other - z * ( other - self_) ) ,
224- ) ;
381+ fn move_ < ' a , MV , O > ( & ' a mut self , model : & MD , move_ : & MV , mut other : O ) -> MD :: Params
382+ where
383+ MV : Move < MD > ,
384+ O : FnMut ( & mut R ) -> & ' a Self ,
385+ {
386+ let ( mut new_state, factor) =
387+ move_. propose ( & self . state , |rng| & other ( rng) . state , & mut self . rng ) ;
225388
226389 let new_log_prob = model. log_prob ( & new_state) ;
227390
228- let log_prob_diff =
229- ( new_state. dimension ( ) - 1 ) as f64 * z. ln ( ) + new_log_prob - self . log_prob ;
391+ let log_prob_diff = factor + new_log_prob - self . log_prob ;
230392
231393 if log_prob_diff > gen_unit ( & mut self . rng ) . ln ( ) {
232394 self . state . clone_from ( & new_state) ;
@@ -380,7 +542,7 @@ where
380542/// Runs the inner `schedule` after calling the given `callback`
381543///
382544/// ```
383- /// # use hammer_and_sample::{sample, MinChainLen, Model, Schedule, Serial, WithProgress};
545+ /// # use hammer_and_sample::{sample, MinChainLen, Model, Schedule, Serial, Stretch, WithProgress};
384546/// # use rand::SeedableRng;
385547/// # use rand_pcg::Pcg64Mcg;
386548/// #
@@ -407,7 +569,7 @@ where
407569/// callback: |chain: &[_]| eprintln!("{} %", 100 * chain.len() / 100_000),
408570/// };
409571///
410- /// let (chain, accepted) = sample(&model, walkers, schedule, Serial);
572+ /// let (chain, accepted) = sample(&model, &Stretch::default(), walkers, schedule, Serial);
411573/// ```
412574pub struct WithProgress < S , C > {
413575 /// The inner schedule which determines the number of iterations
0 commit comments