/
moments.jl
1171 lines (984 loc) · 40.9 KB
/
moments.jl
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
struct PriorTableEntry
key::Symbol
reg::Int64
fixed::Bool
tex_label::String
dist_id::String
mean::Float64
sd::Float64
end
struct PosteriorTableEntry
key::Symbol
reg::Int64
fixed::Bool
tex_label::String
mean::Float64
bands::Vector{Float64}
end
"""
```
function load_posterior_moments(m; load_bands = true, include_fixed = false)
```
Load posterior moments (mean, std) of parameters for a particular sample, and optionally
also load 5% and 95% lower and upper bands.
### Keyword Arguments
- `cloud::ParticleCloud`: Optionally pass in a cloud that you want to load the sample from. If the cloud is non-empty then the model object will only be used to find fixed indices and parameter tex labels
- `load_bands::Bool`: Optionally include the 5% and 95% percentiles for the sample of parameters in the returned df
- `include_fixed::Bool`: Optionally include the fixed parameters in the returned df
- `excl_list::Vector{Symbol}`: List parameters by their key that you want to exclude from
loading
### Outputs
- `df`: A dataframe containing the aforementioned moments/bands
"""
function load_posterior_moments(m::AbstractDSGEModel;
cloud::Union{SMC.Cloud,DSGE.Cloud,ParticleCloud} = ParticleCloud(m, 0),
load_bands::Bool = true,
include_fixed::Bool = false,
excl_list::Vector{Symbol} = Vector{Symbol}(undef, 0),
weighted::Bool = true)
parameters = m.parameters
# Read in Posterior Draws
if cloud_isempty(cloud)
if get_setting(m, :sampling_method) == :MH
params = load_draws(m, :full)
params = get_setting(m, :sampling_method) == :MH ? thin_mh_draws(m, params) : params # TODO
params = params'
weights = Vector{Float64}(undef, 0)
weighted = false
elseif get_setting(m, :sampling_method) == :SMC
cloud = get_cloud(m)
params = get_vals(cloud)
weights = get_weights(cloud)
else
@error "Invalid sampling method"
end
else
params = get_vals(cloud)
weights = get_weights(cloud)
end
# Index out the fixed parameters
if include_fixed
free_indices = 1:n_parameters(m)
else
free_indices = findall(x -> x.fixed == false, parameters)
parameters = parameters[free_indices]
params = params[free_indices, :]
end
# Remove excluded parameters
included_indices = setdiff(1:length(free_indices), calculate_excluded_indices(m, excl_list, include_fixed = include_fixed))
parameters = parameters[included_indices]
params = params[included_indices, :]
tex_labels = [DSGE.detexify(parameters[i].tex_label) for i in 1:length(parameters)]
load_posterior_moments(params, weights, tex_labels, weighted = weighted, load_bands = load_bands)
end
# Aggregating many ParticleClouds to calculate moments across
# multiple SMC estimations
function load_posterior_moments(m::AbstractDSGEModel,
clouds::Union{Vector{ParticleCloud},Vector{SMC.Cloud}};
load_bands::Bool = true,
include_fixed::Bool = false,
excl_list::Vector{Symbol} = Vector{Symbol}(undef, 0),
weighted::Bool = true)
n_params = n_parameters(m)
n_particles = length(clouds[1])
n_clouds = length(clouds)
n_free_params = length(Base.filter(x -> x.fixed == false, m.parameters))
p_mean = Array{Float64}(undef, n_free_params, n_clouds)
p_lb = Array{Float64}(undef, n_free_params, n_clouds)
p_ub = Array{Float64}(undef, n_free_params, n_clouds)
for (i, c) in enumerate(clouds)
df_i = load_posterior_moments(m; weighted = weighted, cloud = c, load_bands = load_bands, include_fixed = include_fixed, excl_list = excl_list)
p_mean[:, i] = df_i[!,:post_mean]
p_lb[:, i] = df_i[!,:post_lb]
p_ub[:, i] = df_i[!,:post_ub]
end
param = load_posterior_moments(m; cloud = clouds[1], load_bands = true, include_fixed = false)[!,:param]
df = DataFrame(param = param, post_mean = dropdims(mean(p_mean, dims = 2), dims = 2), post_std = dropdims(std(p_mean, dims = 2),dims = 2), post_lb = dropdims(mean(p_lb, dims = 2), dims = 2), post_ub = dropdims(mean(p_ub, dims = 2), dims = 2))
return df
end
# Base method
# Assumes n_parameters x n_draws
function load_posterior_moments(params::Matrix{Float64}, weights::Vector{Float64}, tex_labels::Vector{String}; weighted::Bool = true, load_bands::Bool = true)
if size(params, 1) > size(params, 2)
@warn "`params` argument to load_posterior_moments seems to be oriented incorrectly.
The argument should be n_params x n_draws. Currently, size(params) = ($(size(params, 1)), $(size(params, 2)))"
end
if weighted
params_mean = vec(mean(params, Weights(weights), dims = 2))
params_std = vec(std(params, Weights(weights), 2, corrected = false))
else
params_mean = vec(mean(params, dims = 2))
params_std = vec(std(params, dims = 2))
end
df = DataFrame()
df[!,:param] = tex_labels
df[!,:post_mean] = params_mean
df[!,:post_std] = params_std
if load_bands
post_lb = Vector{Float64}(undef, length(params_mean))
post_ub = similar(post_lb)
for i in 1:length(params_mean)
if weighted
post_lb[i] = quantile(params[i, :], Weights(weights), .05)
post_ub[i] = quantile(params[i, :], Weights(weights), .95)
else
post_lb[i] = quantile(params[i, :], .05)
post_ub[i] = quantile(params[i, :], .95)
end
end
df[!,:post_lb] = post_lb
df[!,:post_ub] = post_ub
end
return df
end
# For calculating the indices to exclude when making posterior interval plots
function calculate_excluded_indices(m::AbstractDSGEModel, excl_list::Vector{Symbol}; include_fixed::Bool = false)
parameters = deepcopy(m.parameters)
# If fixed parameters are excluded, the indices need to be calculated
# with respect to only the free parameters
if include_fixed
return findall(x -> x in excl_list, [parameters[i].key for i in 1:length(parameters)])
else
# Remove the fixed parameters
Base.filter!(x -> x.fixed == false, parameters)
return findall(x -> x in excl_list, [parameters[i].key for i in 1:length(parameters)])
end
end
"""
```
moment_tables(m; percent = 0.90, subset_inds = 1:0, subset_string = "",
groupings = Dict{String, Vector{Parameter}}(), use_mode = false,
tables = [:prior_posterior_means, :moments, :prior, :posterior],
caption = true, outdir = "", verbose = :none)
```
Computes prior and posterior parameter moments. Tabulates prior mean, posterior
mean, and bands in various LaTeX tables. These tables will be saved in `outdir`
if it is nonempty, or else in `tablespath(m, \"estimate\")`.
### Inputs
- `m::AbstractDSGEModel`: model object
### Keyword Arguments
- `percent::AbstractFloat`: the percentage of the mass of draws from
Metropolis-Hastings included between the bands displayed in output tables.
- `subset_inds::AbstractRange{Int64}`: indices specifying the draws we want to use
- `subset_string::String`: short string identifying the subset to be
appended to the output filenames. If `subset_inds` is nonempty but
`subset_string` is empty, an error is thrown
- `groupings::Dict{String, Vector{Parameter}}`: see `?parameter_groupings`
- `use_mode::Bool`: use the modal parameters instead of the mean in the
prior_posterior_means table
- `tables::Vector{Symbol}`: which tables to produce
- `caption::Bool`: whether to include table captions
- `outdir::String`: where to save output tables
- `verbose::Symbol`: desired frequency of function progress messages printed to
standard out. One of `:none`, `:low`, or `:high`
"""
function moment_tables(m::AbstractDSGEModel; percent::AbstractFloat = 0.90,
subset_inds::AbstractRange{Int64} = 1:0, subset_string::String = "",
groupings::AbstractDict{String, Vector{Parameter}} = Dict{String, Vector{Parameter}}(),
tables = [:prior_posterior_means, :moments, :prior, :posterior],
caption = true, outdir = "",
verbose::Symbol = :low, use_mode::Bool = false)
### 1. Load parameter draws from Metropolis-Hastings
params = if !isempty(subset_inds)
# Use subset of draws
if isempty(subset_string)
error("Must supply a nonempty subset_string if subset_inds is nonempty")
end
load_draws(m, :subset; subset_inds = subset_inds, verbose = verbose)
else
# Use all draws
load_draws(m, :full; verbose = verbose)
end
### 2. Compute posterior moments
if use_mode
post_mode = h5read(get_forecast_input_file(m, :mode), "params")
end
post_means = vec(mean(params, dims = 1))
# Save posterior means
basename = "paramsmean"
if !isempty(subset_string)
basename *= "_sub=$(subset_string)"
end
filename = workpath(m, "estimate", "$basename.h5")
h5open(filename, "w") do file
write(file, "post_means", post_means)
end
post_bands = permutedims(find_density_bands(params, percent; minimize = true))
# map parameters to indices in regimes 2+
para_regime_indices = Dict{Int64, Vector{Int64}}()
if length(post_means) > length(m.parameters)
i = length(m.parameters)
for para in m.parameters
if haskey(para.regimes, :value)
for key in keys(para.regimes[:value])
if key == 1
para_regime_indices[m.keys[para.key]] = [m.keys[para.key]]
else
i += 1
append!(para_regime_indices[m.keys[para.key]], [i])
end
end
end
end
end
### 3. Produce TeX tables
if :prior_posterior_means in tables
prior_posterior_table(m, use_mode ? post_mode : post_means;
subset_string = subset_string, groupings = groupings,
use_mode = use_mode, caption = caption, outdir = outdir, para_regime_indices = para_regime_indices)
end
if :moments in tables
prior_posterior_moments_table(m, post_means, post_bands; percent = percent,
subset_string = subset_string, groupings = groupings,
caption = caption, outdir = outdir, para_regime_indices = para_regime_indices)
end
if :prior in tables
prior_table(m, groupings = groupings, caption = caption, outdir = outdir, para_regime_indices = para_regime_indices)
end
if :posterior in tables
posterior_table(m, post_means, post_bands, percent = percent,
subset_string = subset_string, groupings = groupings,
caption = caption, outdir = outdir,
para_regime_indices = para_regime_indices)
end
#=
if :mean_mode_moments in tables
mean_mode_moments_table(m, post_means, post_bands; percent = percent,
subset_string = subset_string, groupings = groupings,
caption = caption, outdir = outdir)
end
=#
println(verbose, :low, "Tables are saved as " * tablespath(m, "estimate", "*.tex"))
end
"""
```
moments(θ::Parameter)
```
If θ's prior is a `RootInverseGamma`, τ and ν. Otherwise, returns the mean
and standard deviation of the prior. If θ is fixed, returns `(θ.value, 0.0)`.
"""
function moments(θ::Parameter)
if θ.fixed
return θ.value, 0.0
else
prior = get(θ.prior)
if isa(prior, RootInverseGamma)
return prior.τ, prior.ν
else
return mean(prior), std(prior)
end
end
end
function moments(θ::Parameter, reg::Int64)
if haskey(θ.regimes, :fixed) ? θ.regimes[:fixed][reg] : θ.fixed
return θ.regimes[:value][reg], 0.0
else
prior = get(θ.regimes[:prior][reg])
if isa(prior, RootInverseGamma)
return prior.τ, prior.ν
else
return mean(prior), std(prior)
end
end
end
"""
```
prior_table(m; subset_string = "", groupings = Dict{String, Vector{Parameter}}(),
caption = true, outdir = "")
```
"""
function prior_table(m::AbstractDSGEModel; subset_string::String = "",
caption = true, outdir = "",
groupings::AbstractDict{String, Vector{Parameter}} = Dict{String, Vector{Parameter}}(),
para_regime_indices::Dict{Int64, Vector{Int64}} = Dict{Int64, Vector{Int64}}())
if isempty(groupings)
sorted_parameters = sort(m.parameters, by = (x -> x.key))
groupings[""] = sorted_parameters
end
# Open the TeX file
basename = "priors"
if !isempty(subset_string)
basename *= "_sub=$(subset_string)"
end
outfile = tablespath(m, "estimate", "$basename.tex")
if !isempty(outdir)
outfile = replace(outfile, dirname(outfile) => outdir)
end
fid = open(outfile, "w")
# Write header
write_table_preamble(fid)
@printf fid "\\renewcommand*\\footnoterule{}"
@printf fid "\\vspace*{.5cm}\n"
@printf fid "{\\small\n"
@printf fid "\\begin{longtable}{rlrr@{\\hspace{1in}}rlrr}\n"
if caption
@printf fid "\\caption{Priors}\n"
end
@printf fid "\\label{tab:param-priors}\n"
@printf fid "\\\\ \\hline\n"
@printf fid "& Dist & Mean & Std Dev & & Dist & Mean & Std Dev \\\\ \\hline\n"
@printf fid "\\endhead\n"
@printf fid "\\hline \\\\\n"
@printf fid "\\multicolumn{8}{c}{\\footnotesize Note: For Inverse Gamma prior mean and SD, \$\\tau\$ and \$\\nu\$ reported.}\n"
@printf fid "\\endfoot\n"
# Map prior distributions to identifying strings
distid(::Distributions.Uniform) = "Uniform"
distid(::Distributions.Beta) = "Beta"
distid(::Distributions.Gamma) = "Gamma"
distid(::Distributions.Normal) = "Normal"
distid(::RootInverseGamma) = "InvG"
# Write priors
for group_desc in keys(groupings)
params = groupings[group_desc]
# Take out anticipated shock SDs 2 to k - these priors are all the same
antshock_params = [m[k] for k in [Symbol("σ_r_m$i") for i = 2:n_mon_anticipated_shocks(m)]]
params = setdiff(params, antshock_params)
n_params = length(params)
n_rows = convert(Int, ceil(n_params/2))
# Write grouping description if not empty
if !isempty(group_desc)
@printf fid "\\multicolumn{8}{l}{\\textit{%s}} \\\\[3pt]\n" group_desc
end
# Write footnote about standard deviations of anticipated policy shocks
function anticipated_shock_footnote(key)
if n_mon_anticipated_shocks(m) > 0 && key == :σ_r_m1
nantpad = n_mon_anticipated_shocks_padding(m)
all_sigmas = [m[Symbol("σ_r_m$i")]::Parameter for i = 1:nantpad]
nonzero_sigmas = Base.filter(θ -> !(θ.fixed && θ.value == 0), all_sigmas)
n_nonzero_sigmas = length(nonzero_sigmas)
if n_nonzero_sigmas > 1
text = "\$\\sigma_{ant1}\$ through \$\\sigma_{ant$(n_nonzero_sigmas)}\$ all have the same distribution."
@printf fid "\\let\\thefootnote\\relax\\footnote{\\centering %s}" text
end
end
end
entries = Vector{PriorTableEntry}()
for para_i = 1:n_params
para = params[para_i]
(prior_mean, prior_sd) = moments(para)
dist_id = para.fixed ? "-" : distid(get(para.prior))
append!(entries, [PriorTableEntry(para.key, 1, para.fixed, para.tex_label, dist_id, prior_mean, prior_sd)])
if haskey(para.regimes, :prior)
for reg in keys(para.regimes[:prior])
if reg > 1
(prior_mean, prior_sd) = moments(para, reg)
fixed = haskey(para.regimes, :fixed) ? para.regimes[:fixed][reg] : para.fixed
tex_label = para.tex_label * ", reg $reg"
append!(entries, [PriorTableEntry(para.key, reg, fixed, tex_label, fixed ? "-" : distid(get(para.regimes[:prior][reg])), prior_mean, prior_sd)])
end
end
end
end
n_entries = length(entries)
n_rows = convert(Int, ceil(n_entries/2))
for i = 1:n_rows
# Write left column
entry = entries[i]
@printf fid "\$%s\$ &" entry.tex_label
@printf fid " %s &" entry.dist_id
@printf fid " %0.2f &" entry.mean
if entry.fixed
@printf fid " \\scriptsize{fixed} &"
else
@printf fid " %0.2f &" entry.sd
end
anticipated_shock_footnote(entry.key)
# Write right column if it exists
if n_rows + i <= n_entries
entry = entries[n_rows + i]
@printf fid " \$%s\$ &" entry.tex_label
@printf fid " %s &" entry.dist_id
@printf fid " %0.2f &" entry.mean
if entry.fixed
@printf fid " \\scriptsize{fixed}"
else
@printf fid " %0.2f" entry.sd
end
anticipated_shock_footnote(entry.key)
else
@printf fid "& & &"
end
# Add padding after last row in a grouping
if i == n_rows
@printf fid " \\\\[3pt]\n"
else
@printf fid " \\\\\n"
end
end
end
# Write footer
write_table_postamble(fid; small = true)
# Close file
close(fid)
end
"""
```
posterior_table(m, post_means, post_bands; percent = 0.9, subset_string = "",
groupings = Dict{String, Vector{Parameter}}(), caption = true, outdir = "")
```
"""
function posterior_table(m::AbstractDSGEModel, post_means::Vector, post_bands::Matrix;
percent::AbstractFloat = 0.9,
subset_string::String = "",
groupings::AbstractDict{String, Vector{Parameter}} = Dict{String, Vector{Parameter}}(),
caption::Bool = true,
outdir::String = "",
para_regime_indices::Dict{Int64, Vector{Int64}} = Dict{Int64, Vector{Int64}}())
if isempty(groupings)
sorted_parameters = sort(m.parameters, by = (x -> x.key))
groupings[""] = sorted_parameters
end
# Open the TeX file
basename = "posterior"
if !isempty(subset_string)
basename *= "_sub=$(subset_string)"
end
outfile = tablespath(m, "estimate", "$basename.tex")
if !isempty(outdir)
outfile = replace(outfile, dirname(outfile) => outdir)
end
fid = open(outfile, "w")
# Write header
write_table_preamble(fid)
@printf fid "\\renewcommand*\\footnoterule{}"
@printf fid "\\vspace*{.5cm}\n"
@printf fid "{\\small\n"
@printf fid "\\begin{longtable}{rrc@{\\hspace{1in}}rrc}\n"
if caption
@printf fid "\\caption{Posteriors}\n"
end
@printf fid "\\label{tab:param-posteriors}\n"
@printf fid "\\\\ \\hline\n"
lb = (1 - percent)/2 * 100
ub = 100 - lb
@printf fid "& Mean & (p%0.0f, p%0.0f) & & Mean & (p%0.0f, p%0.0f) \\\\ \\hline\n" lb ub lb ub
@printf fid "\\endhead\n"
@printf fid "\\hline \\\\\n"
@printf fid "\\endfoot\n"
# Write posteriors
for group_desc in keys(groupings)
params = groupings[group_desc]
n_params = length(params)
n_rows = convert(Int, ceil(n_params/2))
entries = Vector{PosteriorTableEntry}()
for para in params
para_i = m.keys[para.key]
append!(entries, [PosteriorTableEntry(para.key, 1, para.fixed, para.tex_label, post_means[para_i], post_bands[para_i, :])])
if haskey(para.regimes, :value)
for reg in keys(para.regimes[:value])
if reg > 1
fixed = haskey(para.regimes, :fixed) ? para.regimes[:fixed][reg] : para.fixed
tex_label = para.tex_label * ", reg $reg"
append!(entries, [PosteriorTableEntry(para.key, reg, fixed, tex_label, post_means[para_regime_indices[para_i][reg]], post_bands[para_regime_indices[para_i][reg], :])])
end
end
end
end
n_entries = length(entries)
n_rows = convert(Int, ceil(n_entries/2))
# Write grouping description if not empty
if !isempty(group_desc)
@printf fid "\\multicolumn{6}{l}{\\textit{%s}} \\\\[3pt]\n" group_desc
end
for i = 1:n_rows
# Write left column
entry = entries[i]
j = m.keys[entry.key]
@printf fid "\$%s\$ &" entry.tex_label
@printf fid " %0.2f &" entry.mean
if entry.fixed
@printf fid " \\scriptsize{fixed} &"
else
@printf fid " (%0.2f, %0.2f) &" entry.bands...
end
# Write right column if it exists
if n_rows + i <= n_entries
entry = entries[n_rows + i]
j = m.keys[entry.key]
@printf fid " \$%s\$ &" entry.tex_label
@printf fid " %0.2f &" entry.mean
if entry.fixed
@printf fid " \\scriptsize{fixed}"
else
@printf fid " (%0.2f, %0.2f)" entry.bands...
end
else
@printf fid " & &"
end
# Add padding after last row in a grouping
if i == n_rows
@printf fid " \\\\[3pt]\n"
else
@printf fid " \\\\\n"
end
end
end
# Write footer
write_table_postamble(fid; small = true)
# Close file
close(fid)
end
"""
```
prior_posterior_moments_table(m, post_means, post_bands; percent = 0.9,
subset_string = "", groupings = Dict{String, Vector{Parameter}}(),
caption = true, outdir = "")
```
Produces a table of prior means, prior standard deviations, posterior means, and
90% bands for posterior draws.
"""
function prior_posterior_moments_table(m::AbstractDSGEModel,
post_means::Vector, post_bands::Matrix;
percent::AbstractFloat = 0.9,
subset_string::String = "",
caption = true, outdir = "",
groupings::AbstractDict{String, Vector{Parameter}} = Dict{String, Vector{Parameter}}(),
para_regime_indices::Dict{Int64, Vector{Int64}} = Dict{Int64, Vector{Int64}}())
if isempty(groupings)
sorted_parameters = sort(m.parameters, by = (x -> x.key))
groupings[""] = sorted_parameters
end
# Open the TeX file
basename = "moments"
if !isempty(subset_string)
basename *= "_sub=$(subset_string)"
end
outfile = tablespath(m, "estimate", "$basename.tex")
if !isempty(outdir)
outfile = replace(outfile, dirname(outfile) => outdir)
end
fid = open(outfile, "w")
# Write header
write_table_preamble(fid)
@printf fid "\\vspace*{.5cm}\n"
@printf fid "{\\small\n"
@printf fid "\\begin{longtable}{lcccccc}\n"
if caption
@printf fid "\\caption{Parameter Estimates}\n"
end
@printf fid "\\\\ \\hline\n"
# Two-row column names. First row is multicolumn, where entries (i,str) are `i` columns
# with content `str`.
colnames0 = [(1,""), (3,"Prior"),(3,"Posterior")]
colnames = ["Parameter", "Type", "Mean", "SD", "Mean",
"$(100*percent)\\% {\\tiny Lower Band}",
"$(100*percent)\\% {\\tiny Upper Band}"]
@printf fid "\\multicolumn{%d}{c}{%s}" colnames0[1][1] colnames0[1][2]
for col in colnames0[2:end]
@printf fid " & \\multicolumn{%d}{c}{%s}" col[1] col[2]
end
@printf fid " \\\\\n"
@printf fid "%s" colnames[1]
for col in colnames[2:end]
@printf fid " & %s" col
end
@printf fid " \\\\\n"
@printf fid "\\cmidrule(lr){1-1} \\cmidrule(lr){2-4} \\cmidrule(lr){5-7}\n"
@printf fid "\\endhead\n"
@printf fid "\\hline\n"
@printf fid "\\\\ \\multicolumn{7}{c}{\\footnotesize Note: For Inverse Gamma (IG) prior mean and SD, \$\\tau\$ and \$\\nu\$ reported.}\n"
@printf fid "\\endfoot\n"
# Map prior distributions to identifying strings
distid(::Distributions.Uniform) = "U"
distid(::Distributions.Beta) = "B"
distid(::Distributions.Gamma) = "G"
distid(::Distributions.Normal) = "N"
distid(::RootInverseGamma) = "IG"
# Write parameter moments
# sorted_parameters = sort(m.parameters, by = (x -> x.key))
for group_desc in keys(groupings)
params = groupings[group_desc]
# Write grouping description if not empty
if !isempty(group_desc)
@printf fid "\\multicolumn{7}{c}{\\textit{%s}} \\\\[3pt]\n" group_desc
end
for param in params
index = m.keys[param.key]
(prior_mean, prior_std) = moments(param)
@printf fid "\$%4.99s\$ & " param.tex_label
@printf fid "%s & " (param.fixed ? "-" : distid(get(param.prior)))
@printf fid "%8.3f & " prior_mean
@printf fid "%8.3f & " prior_std
@printf fid "%8.3f & " post_means[index]
@printf fid "%8.3f & %8.3f \\\\\n" post_bands[index, :]...
end
end
# Write footer
write_table_postamble(fid; small=true)
# Close file
close(fid)
end
"""
```
prior_posterior_table(m, post_values; subset_string = "",
groupings = Dict{String, Vector{Parameter}}(), use_mode = false,
caption = true, outdir = "")
```
Produce a table of prior means and posterior means or mode.
"""
function prior_posterior_table(m::AbstractDSGEModel, post_values::Vector;
subset_string::String = "",
groupings::AbstractDict{String,Vector{Parameter}} = Dict{String, Vector{Parameter}}(),
caption = true, outdir = "",
use_mode::Bool = false,
para_regime_indices::Dict{Int64, Vector{Int64}} = Dict{Int64, Vector{Int64}}())
if isempty(groupings)
sorted_parameters = sort(m.parameters, by = (x -> x.key))
groupings[""] = sorted_parameters
end
# Open the TeX file
basename = use_mode ? "prior_posterior_mode" : "prior_posterior_means"
if !isempty(subset_string)
basename *= "_sub=$(subset_string)"
end
table_out = tablespath(m, "estimate", "$basename.tex")
if !isempty(outdir)
outfile = replace(outfile, dirname(outfile) => outdir)
end
fid = open(table_out, "w")
# Write header
write_table_preamble(fid)
@printf fid "\\vspace*{.5cm}\n"
@printf fid "\\begin{longtable}{ccc}\n"
if caption
if use_mode
@printf fid "\\caption{Parameter Estimates: Prior Mean and Posterior Mode}\n"
else
@printf fid "\\caption{Parameter Estimates: Prior and Posterior Means}\n"
end
end
@printf fid "\\\\ \\hline\n"
@printf fid "Parameter & Prior & Posterior\n"
@printf fid "\\\\ \\hline\n"
@printf fid "\\endhead\n"
@printf fid "\\hline\n"
@printf fid "\\endfoot\n"
# Write results
# sorted_parameters = sort(m.parameters, by = (x -> x.key))
for group_desc in keys(groupings)
params = groupings[group_desc]
# Write grouping description if not empty
if !isempty(group_desc)
@printf fid "\\multicolumn{7}{c}{\\textit{%s}} \\\\[3pt]\n" group_desc
end
for param in params
index = m.keys[param.key]
post_value = if param.fixed
param.value
else
prior = get(param.prior)
isa(prior, RootInverseGamma) ? prior.τ : mean(prior)
end
@printf fid "\$ %4.99s\$ & " param.tex_label
@printf fid "%8.3f & " post_value
@printf fid "\\%8.3f \\\\\n" post_values[index]
end
end
# Write footer
write_table_postamble(fid)
# Close file
close(fid)
end
"""
```
find_density_bands(draws::Matrix, percent::AbstractFloat; minimize::Bool=true)
```
Returns a `2` x `cols(draws)` matrix `bands` such that `percent` of the mass of `draws[:,i]`
is above `bands[1,i]` and below `bands[2,i]`.
### Arguments
- `draws`: `ndraws` by `nperiods` matrix of parameter draws (from Metropolis-Hastings, for example)
- `percent`: percent of data within bands (e.g. .9 to get 90% of mass within bands)
### Optional Arguments
- `minimize`: if `true`, choose shortest interval, otherwise just chop off lowest and
highest (percent/2)
"""
function find_density_bands(draws::AbstractArray, percent::T;
minimize::Bool = true) where {T<:AbstractFloat}
if !(0 <= percent <= 1)
error("percent must be between 0 and 1")
end
ndraws, nperiods = size(draws)
if ndraws == 1
band = repeat(draws, outer=(2, 1))
return band
end
band = zeros(2, nperiods)
n_in_band = round(Int, percent * ndraws) # number of draws in the band
for i in 1:nperiods
# Sort response for parameter i such that 1st element is largest
draw_variable_i = draws[:,i]
sort!(draw_variable_i, rev=true)
# Search to find the shortest interval containing `percent` of
# the mass `low` is the index of the largest draw in the band
# (but the first index to take in `draw_variable_i`, `high` is
# the smallest (but the highest index to take)
low = if minimize
low = 1
done = 0
j = 2
minwidth = draw_variable_i[1] - draw_variable_i[n_in_band]
while j <= (ndraws - n_in_band + 1)
newwidth = draw_variable_i[j] - draw_variable_i[j + n_in_band - 1]
if newwidth < minwidth
low = j
minwidth = newwidth
end
j += 1
end
low
else
# Chop off lowest and highest percent/2
ndraws - n_in_band - round(Int, floor(.5*(ndraws-n_in_band)))
end
high = low + n_in_band - 1
if any(ismissing.(draw_variable_i)) || isnan(draw_variable_i[low]) || isnan(draw_variable_i[high])
band[2,i] = NaN
band[1,i] = NaN
else
band[2,i] = draw_variable_i[low]
band[1,i] = draw_variable_i[high]
end
end
return band
end
"""
```
find_density_bands(draws::Matrix, percents::Vector{T}; minimize::Bool=true) where T<:AbstractFloat
```
Returns a `2` x `cols(draws)` matrix `bands` such that `percent` of the mass of `draws[:,i]`
is above `bands[1,i]` and below `bands[2,i]`.
### Arguments
- `draws`: Matrix of parameter draws (from Metropolis-Hastings, for example)
- `percent`: percent of data within bands (e.g. .9 to get 90% of mass within bands)
### Optional Arguments
- `minimize`: if `true`, choose shortest interval, otherwise just chop off lowest and
highest (percent/2)
"""
function find_density_bands(draws::AbstractArray, percents::Vector{T};
minimize::Bool = true) where {T<:AbstractFloat}
bands = DataFrame()
for p in percents
out = find_density_bands(draws, p, minimize = minimize)
bands[!, Symbol("$(100*p)% UB")] = vec(out[2,:])
bands[!, Symbol("$(100*p)% LB")] = vec(out[1,:])
end
bands
end
function write_table_preamble(fid::IOStream)
@printf fid "\\documentclass[12pt]{article}\n"
@printf fid "\\usepackage{booktabs}\n"
@printf fid "\\usepackage[justification=centering]{caption}\n"
@printf fid "\\usepackage[margin=1in]{geometry}\n"
@printf fid "\\usepackage{longtable}\n"
@printf fid "\\usepackage{graphicx}\n"
@printf fid "\\usepackage{cellspace}\n"
@printf fid "\\setlength\\cellspacetoplimit{7pt}\n"
@printf fid "\\setlength\\cellspacebottomlimit{7pt}\n"
@printf fid "\\begin{document}\n"
@printf fid "\\pagestyle{empty}\n"
end
# `small`: Whether to print an additional curly bracket after "\end{longtable}" (necessary if
# the table is enclosed by "\small{}")
function write_table_postamble(fid::IOStream; small::Bool=false, tabular::Bool=false)
if small
if tabular
@printf fid "\\end{tabular}}\n"
else
@printf fid "\\end{longtable}}\n"
end
else
if tabular
@printf fid "\\end{tabular}\n"
else
@printf fid "\\end{longtable}\n"
end
end
@printf fid "\\end{document}"
end
"""
```
sample_λ(m, pred_dens, θs, T = -1; parallel = true) where S<:AbstractFloat
sample_λ(m, pred_dens, T = -1; parallel = true) where S<:AbstractFloat
```
Computes and samples from the conditional density p(λ_t|θ, I_t, P) for
particle in `θs`, which represents the posterior distribution. The sampled
λ particles represent the posterior distribution p(λ_{t|t} | I_t, P).
If no posterior distribution is passed in, then the function computes
the distribution of λ_{t|t} for a static pool.
### Inputs
- `m::PoolModel{S}`: `PoolModel` object
- `pred_dens::Matrix{S}`: matrix of predictive densities
- `θs::Matrix{S}`: matrix of particles representing posterior distribution of θ
- `T::Int64`: final period for tempered particle filter
where `S<:AbstractFloat`.
### Keyword Argument
- `parallel::Bool`: use parallel computing to compute and sample draws of λ
### Outputs
- `λ_sample::Vector{Float64}`: sample of draws of λs; together with (θ,λ) represents a joint density
```
"""
function sample_λ(m::PoolModel{S}, pred_dens::Matrix{S}, θs::Matrix{S}, T::Int64 = -1;
parallel::Bool = false,
tuning0::Dict{Symbol,Any} = Dict{Symbol,Any}()) where S<:AbstractFloat
# Check size and orientation of θs is correct: assume particle_num x parameter_num
if length(m.parameters) != size(θs,2)
error("number of parameters in PoolModel do not match number of parameters in matrix of posterior draws of θ")
end
# Initialize necessary objects
if T <= 0
error("T must be positive") # No period provided or is invalid
end
tuning = isempty(tuning0) ? deepcopy(get_setting(m, :tuning)) : deepcopy(tuning0)
tuning[:get_t_particle_dist] = true
tuning[:parallel] = false
tuning[:allout] = false
# Sample from p(λ|θ, I_t^P, P) for each θ in posterior
data = (T == 1) ? reshape(pred_dens[:,1], 2, 1) : pred_dens[:,1:T]
if parallel
# Send variables to workers to avoid issues with serialization
# across workers with different Julia system images