forked from brian-lau/MatlabStan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StanModel.m
1220 lines (1108 loc) · 44 KB
/
StanModel.m
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
% STANMODEL - Class defining a Stan model
%
% obj = StanModel(varargin);
%
% All inputs are passed in using name/value pairs. The name is a string
% followed by the value (described below).
% The order of the pairs does not matter, nor does the case.
%
% The Stan model can be passed in three ways:
% 1) as a file (use the 'file' input)
% 2) as a Matlab string (use the 'model_code' input)
% 3) as a Matlab StanModel object (use the 'fit' input)
%
% ATTRIBUTES
% file - string, optional
% The string passed is the filename containing the Stan model.
% stan_version - [MAJOR MINOR PATCH] w/ Stan version
% This is typically set automatically, but can be set
% explicitly as a vector [MAJOR MINOR PATCH] if needed
% method - string, optional
% {'sample' 'optimize' 'variational'}, default = 'sample'
% model_code - string, optional
% String, or cell array of strings containing Stan model.
% Ignored if 'file' is passed in.
% model_name - string, optional
% Name of the model. default = 'anon_model'
% However, if 'file' is passed in, then the filename is used
% to name the model.
% data - struct
% Data for Stan model. Fieldnames and associated values must
% correspond to Stan variable names values.
% chains - scalar, optional, valid when method = 'sample'
% Number of chains for . Default = 4
% iter - scalar, optional, valid when method = 'sample'
% Number of iterations for each chain. Default = 1000
% warmup - scalar, optional, valid when method = 'sample'
% Number of warmup (aka burnin) iterations. Default = 1000
% thin - scalar, optional, valid when method = 'sample'
% Period for saving samples. Default = 1
% init - scalar, struct or string, optional
% 0 initializes all to be zero on the unconstrained support
% x scalar [-x,+x] uniform initial values
% User-supplied initial values can either be supplied as a
% string pointing to a Rdump file, or as a struct, with fields
% corresponding to parameters to be initialized.
% Default initializes parameters uniformly from (-2,+2)
% seed - scalar, optional
% Random number generator seed. Default = round(sum(100*clock))
% Note that this seed is different from Matlab's RNG seed, and
% is only used to sample from Stan models. For multiple chains
% each chain is seeded according to a deterministic function
% of the provided seed to avoid dependency.
% algorithm - string, optional
% If method = 'sample', {'NUTS','HMC'}, default = 'NUTS'
% If method = 'optimize', {'BFGS','NESTEROV' 'NEWTON'}, default = 'BFGS'
% If method = 'variational', {'MEANFIELD','FULLRANK'}, default = 'MEANFIELD'
% sample_file - string, optional
% Name of file(s) where samples for all parameters are saved.
% Default = 'output.csv'.
% diagnostic_file % not done
% verbose - bool, optional
% Specifies whether output is piped to console. Default = false
% refresh - scalar, optional
% Number of iterations between reports of sampling progress.
% Default = 100.
% stan_home - string, optional
% Parent directory of CmdStan installation.
% Default = directory specified in +mstan/stan_home.m
% working_dir - string, optional
% Directory for reading/writing models/data.
% Default = pwd
% file_overwrite - bool, optional
% Controls whether .stan files are automatically overwritten
% when the model changes. Default = false
% If false, a file dialog is opened when the model is changed
% allowing the user to specify a different filename, or
% manually overwrite the current.
%
% METHODS
% set - Set multiple properties (as name/value pairs)
% compile - string
% One of 'stanc' 'libstan.a' 'libstanc.a' 'print', which
% compiles the corresponding elements of CmdStan.
% Or 'model', which compiles the defined model. Default = 'model'
% optimizing
% sampling
% help
% command - displays the Stan commandline parameters for current model
% model_binary_path - returns the path to C++ binary for current model
% copy - returns a shallow copy of the current model
%
% EXAMPLES
%
% $ Copyright (C) 2014 Brian Lau http://www.subcortex.net/ $
% Released under the BSD license. The license and most recent version
% of the code can be found on GitHub:
% https://github.com/brian-lau/MatlabStan
% TODO
% expose remaining pystan parameters
% dump reader (to load data as struct)
% model definitions
% Windows
% o hash for binary doesn't make sense as dependent
classdef StanModel < handle
properties
stan_home
stan_version
working_dir
id
end
properties(SetAccess = private)
model_home = ''% url or path to .stan file
end
properties(Dependent = true)
file = ''
model_name
model_code
iter
warmup
thin
seed
algorithm
control
inc_warmup
sample_file
diagnostic_file
refresh
end
properties
method
init
data
chains
verbose
file_overwrite
end
properties(SetAccess = private, Dependent = true)
checksum_stan
checksum_binary
command
end
properties(SetAccess = private, Hidden = true)
params
defaults
validators
file_
model_name_
end
properties(SetAccess = protected)
version = '0.9.0';
end
methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Constructor
function self = StanModel(varargin)
p = inputParser;
p.KeepUnmatched = true;
p.FunctionName = 'StanModel constructor';
p.addParamValue('stan_home',mstan.stan_home);
p.addParamValue('stan_version',[],@(x) isnumeric(x) && numel(x)==3);
p.addParamValue('file','');
p.addParamValue('model_name','anon_model');
p.addParamValue('model_code',{});
p.addParamValue('id','',@ischar);
p.addParamValue('working_dir',pwd);
p.addParamValue('method','sample',@(x) any(strcmp(x,...
{'sample' 'optimize' 'variational' 'diagnose'})));
p.addParamValue('chains',4);
p.addParamValue('sample_file','',@ischar);
p.addParamValue('verbose',false,@islogical);
p.addParamValue('file_overwrite',false,@islogical);
p.parse(varargin{:});
self.verbose = p.Results.verbose;
self.file_overwrite = p.Results.file_overwrite;
self.stan_home = p.Results.stan_home;
if ~exist('processManager')
error('StanModel:constructor:MissingFunction',...
'processManager (https://github.com/brian-lau/MatlabProcessManager) is required');
end
if isempty(p.Results.id)
self.random_id();
else
self.id = p.Results.id;
end
if isempty(p.Results.stan_version)
self.stan_version = self.get_stan_version();
else
self.stan_version = p.Results.stan_version;
end
[self.defaults,self.validators] = mstan.stan_params(self.stan_version);
self.params = self.defaults;
if isempty(p.Results.file)
self.file = '';
self.model_name = p.Results.model_name;
self.model_code = p.Results.model_code;
else
self.file = p.Results.file;
end
self.working_dir = p.Results.working_dir;
self.method = p.Results.method;
self.chains = p.Results.chains;
if isempty(p.Results.sample_file)
self.params.output.file = [self.id '-output.csv'];
end
% pass remaining inputs to set()
self.set(p.Unmatched);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function set(self,varargin)
p = inputParser;
p.KeepUnmatched = false;
p.FunctionName = 'StanModel parameter setter';
p.addParamValue('stan_home',self.stan_home);
p.addParamValue('file',self.file);
p.addParamValue('model_name',self.model_name);
p.addParamValue('model_code',self.model_code);
p.addParamValue('id',self.id);
p.addParamValue('working_dir',self.working_dir);
p.addParamValue('method',self.method);
p.addParamValue('sample_file',self.sample_file);
p.addParamValue('iter',self.iter);
p.addParamValue('warmup',self.warmup);
p.addParamValue('thin',self.thin);
p.addParamValue('init',self.init);
p.addParamValue('seed',self.seed);
p.addParamValue('control',self.control);
p.addParamValue('chains',self.chains);
p.addParamValue('inc_warmup',self.inc_warmup);
p.addParamValue('data',[]);
p.addParamValue('verbose',self.verbose);
p.addParamValue('file_overwrite',self.file_overwrite);
p.addParamValue('refresh',self.refresh);
p.parse(varargin{:});
self.verbose = p.Results.verbose;
self.file_overwrite = p.Results.file_overwrite;
self.stan_home = p.Results.stan_home;
if isempty(p.Results.file)
self.model_name = p.Results.model_name;
self.model_code = p.Results.model_code;
else
% Update only if we are not pointing to the same file
if ~strcmp(fullfile(self.model_home,self.file),self.model_path)
self.file = p.Results.file;
end
end
self.working_dir = p.Results.working_dir;
if ~isempty(p.Results.id)
self.id = p.Results.id;
end
self.params.output.file = [self.id '-output.csv'];
self.method = p.Results.method;
self.chains = p.Results.chains;
self.iter = p.Results.iter;
self.warmup = p.Results.warmup;
self.thin = p.Results.thin;
self.init = p.Results.init;
self.seed = p.Results.seed;
self.control = p.Results.control;
self.chains = p.Results.chains;
self.inc_warmup = p.Results.inc_warmup;
self.data = p.Results.data;
self.refresh = p.Results.refresh;
end
function set.stan_home(self,d)
[success,fa] = fileattrib(d);
if ~success
error('StanModel:stan_home:InputFormat',...
'Can''t parse stan_home. Is it set correctly? Check ''mstan.stan_home''');
end
if fa.directory
if exist(fullfile(fa.Name,'makefile'),'file') ...
&& exist(fullfile(fa.Name,'bin'),'dir')
self.stan_home = fa.Name;
else
% TODO make this message more informative
error('StanModel:stan_home:InputFormat',...
'Does not look like a proper stan setup');
end
else
error('StanModel:stan_home:InputFormat',...
'stan_home must be the base directory for stan');
end
end
function set.file(self,fname)
if isempty(fname)
self.update_model('file','');
elseif ischar(fname)
[path,name,ext] = fileparts(fname);
if isempty(path)
fname = fullfile(pwd,fname);
end
if ~exist(fname,'file')
error('StanModel:file:NoFile','File does not exist');
end
self.update_model('file',fname);
else
%error('StanModel:file:InputFormat','file must be a string');
end
end
function file = get.file(self)
file = self.file_;
end
function select_file(self)
[name,path] = uigetfile('*.stan','Name stan model');
self.update_model('file',fullfile(path,name));
end
function set.model_name(self,model_name)
if ischar(model_name) && (numel(model_name)>0)
if isempty(self.file)
self.model_name_ = model_name;
else
self.update_model('model_name',model_name);
end
else
error('stan:model_name:InputFormat',...
'model_name should be a non-empty string');
end
end
function model_name = get.model_name(self)
model_name = self.model_name_;
end
function path = model_path(self)
path = fullfile(self.model_home,[self.model_name '.stan']);
end
function binary_path = model_binary_path(self)
if ispc % FIXME is this necessary in Stan 2.1?
binary_path = fullfile(self.model_home,[self.model_name '.exe']);
else
binary_path = fullfile(self.model_home,self.model_name);
end
end
function bool = is_compiled(self)
bool = false;
if ~isempty(dir(self.model_binary_path))
% MD5
chk = mstan.DataHash(self.model_binary_path,struct('Input','file'));
if strcmp(chk,self.checksum_binary)
bool = true;
end
return;
end
end
function chk = get.checksum_stan(self)
if exist(self.model_path,'file')
chk = mstan.DataHash(self.model_path,struct('Input','file'));
else
chk = '';
end
end
function chk = get.checksum_binary(self)
if exist(self.model_binary_path,'file')
chk = mstan.DataHash(self.model_binary_path,struct('Input','file'));
else
chk = '';
end
end
function set.model_code(self,model)
if isempty(model)
return;
end
if ischar(model)
% Convert a char array into a cell array of strings split by line
model = regexp(model,'(\r\n|\n|\r)','split')';
end
temp = strtrim(model);
if any(strncmp('data',temp,4)) ...
|| any(strncmp('parameters',temp,10))...
|| any(strncmp('model',temp,5))
self.update_model('model_code',model);
else
error('StanModel:model_code:InputFormat',...
'does not look like a stan model');
end
end
function model_code = get.model_code(self)
if isempty(self.file_)%isempty(self.model_home)
model_code = {};
else
% Always reread file? Or checksum? or listen for property change?
% TODO: AbortSet should fix this
model_code = mstan.read_lines(fullfile(self.model_home,self.file));
end
end
function set.model_home(self,d)
if isempty(d)
self.model_home = pwd;
elseif isdir(d)
[~,fa] = fileattrib(d);
if fa.UserWrite && fa.UserExecute
self.model_home = fa.Name;
else
error('StanModel:model_home:NoWritePermission',...
'Must be able to write and execute in model_home');
end
else
error('StanModel:model_home:InputFormat',...
'model_home must be a directory');
end
end
function set.working_dir(self,d)
if isdir(d)
[~,fa] = fileattrib(d);
if fa.directory && fa.UserWrite && fa.UserRead
self.working_dir = fa.Name;
else
self.working_dir = tempdir;
end
else
error('StanModel:working_dir:InputFormat',...
'working_dir must be a directory');
end
end
function set.method(self,method)
assert(ischar(method),'Method must be a string');
method = lower(method);
assert(any(strcmp(method,{'sample','optimize','variational'})),...
'Method must be one of ''sample'', ''optimize'', ''variational''');
if any(strcmp(method,{'optimize' 'variational'}))
self.chains = 1;
end
self.method = method;
end
function set.chains(self,n_chains)
n_processors = java.lang.Runtime.getRuntime.availableProcessors;
if n_chains < 1
fprintf('Setting # of chains = 1\n');
n_chains = 1;
elseif n_chains > n_processors
warning('stan:chains:InputFormat','# of chains > # of cores.');
end
if any(strcmp(self.method,{'optimize' 'variational'}))
self.chains = 1;
else
self.chains = round(n_chains);
end
if self.chains < numel(self.init)
self.init = self.init(1:self.chains);
elseif self.chains > numel(self.init)
% TODO
if isempty(self.init)
self.init = []; % Default
elseif numel(self.init) == 1
self.init(2:n_chains) = self.init;
elseif isstruct(self.init)
temp = num2cell(self.init);
if isequal(temp{:})
self.init(numel(self.init):n_chains) = self.init(1);
else
self.init = [];
end
elseif all(self.init == self.init(1))
self.init(numel(self.init)+1:n_chains) = self.init(1);
else
self.init = []; % Default
end
end
end
function set.refresh(self,refresh)
validateattributes(refresh,self.validators.output.refresh{1},...
self.validators.output.refresh{2})
self.params.output.refresh = refresh;
end
function refresh = get.refresh(self)
refresh = self.params.output.refresh;
end
function set.id(self,id)
if ischar(id) && ~isempty(id)
self.id = id;
% Update the output filename
self.params.output.file = [self.id '-output.csv'];
else
error('bad id');
end
end
function random_id(self)
self.id = mstan.randomUUID('base62');
end
function set.iter(self,iter)
validateattributes(iter,self.validators.sample.num_samples{1},...
self.validators.sample.num_samples{2})
self.params.sample.num_samples = iter;
end
function iter = get.iter(self)
iter = self.params.sample.num_samples;
end
function set.warmup(self,warmup)
validateattributes(warmup,self.validators.sample.num_warmup{1},...
self.validators.sample.num_warmup{2})
self.params.sample.num_warmup = warmup;
end
function warmup = get.warmup(self)
warmup = self.params.sample.num_warmup;
end
function set.thin(self,thin)
validateattributes(thin,self.validators.sample.thin{1},...
self.validators.sample.thin{2})
self.params.sample.thin = thin;
end
function thin = get.thin(self)
thin = self.params.sample.thin;
end
function set.init(self,init)
% Set initial conditions for chains
% Can have different inits for each chain
if isstruct(init) || isa(init,'containers.Map')
nChains = numel(init);
for i = 1:nChains
fname = fullfile(self.working_dir,[self.id '-init-' num2str(i) '.R']);
mstan.rdump(fname,init(i));
fnames{i} = fname;
end
self.init = init(:)';
self.params.init = fnames;
elseif ischar(init)
if exist(init,'file') %% FIXME: exist checks in entire Matlabpath
% TODO: read data into struct... what a mess...
% self.data = dump2struct()
self.init = 'from file';
self.params.init = init;
else
error('StanModel:init:FileNotFound','init file not found');
end
else
if isempty(init)
nChains = self.chains;
self.init = repmat(self.defaults.init,1,nChains);
self.params.init = self.defaults.init;
else
nChains = numel(init);
for i = 1:nChains
validateattributes(init(i),self.validators.init{1},...
self.validators.init{2});
end
self.init = init(:)';
self.params.init = init(:)';
end
end
if self.chains ~= nChains
% TODO, setter getting called repeatedly?
self.chains = nChains;
end
end
function set.seed(self,seed)
validateattributes(seed,self.validators.random.seed{1},...
self.validators.random.seed{2})
if seed < 0
self.params.random.seed = round(sum(100*clock));
else
self.params.random.seed = seed;
end
end
function seed = get.seed(self)
seed = self.params.random.seed;
end
function set.algorithm(self,algorithm)
algorithm = lower(algorithm);
switch lower(self.method)
case 'optimize'
if any(strcmp(self.validators.optimize.algorithm,algorithm))
self.params.optimize.algorithm = algorithm;
else
error('StanModel:algorithm:InputFormat',...
'Unknown algorithm for optimizer');
end
case 'sample'
if strcmp(algorithm,'hmc')
algorithm = 'static';
end
if any(strcmp(self.validators.sample.hmc.engine,algorithm))
self.params.sample.hmc.engine = algorithm;
else
error('StanModel:algorithm:InputFormat',...
'Unknown algorithm for sampler');
end
case 'variational'
if any(strcmp(self.validators.variational.algorithm,algorithm))
self.params.variational.algorithm = algorithm;
else
error('StanModel:algorithm:InputFormat',...
'Unknown algorithm for variational inference');
end
end
end
function algorithm = get.algorithm(self)
switch lower(self.method)
case 'optimize'
algorithm = self.params.optimize.algorithm;
case 'sample'
algorithm = [self.params.sample.algorithm ':' ...
self.params.sample.hmc.engine];
case 'variational'
algorithm = self.params.variational.algorithm;
end
end
function set.control(self,control)
if ~isempty(control)
assert(isstruct(control),'StanModel:control:InputFormat',...
'control must be a structure');
fn = fieldnames(control);
for i = 1:numel(fn)
switch lower(fn{i})
case {'engaged' 'adapt_engaged'}
set_adapt_engaged(self,control.(fn{i}));
case {'gamma' 'adapt_gamma'}
set_adapt_gamma(self,control.(fn{i}));
case {'delta' 'adapt_delta'}
set_adapt_delta(self,control.(fn{i}));
case {'kappa' 'adapt_kappa'}
set_adapt_kappa(self,control.(fn{i}));
case {'t0' 'adapt_t0'}
set_adapt_t0(self,control.(fn{i}));
case {'init_buffer' 'adapt_init_buffer'}
set_adapt_init_buffer(self,control.(fn{i}));
case {'term_buffer' 'adapt_term_buffer'}
set_adapt_term_buffer(self,control.(fn{i}));
case {'window' 'adapt_window'}
set_adapt_window(self,control.(fn{i}));
case {'metric' 'hmc_metric'}
set_hmc_metric(self,control.(fn{i}));
case {'stepsize' 'hmc_stepsize'}
set_hmc_stepsize(self,control.(fn{i}));
case {'stepsize_jitter' 'hmc_stepsize_jitter'}
set_hmc_stepsize_jitter(self,control.(fn{i}));
otherwise
fprintf('%s is not an adapt or hmc parameter\n',fn{i});
end
end
end
end
function control = get.control(self)
switch lower(self.method)
case 'optimize'
control = [];
case 'sample'
control = self.params.sample.adapt;
if strncmp(self.algorithm,'hmc',3)
control.metric = self.params.sample.hmc.metric;
control.stepsize = self.params.sample.hmc.stepsize;
control.stepsize_jitter = self.params.sample.hmc.stepsize_jitter;
end
case 'variational'
control = [];
end
end
function set.diagnostic_file(self,name)
if ischar(name)
self.params.output.diagnostic_file = name;
end
end
function name = get.diagnostic_file(self)
name = self.params.output.diagnostic_file;
end
function set.sample_file(self,name)
if ischar(name)
self.params.output.file = name;
end
end
function name = get.sample_file(self)
name = self.params.output.file;
end
function set.inc_warmup(self,bool)
validateattributes(bool,self.validators.sample.save_warmup{1},...
self.validators.sample.save_warmup{2})
self.params.sample.save_warmup = bool;
end
function bool = get.inc_warmup(self)
bool = self.params.sample.save_warmup;
end
function set.data(self,d)
if isstruct(d) || isa(d,'containers.Map') || isa(d,'RData')
% FIXME: how to contruct filename?
fname = fullfile(self.working_dir,[self.id '-data.R']);
if isa(d,'RData')
rdump(d,fname);
else
mstan.rdump(fname,d);
end
self.data = d;
self.params.data.file = fname;
elseif ischar(d)
if exist(d,'file')
% TODO: read data into struct... what a mess...
% self.data = dump2struct()
self.data = 'from file';
self.params.data.file = d;
else
%error('StanModel:data:FileNotFound','data file not found');
end
else
%error('StanModel:data:InputFormat','not done');
end
end
function command = get.command(self)
command = {[self.model_binary_path ' ']};
str = mstan.parse_stan_params(self.params,self.method);
command = cat(1,command,str);
end
function fit = sampling(self,varargin)
if nargout == 0
error('StanModel:sampling:OutputFormat',...
'Need to assign the fit to a variable');
end
self.set(varargin{:});
self.method = 'sample';
if ~self.is_compiled
if self.verbose
fprintf('We have to compile the model first...\n');
end
self.compile('model');
end
if self.verbose
fprintf('Stan is sampling with %g chains...\n',self.chains);
end
[~,name,ext] = fileparts(self.sample_file);
base_name = self.sample_file;
for i = 1:self.chains
% Set a filename for each chain
sample_file{i} = [name '-' num2str(i) ext];
self.sample_file = sample_file{i};
% Give Stan a different id for each chain. This is used to advance
% Stan's RNG to ensure that draws come from non-overlapping sequences.
self.params.id = i;
% Chain specific inits
if isstruct(self.init) || isa(self.init,'containers.Map')
self.params.init = fullfile(self.working_dir,[self.id '-init-' num2str(i) '.R']);
else
self.params.init = self.init(i);
end
p(i) = processManager('id',sample_file{i},...
'command',sprintf('%s',self.command{:}),...
'workingDir',self.working_dir,...
'wrap',100,...
'keepStdout',true,...
'pollInterval',1,...
'printStdout',self.verbose,...
'autoStart',false);
end
% Reset base name
self.sample_file = base_name;
self.params.init = self.init;
fit = StanFit('model',copy(self),'processes',p,...
'output_file',cellfun(@(x) fullfile(self.working_dir,x),sample_file,'uni',0),...
'verbose',self.verbose);
p.start();
end
function fit = optimizing(self,varargin)
if nargout == 0
error('StanModel:optimizing:OutputFormat',...
'Need to assign the fit to a variable');
end
self.set(varargin{:});
self.method = 'optimize';
if ~self.is_compiled
if self.verbose
fprintf('We have to compile the model first...\n');
end
self.compile('model');
end
if self.verbose
fprintf('Stan is optimizing ...\n');
end
p = processManager('id',self.sample_file,...
'command',sprintf('%s',self.command{:}),...
'workingDir',self.working_dir,...
'wrap',100,...
'keepStdout',true,...
'pollInterval',1,...
'printStdout',self.verbose,...
'autoStart',false);
fit = StanFit('model',copy(self),'processes',p,...
'output_file',{fullfile(self.working_dir,self.sample_file)},...
'verbose',self.verbose);
p.start();
end
function fit = vb(self,varargin)
if nargout == 0
error('StanModel:vb:OutputFormat',...
'Need to assign the fit to a variable');
end
self.set(varargin{:});
self.method = 'variational';
if ~self.is_compiled
if self.verbose
fprintf('We have to compile the model first...\n');
end
self.compile('model');
end
if self.verbose
fprintf('Stan is performing variational inference ...\n');
end
p = processManager('id',self.sample_file,...
'command',sprintf('%s',self.command{:}),...
'workingDir',self.working_dir,...
'wrap',100,...
'keepStdout',true,...
'pollInterval',1,...
'printStdout',self.verbose,...
'autoStart',false);
fit = StanFit('model',copy(self),'processes',p,...
'output_file',{fullfile(self.working_dir,self.sample_file)},...
'verbose',self.verbose);
p.start();
end
function diagnose(self)
error('not done');
end
function ver = get_stan_version(self)
% Get Stan version by calling stanc
count = 0;
while 1 % Occasionally stanc does not return version?
try
ver = self.get_stan_version_();
if count > 0
disp('Succeeded in getting stan version.');
end
break;
catch err
if count == 0
disp('Having a problem getting stan version.');
disp('This is likely a problem with Java running out of file descriptors');
end
if count <= 5
disp('Trying again.');
pause(0.25);
else
disp('Giving up.');
disp('You can try setting the Stan version explicitly using the stan_version attribute.');
disp('i.e. StanModel.stan_version = [2 15 0]');
rethrow(err);
end
count = count + 1;
end
end
end
function ver = get_stan_version_(self)
command = [fullfile(self.stan_home,'bin','stanc') ' --version'];
p = processManager('id','stanc version','command',command,...
'keepStdout',true,...
'printStdout',false,...
'pollInterval',0.005);
p.block(0.05);
if p.exitValue == 0
str = regexp(p.stdout{1},'\ ','split');
ver = cellfun(@str2num,regexp(str{3},'\.','split'));
else
fprintf('%s\n',p.stdout{:});
end
end
function help(self,str)
% TODO:
% if str is stanc or other basic binary
%else
% need to check that model binary exists
command = [self.model_binary_path ' ' str ' help'];
p = processManager('id','stan help','command',command,...
'workingDir',self.model_home,...
'wrap',100,...
'keepStdout',true,...
'printStdout',false);
p.block(0.05);
if p.exitValue == 0
% Trim off the boilerplate
ind = find(strncmp('Usage: ',p.stdout,7));
fprintf('%s\n',p.stdout{1:ind-1});
else
fprintf('%s\n',p.stdout{:});
end
end
function config(self)
% Get CmdStan configuration
p = processManager('id','stan help','command','make help-dev',...
'workingDir',self.stan_home,...
'wrap',100,...
'keepStdout',true,...
'printStdout',false);
p.block(0.05);
fprintf('%s\n',p.stdout{:});
end
function compile(self,target,flags)
% Compile CmdStan components and models
if nargin < 3
flags = '';
elseif iscell(flags) && all(cellfun(@(x) ischar(x),flags))
flags = sprintf('%s ',flags{:});
elseif ischar(flags)
flags = sprintf('%s ',flags);
else
error('StanModel:compile:InputFormat',...
'flags should be formatted as a string or cell array of strings');
end
if nargin < 2
target = 'model';
end
switch lower(target)
case {'stanc' 'libstan.a' 'libstanc.a' 'print' 'stansummary'}
% FIXME: does Stan on windows use / or \?
command = ['make ' flags 'bin/' target];
printStderr = false;
case 'model'
if ispc
command = ['make ' flags regexprep(self.model_binary_path,'\','/')];
else
command = ['make ' flags self.model_binary_path];
end
printStderr = and(true,self.verbose);
otherwise
error('StanModel:compile:InputFormat',...
'Unknown target');