-
Notifications
You must be signed in to change notification settings - Fork 1
/
isis_emcee.sl
2364 lines (2035 loc) · 77.1 KB
/
isis_emcee.sl
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% v. 0.9.2 -- Sept. 12, 2016
%%% NOTE: Breaks backward compatability with v0.7.x !!!
%%% v0.8.+ uses a new file format for output. Conversion
%%% routine included to change old fits files into new format
% A simple MCMC code for ISIS, based upon the parallel "simple
% stretch" method from "emcee: the MCMC Hammer" by Foreman-Mackey et
% al., (2012); arXiv:1202.3665
% Written by M. Nowak, mnowak@space.mit.edu, with modifications by
% Tobias Beuchert, tobias.beuchert@sternwarte.uni-erlangen.de
% Lia Corrales, lia@space.mit.edu
% Matthias Kuehnel, matthias.kuehnel@sternwarte.uni-erlangen.de
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Some definitions for people with older versions of S-lang
#ifnexists wherefirst
define wherefirst (a)
{
variable i = where (a);
if (length(i))
return i[0];
else
return NULL;
}
#endif
#ifnexists wherefirstmax
public define wherefirstmax(a)
{
return wherefirst (a==max(a));
}
#endif
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set the free model parameters from an array of parameter values.
% Return a 1 if any of the steps violates a parameter boundary
private define set_pars(fp,x)
{
variable i;
_for i (0,length(x)-1,1)
{
if( x[i] < get_par_info(fp[i]).min ||
x[i] > get_par_info(fp[i]).max )
{
return 1;
}
else
{
set_par(fp[i],x[i]);
}
}
return 0;
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Evaluate the log probability difference between the current walker
% and the proposal. This presumes that P(D|M) is given by
% P(M)*exp(-chi^2/2), where P(M) is uniform within the min/max bounds
% of the parameter file, and 0 outside of that range. Note that this
% presumes that for the already known walkers, one has the fit
% statistic already calculated (sent via xstat).
private define gauss_prior(priors)
{
% Expected INPUTS:
% priors = struct{parlist, priorlist}
% where
% parlist = list of parameter ids that have priors
% priorlist = list of prior structures with field names "center", "sigma"
% The priors are assumed to be gaussian and are not normalized with respect to the hard limits
%
% OUTPUT:
% Sum of log-probabilities to be added to the log-likelihood of the raw fit statistic (logpn)
% Note that chi^2 stat used in logpn is positive (negative is propogated through dlogpn),
% so this needs to return a positive value. Also do not divide by two because of treatment in logpn
variable i, par, pprob, result = 0.0;
_for i (0,length(priors.parlist)-1, 1)
{
par = get_par(priors.parlist[i]);
pprob = priors.priorlist[i];
result += (par - pprob.mean)^2 / (pprob.sigma^2);
}
%message(sprintf("Adding %.2f to the chi-squared stat", result));
return result;
}
private define logpn(fp,xstat,y,z)
{
% First, deal with priors
variable log_prior = 0.0;
if (qualifier_exists("priors")) log_prior = gauss_prior(qualifier("priors"));
% Now do the rest
variable infoy, ystat=1.e32, dlogpn=-1.e32, fv_hold = Fit_Verbose,
i, nfp = length(fp);
ifnot(set_pars(fp,y))
{
Fit_Verbose = -1;
() = eval_counts(&infoy);
ystat = infoy.statistic + log_prior; % Log-likelihood = log-fitstat + log-priors
%message(sprintf("Total ystat = %.2f", ystat));
dlogpn = (xstat-ystat)/2. + (nfp-1)*log(z);
Fit_Verbose = fv_hold;
}
return dlogpn,ystat;
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Revamped output routine so that it appends the file, rather than
% write it from scratch each time
public define write_chain( fname, nw, freepar, cdf_scl_lo, cdf_scl_hi,
chain, chainstat, chng, pfile )
{
variable i, fp;
if(qualifier_exists("create"))
{
fp = fits_open_file(fname,"c");
%%% First extension: list of free parameters.
%%%
variable extname = "PARAMETERS";
variable colname = ["FREE_PAR"];
variable nrows = length(freepar);
variable ttype = ["J"];
variable tunit = [" parameter indices"];
fits_create_binary_table(fp, extname, nrows, colname, ttype, tunit);
fits_update_key(fp, "PFILE", pfile, "");
fits_update_key(fp, "MODEL", get_fit_fun, "");
variable dlist;
list_data(&dlist);
if(typeof(dlist)==Undefined_Type) dlist=" Data not defined at time of file write";
variable hist_comment =
["This file contains the results of a Markov chain analysis",
"generated by the emcee hammer subroutine",
"This extension contains information about the model",
"PFILE are the parameter files that started the chain",
"MODEL is the fit function that was applied to the data",
"FREE_PAR are the parameter indices of the free parameters",
"The following is the list of data fit:","",
strchop(dlist,'\n',0)
];
array_map(Void_Type, &fits_write_comment, fp, hist_comment);
if(_fits_write_col(fp,fits_get_colnum(fp,"FREE_PAR"),1,1,freepar))
throw IOError;
%%% Second extension: chain results for each walker/parameter
%%%
extname = "MCMCCHAIN";
colname = ["FITSTAT","UPDATE"], ttype = ["D","J"],
tunit = [" fit statistics"," update indicator"];
nrows = length(chainstat);
variable nfrpar = length(freepar);
variable nsteps = length(chainstat[*,0]);
_for i (0,length(freepar)-1,1)
{
colname = [colname,"CHAINS"+string(freepar[i])];
ttype = [ttype,"D"];
tunit = [tunit, " parameter values"];
}
fits_create_binary_table(fp, extname, nrows, colname, ttype, tunit);
fits_update_key(fp, "NWALKERS", nw, "");
fits_update_key(fp, "NFREEPAR", nfrpar, "");
fits_update_key(fp, "NSTEPS", nsteps, "");
fits_update_key(fp, "CDF_SCL_LO", cdf_scl_lo, "");
fits_update_key(fp, "CDF_SCL_HI", cdf_scl_hi, "");
hist_comment =
["A Markov chain generated by the emcee hammer subroutine",
"NWALKERS is the number of walkers *per* free parameter",
"NFREEPAR is the number of free parameters",
"NSTEPS is the number of iterations for each walker",
"CDF_SCL_LO: The step amplitude distribution goes as 1/sqrt(z),",
"CDF_SCL_HI: bounded by z = 1/CDF_SCL_LO -> CDF_SCL_HI","",
"The following file columns are the results unpacked",
"as 1D vectors of length NWALKERS*NFREEPAR*NSTEPS:","",
"FITSTAT contains the vector of walker fit statistics",
"UPDATE is a yes/no answer as to whether a walker updated",
"CHAINS# are the values for the free parameter given by",
"parameter index #"
];
array_map(Void_Type, &fits_write_comment, fp, hist_comment);
_for i (0,nfrpar-1,1)
{
if(_fits_write_col(fp,
fits_get_colnum(fp,"CHAINS"+string(freepar[i])),1,1,chain[i,*]))
throw IOError;
}
_for i (0,nsteps-1,1)
{
if(_fits_write_col(fp,fits_get_colnum(fp,"FITSTAT"),1+i*nw*nfrpar,1,chainstat[i,*]))
throw IOError;
if(_fits_write_col(fp,fits_get_colnum(fp,"UPDATE"),1+i*nw*nfrpar,1,chng[i,*]))
throw IOError;
}
%%% Third extension: chain statistics at each iteration
%%%
extname = "CHAINSTATS";
colname = ["FRAC_UPDATE","MIN_STAT","MED_STAT","MAX_STAT"];
nrows = length(chainstat[*,0]);
ttype = ["D","D","D","D"];
tunit = [" fraction"," chi2"," chi2"," chi2"];
fits_create_binary_table(fp, extname, nrows, colname, ttype, tunit);
hist_comment =
["This extension contains some useful summary information",
"for the individual chain steps",
"FRAC_UPDATE is the fraction of walkers that updated",
"MIN_STAT: minimum chi2 for a given step",
"MED_STAT: median chi2 for a given step",
"MAX_STAT: maximum chi2 for a given step"
];
array_map(Void_Type, &fits_write_comment, fp, hist_comment);
variable update=Double_Type[nrows], mnstat=@update, mdstat=@update, mxstat=@update;
_for i (0,nrows-1,1)
{
update[i] = sum(chng[i,*])/length(chng[i,*]);
mnstat[i] = min(chainstat[i,*]);
mdstat[i] = median(chainstat[i,*]);
mxstat[i] = max(chainstat[i,*]);
}
if(_fits_write_col(fp,fits_get_colnum(fp,"FRAC_UPDATE"),1,1,update))
throw IOError;
if(_fits_write_col(fp,fits_get_colnum(fp,"MIN_STAT"),1,1,mnstat))
throw IOError;
if(_fits_write_col(fp,fits_get_colnum(fp,"MED_STAT"),1,1,mdstat))
throw IOError;
if(_fits_write_col(fp,fits_get_colnum(fp,"MAX_STAT"),1,1,mxstat))
throw IOError;
}
else
{
%%% Second extension (first unchanged): chain results
%%%
fp = fits_open_file(fname+"[MCMCCHAIN]","w");
variable nsteps_prev = fits_read_key(fname+"[MCMCCHAIN]","NSTEPS");
nfrpar = length(freepar);
nsteps = length(chainstat[*,0]);
nrows = nsteps_prev*nfrpar*nw;
_for i (0,nfrpar-1,1)
{
if(_fits_write_col(fp,fits_get_colnum(fp,"CHAINS"+string(freepar[i])),
nrows+1,1,chain[i,*]))
throw IOError;
}
_for i (0,nsteps-1,1)
{
if(_fits_write_col(fp,fits_get_colnum(fp,"FITSTAT"),nrows+1+i*nw*nfrpar,1,chainstat[i,*]))
throw IOError;
if(_fits_write_col(fp,fits_get_colnum(fp,"UPDATE"),nrows+1+i*nw*nfrpar,1,chng[i,*]))
throw IOError;
}
fits_update_key(fp, "NSTEPS", nsteps+nsteps_prev, "");
%%% Third extension: chain statistics
%%%
fp = fits_open_file(fname+"[CHAINSTATS]","w");
nrows = length(chainstat[*,0]);
update=Double_Type[nrows], mnstat=@update, mdstat=@update, mxstat=@update;
_for i (0,nrows-1,1)
{
update[i] = sum(chng[i,*])/length(chng[i,*]);
mnstat[i] = min(chainstat[i,*]);
mdstat[i] = median(chainstat[i,*]);
mxstat[i] = max(chainstat[i,*]);
}
if(_fits_write_col(fp,fits_get_colnum(fp,"FRAC_UPDATE"),nsteps_prev+1,1,update))
throw IOError;
if(_fits_write_col(fp,fits_get_colnum(fp,"MIN_STAT"),nsteps_prev+1,1,mnstat))
throw IOError;
if(_fits_write_col(fp,fits_get_colnum(fp,"MED_STAT"),nsteps_prev+1,1,mdstat))
throw IOError;
if(_fits_write_col(fp,fits_get_colnum(fp,"MAX_STAT"),nsteps_prev+1,1,mxstat))
throw IOError;
}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
private variable fs = stderr;
% A subroutine to read out a chain from a FITS file, of the format
% from the subroutine above. If the qualifier init_walker is set, it
% will spit out an array suitable for restarting the chain.
public define old_read_chain()
{
if(_NARGS==1)
{
variable fname = ();
}
else
{
() = fprintf(fs, "%s\n", %{{{
`
(nw, nfreepar, freepar, chain) = old_read_chain(fname);
(nw, nfreepar, freepar,
cdf_scl_lo, cdf_scl_hi,
chain, chain_statistic,
update_indicator, pfile,
walkers_init, statistic_init) = old_read_chain(fname; init_walker);
frac_update = old_read_chain(fname; frac_update);
Read the MCMC results stored in a fits file of the format produced
by versions <0.7 of this code. Normally, it will return just the
minimum results required for plotting. Qualifiers, however, can be
used to have it return enough information to initialize a chain, or
just return an array that has the fraction of walkers updated at
each step.
`); %}}}
return;
}
variable nw, nfreepar, freepar, cdf_scl_lo, cdf_scl_hi, pfile,
chain, chainstat, chng, frac_update, statinit;
(nw, nfreepar, pfile, cdf_scl_lo, cdf_scl_hi ) =
fits_read_key(fname+"[MCMCCHAIN]","NWALKERS","NFREEPAR","PFILE",
"CDF_SCL_LO","CDF_SCL_HI");
(freepar, chain) = fits_read_col(fname+"[MCMCCHAIN]",
"FREE_PAR","CHAIN" );
chainstat = fits_read_col(fname+"[CHAINSTEPS]","FITSTAT");
chng = fits_read_col(fname+"[CHAINSTEPS]","UPDATE");
frac_update = fits_read_col(fname+"[CHAINSTEPS]","FRAC_UPDATE");
if(qualifier_exists("init_walker"))
{
variable iwalk = Double_Type[nfreepar,nw*nfreepar];
variable clength = length(chain[0,*]);
iwalk = chain[*,[clength-nw*nfreepar:clength-1]];
statinit = chainstat[-1,*];
return nw, nfreepar, freepar, cdf_scl_lo, cdf_scl_hi,
chain, chainstat, chng, pfile, iwalk, statinit;
}
else if(qualifier_exists("frac_update"))
{
return frac_update;
}
else
{
return nw, nfreepar, freepar, chain;
}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
public define old_to_new_chain()
{
if(_NARGS==2)
{
variable fname_old, fname_new;
(fname_old, fname_new) = ();
}
else
{
() = fprintf(fs, "%s\n", %{{{
`
old_to_new_chain(fname_old,fname_new);
Takes the chain results stored in a version <= 0.7.x file,
fname_old, and writes them to a version >= 0.8.0 file, fname_new.
`); %}}}
return;
}
variable nw, nfreepar, freepar, cdf_scl_lo, cdf_scl_hi, chain,
chain_statistic, update_indicator, pfile;
(nw, nfreepar, freepar, cdf_scl_lo, cdf_scl_hi,
chain, chain_statistic, update_indicator, pfile, , ) =
old_read_chain(fname_old; init_walker);
write_chain(fname_new, nw, freepar, cdf_scl_lo, cdf_scl_hi, chain,
chain_statistic, update_indicator, pfile; create); }
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
private variable fs = stderr;
% A subroutine to read out a chain from a FITS file, of the format
% from the subroutine above. If the qualifier init_walker is set, it
% will spit out an array suitable for restarting the chain.
public define read_chain()
{
if(_NARGS==1)
{
variable fname = ();
}
else
{
() = fprintf(fs, "%s\n", %{{{
`
(nw, nfreepar, freepar,
chain_statistic, chain) = read_chain(fname);
(nw, nfreepar, freepar,
cdf_scl_lo, cdf_scl_hi,
pfile, walkers_init,
statistic_init, change) = read_chain(fname; init_walker);
frac_update = read_chain(fname; frac_update);
(frac_update, min_statistic,
med_statistic, max_statistic) = read_chain(fname; chain_stats);
Read the MCMC results stored in a fits file. Normally, it will
return just the minimum results required for plotting. Qualifiers,
however, can be used to have it return enough information to
initialize a chain, return an array that has the fraction of
walkers updated at each step, or return the fractional update array
along with the min, median, and maximum value of the statistic at
each step.
`); %}}}
return;
}
variable i, nw, nfreepar, nsteps, cdf_scl_lo, cdf_scl_hi, pfile,
freepar, frac_update, chain, chain_stat, chain_chng,
tmp_chain, tmp_stat, tmp_chng, indces;
variable statinit, walkinit;
(pfile) = fits_read_key(fname+"[PARAMETERS]","PFILE");
(nw, nfreepar, nsteps, cdf_scl_lo, cdf_scl_hi ) =
fits_read_key(fname+"[MCMCCHAIN]","NWALKERS","NFREEPAR","NSTEPS",
"CDF_SCL_LO","CDF_SCL_HI");
freepar = fits_read_col(fname+"[PARAMETERS]","FREE_PAR");
if( qualifier_exists("init_walker") )
{
chain = Double_Type[nfreepar,nw*nfreepar];
indces = [nsteps*nw*nfreepar-nw*nfreepar:nsteps*nw*nfreepar-1];
_for i (0,nfreepar-1,1)
{
tmp_chain = fits_read_col(fname+"[MCMCCHAIN]","CHAINS"+string(freepar[i]));
chain[i,*] = tmp_chain[indces];
() = __tmp(tmp_chain);
}
tmp_stat = fits_read_col(fname+"[MCMCCHAIN]","FITSTAT");
chain_stat = tmp_stat[indces];
() = __tmp(tmp_stat);
tmp_chng = fits_read_col(fname+"[MCMCCHAIN]","UPDATE");
chain_chng = tmp_chng[indces];
() = __tmp(tmp_chng);
return nw, nfreepar, freepar, cdf_scl_lo, cdf_scl_hi, pfile,
chain, chain_stat, chain_chng;
}
else if(qualifier_exists("frac_update"))
{
frac_update = fits_read_col(fname+"[CHAINSTATS]","FRAC_UPDATE");
return frac_update;
}
else if(qualifier_exists("chain_stats"))
{
variable min_statistic, med_statistic, max_statistic;
(frac_update, min_statistic,
med_statistic, max_statistic)=fits_read_col(fname+"[CHAINSTATS]",
"FRAC_UPDATE", "MIN_STAT",
"MED_STAT", "MAX_STAT" );
return frac_update, min_statistic, med_statistic, max_statistic;
}
else
{
chain = Double_Type[nfreepar,nsteps*nw*nfreepar];
_for i (0,nfreepar-1,1)
{
chain[i,*] = fits_read_col(fname+"[MCMCCHAIN]","CHAINS"+string(freepar[i]));
}
chain_stat = fits_read_col(fname+"[MCMCCHAIN]","FITSTAT");
reshape(chain_stat,[nsteps,nw*nfreepar]);
return nw, nfreepar, freepar, chain_stat, chain;
}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The inverse of the Cumulative Distribution Function for 1/sqrt(z),
% if 1/a <= z <= b, to use as a random number generator for a
% 1/sqrt(z) probability distribution. Parameter steps will have an
% amplitude governed by random draws from this distribution.
private define icdf(x,a,b)
{
variable c1 = 1/(sqrt(a*b)-1);
variable c2 = 1/c1^2/a;
return c2*(x+c1)^2;
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Return an array with the indices of the free parameters
private define free_par()
{
variable i, free_par = Integer_Type[0];
_for i (1,get_num_pars,1)
{
if(get_par_info(i).freeze == 0 &&
get_par_info(i).tie == NULL)
{
free_par = [free_par,i];
}
}
return free_par;
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialize nw walkers *per free parameter*, whose indices are in fp.
% For now, we will initialize uniformly, or as a gaussian, over the
% range given for the min/max values of the free parameters, or over
% the min/max values for an input parameter file, both modulo a scale
% factor (==1 for full min/max range, uniform draw)
private define init_walker(fp,nw)
{
variable npfile=1, fname = "/tmp/mcmc_pfile_"+string(getpid)+".par";
try{
save_par(fname);
}
catch AnyError: {
() = printf("\n\n Failed saving initial parameters \n\n");
plot_pause;
}
if(qualifier_exists("pfile"))
{
variable pfile_init, pfiles = strchop(qualifier("pfile"),';',0);
npfile = length(pfiles);
try{
foreach pfile_init (pfiles)
{
load_par(pfile_init);
}
}
catch AnyError: {
() = printf("\n\n Cannot read parameter file: %s \n",pfile_init);
() = printf(" Retaining original parameter file for initialization. \n\n");
npfile = 1;
pfiles = [fname];
load_par(fname);
}
}
else
{
pfiles = [fname];
}
variable sc, sig;
if(qualifier_exists("gaussian"))
{
sc = qualifier("scale",1./3.);
}
else
{
sc = qualifier("scale",1.);
}
variable fv_hold = Fit_Verbose;
Fit_Verbose = -1;
% The walkers are 2D arrays, with the first index covering the free
% parameters, and the second index being the specific instances
% (i.e., the length of the 2nd index is the number of walkers).
variable i, j, k, info, nfp = length(fp),
xp = Double_Type[nfp, npfile], xl=@xp, xh=@xp,
xstrt = Double_Type[nfp,nw*nfp],
xstat = Double_Type[nw*nfp];
_for k (0,npfile-1,1)
{
load_par(pfiles[k]);
() = eval_counts;
_for i (0,nfp-1,1)
{
xp[i,k] = get_par_info(fp[i]).value;
xl[i,k] = get_par_info(fp[i]).min;
xh[i,k] = get_par_info(fp[i]).max;
}
}
% Reload the original parameter file, which should have the widest
% allowable min/max values (enough to encompass any ranges present
% in the input parameter files)
if(qualifier_exists("pfile"))
{
try{
load_par(fname);
}
catch AnyError: {
() = printf("\n\n Failed reloading original parameters \n\n");
plot_pause;
}
if(eval_counts)
{
() = printf("\n\n Failed evaluating original parameters \n\n");
plot_pause;
}
}
_for j (0,nw*nfp-1,1)
{
k = j*npfile/(nw*nfp);
_for i (0,nfp-1,1)
{
if(qualifier_exists("gaussian"))
{
sig = (@(qualifier("grnd", &grand)))();
if(sig < 0)
{
xstrt[i,j] = xp[i,k] + sig*sc*(xp[i,k]-xl[i,k]);
}
else
{
xstrt[i,j] = xp[i,k] + sig*sc*(xh[i,k]-xp[i,k]);
}
}
else
{
xstrt[i,j] = (1-sc)*xp[i,k] + sc*(xl[i,k]+(xh[i,k]-xl[i,k])*(@(qualifier("urnd", &urand)))());
}
if(xstrt[i,j]<xl[i,k]) xstrt[i,j] = xl[i,k];
if(xstrt[i,j]>xh[i,k]) xstrt[i,j] = xh[i,k];
set_par(fp[i],xstrt[i,j]);
}
() = eval_counts(&info);
variable stat = info.statistic;
if (qualifier_exists("priors"))
{
stat += gauss_prior(qualifier("priors"));
}
xstat[j] = stat;
}
Fit_Verbose = fv_hold;
return xstrt, xstat;
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The function to create a proposition (i.e., the new trial
% parameters), and test whether or not that proposition is accepted.
private define update_walker(cdf_scl_lo,cdf_scl_hi,rnd,fp,xa,xstat,xb)
{
% xa is a vector of parameters for a specific walker to be updated,
% while xstat is the fit statistic of that walker. xb is an array
% of walker parameters (a second, independent group) from which an
% update is drawn. The first index of xb spans the parameter,
% while the second spans specific walker instances.
variable lb = length(xb[0,*]); % No. of walkers
variable xuse = xb[*,int(rnd[0]*lb)]; % Choose one
variable z = icdf(rnd[1],cdf_scl_lo,cdf_scl_hi); % Random step size
% New trial parameters
xuse += z*(xa-xuse);
%variable priors = qualifier("priors",0);
variable dlogpn, ystat;
(dlogpn,ystat) = logpn(fp,xstat,xuse,z;; __qualifiers);
variable ptest = log(rnd[2]);
if(ptest <= dlogpn)
{
return xuse, ystat, 1; % 1 = changed value
}
else
{
return xa, xstat, 0; % 0 = same value
}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This variable will be used to communicate with the slaves running
% the code in parallel, as well as receive their results.
private variable Task_List =
struct{ index, length, rands, free_par, walkers, wstats, change,
proposals, output };
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This is the function that the slaves will be running. It will
% continously loop, receiving instructions, running the walker update
% for a specific index, and spitting back the results, until it gets
% sent a negative index.
private define slave_task(s, k, cdf_scl_lo, cdf_scl_hi)
{
send_msg(s, SLAVE_READY);
% message("Slave "+string(k)+" Starting");
variable robjs, index, rands, freepar, walkers, wstats, props,
output, nstat, chng;
forever
{
robjs = recv_objs (s);
index = robjs[0];
if(index < 0) break;
rands = robjs[1]; % Vector of three random numbers
freepar = robjs[2]; % Vector of free parameter indices
walkers = robjs[3]; % Parameter vector for a single walker
wstats = robjs[4]; % Fit statistic for above walker
props = robjs[5]; % Parameter vectors for walker group
%variable priors = qualifier("priors", 0);
(output, nstat, chng) = update_walker(cdf_scl_lo, cdf_scl_hi, rands,
freepar, walkers, wstats, props;; __qualifiers);
send_msg (s, SLAVE_RESULT);
send_objs (s, index, output, nstat, chng);
}
% message("Slave "+string(k)+" Ending");
return 0;
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Stolen from the conf_loop.sl script in the ISIS distribution (in the
% .../isis-[version-minorversion]/share directory). This function is
% for the parallelized version of the code. Once all slaves are
% finished (i.e., show a SLAVE_READY status), shut them down by
% sending a negative index
private define maybe_finished (slaves)
{
variable s;
foreach s (slaves)
{
if (s.status != SLAVE_READY) return;
}
foreach s (slaves)
{
send_objs (s, -1);
}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% A function to send tasks (indices, walker arrays, random number
% arrays, etc.) to the slaves running in parallel
private define send_next_task (s)
{
if(Task_List.index < Task_List.length)
{
variable index, rands, freepar, walker, wstat, props;
index = Task_List.index;
rands = Task_List.rands[index];
freepar = Task_List.free_par;
walker = Task_List.walkers[index];
wstat = Task_List.wstats[index];
props = Task_List.proposals;
send_objs (s, index, rands, freepar, walker, wstat, props);
Task_List.index++;
s.status = SLAVE_RUNNING;
}
else maybe_finished (s);
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% A function to receive the results from the slaves. Here the return
% status isn't really necessary, but see the ISIS script conf_loop.sl
% for an example of using a return status to decide whether or not to
% start a new set of slaves.
private define recv_slave_result(s)
{
variable objs = recv_objs(s);
Task_List.output[objs[0]] = objs[1];
Task_List.wstats[objs[0]] = objs[2];
Task_List.change[objs[0]] = objs[3];
s.status = SLAVE_READY;
return 0;
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This is the simple function that manage_slaves will continously loop
% over. It will listen to the slaves and either send them a task, or
% receive a result, and then send them a task. The details of the
% sending and receiving are handled in separate functions.
private define slave_handler(s,msg)
{
switch (msg.type)
{
case SLAVE_READY: send_next_task (s);
}
{
case SLAVE_RESULT:
() = recv_slave_result(s);
send_next_task(s);
}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The function to do the emcee hammer. It takes as input the number
% of walkers per free parameter, and the number of simulations per set
% of walkers. Optionally, it can take a qualifier to read the
% parameter min/max values from other file(s). Or it can be
% initialized from an existing chain.
public define emcee()
{
if(_NARGS==2)
{
variable nw, nsim;
(nw, nsim) = ();
}
else
{
() = fprintf(fs, "%s\n", %{{{
`
emcee( nw, nsim; pfile="file1;file2;...;filen",
scale=#, gaussian,
cdf_scl_lo=#, cdf_scl_hi=#,
init_chain=file,
output=file, sim_count=#,
num_slaves=#, nice=#, serial,
nocopy, priors, urnd=&urand, grnd=&grand );
Create a set of MCMC chains for an ensemble of walkers (i.e.,
propositions) consisting of a number of walkers equal to nw X the
number of free parameters. This ensemble will be evolved for nsim
iterations. All results will be stored in an output file.
The initial distribution of walkers is taken from the current
parameter values, or from the parameter values in the files listed
in pfile (file names, including full paths if not in the local
directory, separated by semi-colons). If the gaussian qualifier is
not set, each walker has its parameters uniformly distributed from
value-scale*(value-min) to value+scale*(max-value). (Default
scale=1.)
Otherwise, the walkers have initial parameters gaussianly
distributed about value with sigma = scale*(max-value) or sigma =
scale*(value-min) (i.e., normalized to the possibly asymmetric
min/max values). (Default scale=1/3.)
Alternatively, the walkers can be initialized from the last
iteration of an existing chain stored in a file, init_chain.
The walkers are split into groups (0) and (1), with the update
proposition (i.e., parameter vector) for the group (0) j^th walker
being:
X(0)'_j = X(1)_k + z*(X(0)_j-X(1)_k)
X(1)_k is randomly drawn from group (1) and z is randomly
distributed as 1/sqrt(z) between values of 1/cdf_scl_lo and
cdf_scl_hi (default for both=2). Group (1) is then subsequently
updated in a similar manner.
The output chain is placed in the file specified by the output
qualifier (default name is mcmc_results_processid.fits).
Intermediate results are written to this file every sim_count
(default=50) iterations. If the chains were started from a previous
chain file, the final output file will contain the initial chains as
well unless the nocopy qualifier has been set.
If num_slaves is specified, the process will be parallelized with a
niceness value of nice for each process. The serial qualifier will
always override this, and force the default behavior of serial
evaluation.
The optional qualifiers grnd and urnd can be set to user defined
functions to, e.g., allow random numbers drawn from a server or file
in case of a manual multi-job run (among several machines).
PRIORS
One can apply gaussian priors to particular parameters by
constructing a structure with the following fields
priors.parlist -- an array of parameter ids
priors.priorlist -- an array of structures describing each prior. A
prior structure needs two fields: 'mean' and 'sigma'
For example:
myprior = struct{mean=0.1, sigma=0.2}
emcee(nw, nsim; priors=struct{parlist=[1], priorlist=[myprior]})
`); %}}}
return;
}
% Store initial parameters so that we can restore them at the end
variable pars = get_params;
variable num_slaves = int(qualifier("num_slaves",1));
if(qualifier_exists("serial")) num_slaves=1;
variable isc=0, sim_count_array, sim_count = int(qualifier("sim_count",50));
if(sim_count > 0) sim_count_array=[0:nsim+sim_count:sim_count];
variable ochain, ostat, ochng;
variable screwup = qualifier("infile","NONE");
screwup = qualifier("in_file",screwup);
screwup = qualifier("start",screwup);
screwup = qualifier("start_file",screwup);
screwup = qualifier("initfile",screwup);
screwup = qualifier("init_file",screwup);
screwup = qualifier("input",screwup);
screwup = qualifier("initchain",screwup);
variable init_chain = qualifier("init_chain",screwup);
if ( screwup != "NONE" )
()=printf("\n *** Using %s for chain initialization *** \n\n",init_chain);
screwup = qualifier("outfile","mcmc_results_");
screwup = qualifier("out_file",screwup);
screwup = qualifier("stop",screwup);
screwup = qualifier("stop_file",screwup);
screwup = qualifier("outchain",screwup);
screwup = qualifier("out_chain",screwup);
variable outfile = qualifier("output",screwup);
if ( outfile == "mcmc_results_" ) outfile += "_"+string(getpid)+".fits";
()=printf("\n *** Using %s for output file *** \n\n",outfile);
variable pfile = qualifier("pfile","NONE");
variable cdf_scl_lo = qualifier("cdf_scl_lo",2.);
variable cdf_scl_hi = qualifier("cdf_scl_hi",2.);
nw = int(nw);
nsim = int(nsim);
variable xwalk, xstat, xwalk_a, xwalk_b, freepar = free_par();
if(init_chain=="NONE")
{