3
3
//! Simplistic MCMC ensemble sampler based on [emcee](https://emcee.readthedocs.io/), the MCMC hammer
4
4
//!
5
5
//! ```
6
- //! use hammer_and_sample::{sample, MinChainLen, Model, Serial};
6
+ //! use hammer_and_sample::{sample, MinChainLen, Model, Serial, Stretch };
7
7
//! use rand::{Rng, SeedableRng};
8
8
//! use rand_pcg::Pcg64;
9
9
//!
39
39
//! ([p], rng)
40
40
//! });
41
41
//!
42
- //! let (chain, _accepted) = sample(&model, walkers, MinChainLen(10 * 1000), Serial);
42
+ //! let (chain, _accepted) = sample(&model, &Stretch::default(), walkers, MinChainLen(10 * 1000), Serial);
43
43
//!
44
44
//! // 100 iterations of 10 walkers as burn-in
45
45
//! let chain = &chain[10 * 100..];
48
48
//! }
49
49
//! ```
50
50
use std:: ops:: ControlFlow ;
51
+ use std:: ptr;
51
52
52
53
use rand:: {
53
54
distr:: { Distribution , StandardUniform , Uniform } ,
54
55
Rng ,
55
56
} ;
57
+ use rand_distr:: {
58
+ weighted:: { AliasableWeight , WeightedAliasIndex } ,
59
+ Normal ,
60
+ } ;
56
61
#[ cfg( feature = "rayon" ) ]
57
62
use rayon:: iter:: { IntoParallelRefMutIterator , ParallelExtend , ParallelIterator } ;
58
63
@@ -117,6 +122,169 @@ impl Params for Box<[f64]> {
117
122
}
118
123
}
119
124
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
+
120
288
/// Models are defined by the type of their parameters and their probability functions
121
289
pub trait Model : Send + Sync {
122
290
/// Type used to store the model parameters, e.g. `[f64; N]` or `Vec<f64>`
@@ -126,9 +294,6 @@ pub trait Model: Send + Sync {
126
294
///
127
295
/// 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.
128
296
fn log_prob ( & self , state : & Self :: Params ) -> f64 ;
129
-
130
- /// Scale parameter for stretch moves
131
- const SCALE : f64 = 2. ;
132
297
}
133
298
134
299
/// 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 {
138
303
/// The number of walkers must be non-zero, even and at least twice the number of parameters.
139
304
///
140
305
/// 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 ,
143
309
walkers : W ,
144
310
mut schedule : S ,
145
311
execution : E ,
146
- ) -> ( Vec < M :: Params > , usize )
312
+ ) -> ( Vec < MD :: Params > , usize )
147
313
where
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 ) > ,
150
317
R : Rng + Send + Sync ,
151
- S : Schedule < M :: Params > ,
318
+ S : Schedule < MD :: Params > ,
152
319
E : Execution ,
153
320
{
154
321
let mut walkers = walkers
@@ -166,10 +333,8 @@ where
166
333
167
334
let random_index = Uniform :: new ( 0 , half) . unwrap ( ) ;
168
335
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) ] )
173
338
} ;
174
339
175
340
while schedule. next_step ( & chain) . is_continue ( ) {
@@ -187,22 +352,22 @@ where
187
352
( chain, accepted)
188
353
}
189
354
190
- struct Walker < M , R >
355
+ struct Walker < MD , R >
191
356
where
192
- M : Model ,
357
+ MD : Model ,
193
358
{
194
- state : M :: Params ,
359
+ state : MD :: Params ,
195
360
log_prob : f64 ,
196
361
rng : R ,
197
362
accepted : usize ,
198
363
}
199
364
200
- impl < M , R > Walker < M , R >
365
+ impl < MD , R > Walker < MD , R >
201
366
where
202
- M : Model ,
367
+ MD : Model ,
203
368
R : Rng ,
204
369
{
205
- fn new ( model : & M , state : M :: Params , rng : R ) -> Self {
370
+ fn new ( model : & MD , state : MD :: Params , rng : R ) -> Self {
206
371
let log_prob = model. log_prob ( & state) ;
207
372
208
373
Self {
@@ -213,20 +378,17 @@ where
213
378
}
214
379
}
215
380
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 ) ;
225
388
226
389
let new_log_prob = model. log_prob ( & new_state) ;
227
390
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 ;
230
392
231
393
if log_prob_diff > gen_unit ( & mut self . rng ) . ln ( ) {
232
394
self . state . clone_from ( & new_state) ;
@@ -380,7 +542,7 @@ where
380
542
/// Runs the inner `schedule` after calling the given `callback`
381
543
///
382
544
/// ```
383
- /// # use hammer_and_sample::{sample, MinChainLen, Model, Schedule, Serial, WithProgress};
545
+ /// # use hammer_and_sample::{sample, MinChainLen, Model, Schedule, Serial, Stretch, WithProgress};
384
546
/// # use rand::SeedableRng;
385
547
/// # use rand_pcg::Pcg64Mcg;
386
548
/// #
@@ -407,7 +569,7 @@ where
407
569
/// callback: |chain: &[_]| eprintln!("{} %", 100 * chain.len() / 100_000),
408
570
/// };
409
571
///
410
- /// let (chain, accepted) = sample(&model, walkers, schedule, Serial);
572
+ /// let (chain, accepted) = sample(&model, &Stretch::default(), walkers, schedule, Serial);
411
573
/// ```
412
574
pub struct WithProgress < S , C > {
413
575
/// The inner schedule which determines the number of iterations
0 commit comments