/
parameters.jl
1644 lines (1427 loc) · 67.9 KB
/
parameters.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
import Base: <=
Interval{T} = Tuple{T,T}
"""
```
Transform
```
Subtypes of the abstract Transform type indicate how a `Parameter`'s
value is transformed from model space (which can be bounded to a
limited section of the real line) to the entire real line (which is
necessary for mode-finding using csminwel). The transformation is
performed by the `transform_to_real_line` function, and is reversed by the
`transform_to_model_space` function.
"""
abstract type Transform end
struct Untransformed <: Transform end
struct SquareRoot <: Transform end
struct Exponential <: Transform end
Base.show(io::IO, t::Untransformed) = @printf io "x -> x\n"
Base.show(io::IO, t::SquareRoot) = @printf io "x -> (a+b)/2 + (b-a)/2*c*x/sqrt(1 + c^2 * x^2)\n"
Base.show(io::IO, t::Exponential) = @printf io "x -> b + (1/c) * log(x-a)\n"
"""
```
AbstractParameter{T<:Number}
```
The AbstractParameter type is the common supertype of all model
parameters, including steady-state values. Its subtype structure is
as follows:
-`AbstractParameter{T<:Number}`: The common abstract supertype for all parameters.
-`Parameter{S<:Real,T<:Number, U<:Transform}`: The abstract supertype for parameters that are directly estimated.
-`UnscaledParameter{S<:Real, T<:Number, U:<Transform}`: Concrete type for parameters that do not need to be scaled for equilibrium conditions.
-`ScaledParameter{S<:Real, T<:Number, U:<Transform}`: Concrete type for parameters that are scaled for equilibrium conditions.
-`SteadyStateParameter{T<:Number}`: Concrete type for steady-state parameters.
"""
abstract type AbstractParameter{T<:Number} end
abstract type AbstractVectorParameter{V<:Vector, T<:Number} end
#abstract type AbstractArrayParameter{A<:Array} end
"""
```
Parameter{ S<:Real, T<:Number, U<:Transform} <: AbstractParameter{T}
```
The Parameter type is the common supertype of time-invariant, non-steady-state model
parameters. It has 2 subtypes, `UnscaledParameter` and `ScaledParameter`.
`ScaledParameter`s are parameters whose values are scaled when used in the model's
equilibrium conditions. The scaled value is stored for convenience, and updated when the
parameter's value is updated.
The Parameter type has separate `T` and `S` types to allow for
automatic differentiation, which will make the type of `S` a Dual type. By specifying
this difference, while we cannot enforce `T` and `S` to always sensibly match
each others types, we can avoid the issue of having to recast the types of fields
with type `T` to be Duals as well.
"""
abstract type Parameter{T,U<:Transform} <: AbstractParameter{T} end
abstract type ParameterAD{S<:Real,T,U} <: Parameter{T,U} end
abstract type VectorParameter{V,T,U<:Transform} <: AbstractVectorParameter{V,T} end
#abstract type ArrayParameter{A,U<:Transform} <: AbstractArrayParameter{A} end
# ParameterVector is a wrapper for a vector
# that takes any subtype of AbstractParameter, but it is not
# an "abstract" type since we are not intending
# to define subtypes of ParameterVector.
ParameterVector{T} = Vector{AbstractParameter{T}}
VectorParameterVector{V,T} = Vector{AbstractVectorParameter{V,T}}
#ArrayParameterVector{A} = Vector{AbstractArrayParameter{A}}
NullablePriorUnivariate = Nullables.Nullable{ContinuousUnivariateDistribution}
NullablePriorMultivariate = Nullables.Nullable{ContinuousMultivariateDistribution}
"""
```
UnscaledParameter{S<:Real,T<:Number,U<:Transform} <: Parameter{S,T,U}
```
Time-invariant model parameter whose value is used as-is in the model's equilibrium
conditions.
#### Fields
- `key::Symbol`: Parameter name. For maximum clarity, `key`
should conform to the guidelines established in the DSGE Style Guide.
- `value::S`: Parameter value. Initialized in model space (guaranteed
to be between `valuebounds`), but can be transformed between model
space and the real line via calls to `transform_to_real_line` and
`transform_to_model_space`.
- `valuebounds::Interval{T}`: Bounds for the parameter's value in model space.
- `transform_parameterization::Interval{T}`: Parameters used to
transform `value` between model space and the real line.
- `transform::U`: Transformation used to transform `value` between
model space and real line.
- `prior::NullablePrior`: Prior distribution for parameter value.
- `fixed::Bool`: Indicates whether the parameter's value is fixed rather than estimated.
- `regimes::Dict{Symbol,OrderedDict{Int64,Any}}`: Dictionary for holding information
when there are multiple regimes for parameter values
- `description::String`: A short description of the parameter's economic
significance.
- `tex_label::String`: String for printing the parameter name to LaTeX.
"""
mutable struct UnscaledParameterAD{S,T,U} <: ParameterAD{S,T,U} # New parameter type for Autodiff
key::Symbol
value::S # parameter value in model space
valuebounds::Interval{T} # bounds of parameter value
transform_parameterization::Interval{T} # parameters for transformation
transform::U # transformation between model space and real line for optimization
prior::NullablePriorUnivariate # prior distribution
fixed::Bool # is this parameter fixed at some value?
regimes::Dict{Symbol,OrderedDict{Int64,Any}}
description::String
tex_label::String # LaTeX label for printing
end
mutable struct UnscaledParameter{T,U} <: Parameter{T,U} # Old parameter type
key::Symbol
value::T # parameter value in model space
valuebounds::Interval{T} # bounds of parameter value
transform_parameterization::Interval{T} # parameters for transformation
transform::U # transformation between model space and real line for optimization
prior::NullablePriorUnivariate # prior distribution
fixed::Bool # is this parameter fixed at some value?
regimes::Dict{Symbol,OrderedDict{Int64,Any}}
description::String
tex_label::String # LaTeX label for printing
end
mutable struct UnscaledVectorParameter{V,T,U} <: VectorParameter{V,T,U}
key::Symbol
value::V # parameter value in model space
valuebounds::Interval{T} # bounds of parameter value
transform_parameterization::Interval{T} # parameters for transformation
transform::U # transformation between model space and real line for optimization
prior::NullablePriorMultivariate # prior distribution
fixed::Bool # is this parameter fixed at some value?
regimes::Dict{Symbol,OrderedDict{Int64,Any}}
description::String
tex_label::String # LaTeX label for printing
end
"""
```
ScaledParameter{S,T,U} <: Parameter{S,T,U}
```
Time-invariant model parameter whose value is scaled for use in the model's equilibrium
conditions.
#### Fields
- `key::Symbol`: Parameter name. For maximum clarity, `key`
should conform to the guidelines established in the DSGE Style Guide.
- `value::T`: The parameter's unscaled value. Initialized in model
space (guaranteed to be between `valuebounds`), but can be
transformed between model space and the real line via calls to
`transform_to_real_line` and `transform_to_model_space`.
- `scaledvalue::T`: Parameter value scaled for use in `eqcond.jl`
- `valuebounds::Interval{T}`: Bounds for the parameter's value in model space.
- `transform_parameterization::Interval{T}`: Parameters used to
transform `value` between model space and the real line.
- `transform::U`: The transformation used to convert `value` between model space and the
real line, for use in optimization.
- `prior::NullablePrior`: Prior distribution for parameter value.
- `fixed::Bool`: Indicates whether the parameter's value is fixed rather than estimated.
- `scaling::Function`: Function used to scale parameter value for use in equilibrium
conditions.
- `regimes::Dict{Symbol,OrderedDict{Int64,Any}}`: Dictionary for holding information
when there are multiple regimes for parameter values
- `description::String`: A short description of the parameter's economic
significance.
- `tex_label::String`: String for printing parameter name to LaTeX.
"""
mutable struct ScaledParameterAD{S,T,U} <: ParameterAD{S,T,U}
key::Symbol
value::S
scaledvalue::S
valuebounds::Interval{T}
transform_parameterization::Interval{T}
transform::U
prior::NullablePriorUnivariate
fixed::Bool
scaling::Function
regimes::Dict{Symbol,OrderedDict{Int64,Any}}
description::String
tex_label::String
end
mutable struct ScaledParameter{T,U} <: Parameter{T,U}
key::Symbol
value::T #S
scaledvalue::T #S
valuebounds::Interval{T}
transform_parameterization::Interval{T}
transform::U
prior::NullablePriorUnivariate
fixed::Bool
scaling::Function
regimes::Dict{Symbol,OrderedDict{Int64,Any}}
description::String
tex_label::String
end
mutable struct ScaledVectorParameter{V,T,U} <: VectorParameter{V,T,U}
key::Symbol
value::V
scaledvalue::V
valuebounds::Interval{T}
transform_parameterization::Interval{T}
transform::U
prior::NullablePriorMultivariate
fixed::Bool
scaling::Function
regimes::Dict{Symbol,OrderedDict{Int64,Any}}
description::String
tex_label::String
end
"""
```
SteadyStateParameter{T} <: AbstractParameter{T}
```
Steady-state model parameter whose value depends upon the value of other (non-steady-state)
`Parameter`s. `SteadyStateParameter`s must be constructed and added to an instance of a
model object `m` after all other model `Parameter`s have been defined. Once added to `m`,
`SteadyStateParameter`s are stored in `m.steady_state`. Their values are calculated and set
by `steadystate!(m)`, rather than being estimated directly. `SteadyStateParameter`s do not
require transformations from the model space to the real line or scalings for use in
equilibrium conditions.
#### Fields
- `key::Symbol`: Parameter name. Should conform to the guidelines
established in the DSGE Style Guide.
- `value::T`: The parameter's steady-state value.
- `description::String`: Short description of the parameter's economic significance.
- `tex_label::String`: String for printing parameter name to LaTeX.
"""
mutable struct SteadyStateParameter{T} <: AbstractParameter{T}
key::Symbol
value::T
description::String
tex_label::String
end
"""
```
SteadyStateParameterGrid{T} <: AbstractParameter{T}
```
Steady-state model parameter grid (for heterogeneous agent models) whose value is calculated by an
iterative procedure.
`SteadyStateParameterGrid`s must be constructed and added to an instance of a
model object `m` after all other model `Parameter`s have been defined. Once added to `m`,
`SteadyStateParameterGrid`s are stored in `m.steady_state`. Their values are calculated and set
by `steadystate!(m)`, rather than being estimated directly. `SteadyStateParameter`s do not
require transformations from the model space to the real line or scalings for use in
equilibrium conditions.
#### Fields
- `key::Symbol`: Parameter name. Should conform to the guidelines
established in the DSGE Style Guide.
- `value::Array{T}`: The parameter's steady-state value grid.
- `description::String`: Short description of the parameter's economic significance.
- `tex_label::String`: String for printing parameter name to LaTeX.
"""
mutable struct SteadyStateParameterGrid{T} <: AbstractParameter{T}
key::Symbol
value::Array{T}
description::String
tex_label::String
end
iterate(p::SteadyStateParameterGrid) = iterate(p.value)
iterate(p::SteadyStateParameterGrid, i::Int) = iterate(p.value, i)
size(p::SteadyStateParameterGrid) = size(p.value)
size(p::SteadyStateParameterGrid, dims) = size(p.value, dims)
sum(p::SteadyStateParameterGrid; dims = nothing) = isnothing(dims) ? sum(p.value) : sum(p.value; dims = dims)
getindex(p::SteadyStateParameterGrid, i) = getindex(p.value, i)
-(p::SteadyStateParameterGrid) = -p.value
function SteadyStateParameterGrid(key::Symbol,
value::Array{T};
description::String = "No description available",
tex_label::String = "") where {T<:Number}
return SteadyStateParameterGrid{T}(key, value, description, tex_label)
end
"""
```
SteadyStateParameterArray{T} <: AbstractParameter{T}
```
Steady-state model parameter whose value is an Array and
depends upon the value of other (non-steady-state)
`Parameter`s. `SteadyStateParameterArray`s must be constructed and added to an instance of a
model object `m` after all other model `Parameter`s have been defined. Once added to `m`,
`SteadyStateParameterArray`s are stored in `m.steady_state`. Their values are calculated and set
by `steadystate!(m)`, rather than being estimated directly. `SteadyStateParameterArray`s do not
require transformations from the model space to the real line or scalings for use in
equilibrium conditions.
#### Fields
- `key::Symbol`: Parameter name. Should conform to the guidelines
established in the DSGE Style Guide.
- `value::Array{T}`: The parameter's steady-state values.
- `description::String`: Short description of the parameter's economic significance.
- `tex_label::String`: String for printing parameter name to LaTeX.
"""
mutable struct SteadyStateParameterArray{T} <: AbstractParameter{T}
key::Symbol
value::Array{T}
description::String
tex_label::String
end
iterate(p::SteadyStateParameterArray) = iterate(p.value)
"""
```
SteadyStateParameterArray{T<:Number}(key::Symbol, value::Array{T};
description::String = "",
tex_label::String = "")
```
SteadyStateParameter constructor with optional `description` and `tex_label` arguments.
"""
function SteadyStateParameterArray(key::Symbol,
value::Array{T};
description::String = "No description available",
tex_label::String = "") where {T<:Number}
return SteadyStateParameterArray(key, value, description, tex_label)
end
# TypeError: non-boolean (BitArray{1}) used in boolean context
# gets thrown when we print the value.
function Base.show(io::IO, p::SteadyStateParameterArray{T}) where {T}
@printf io "%s\n" typeof(p)
@printf io "(:%s)\n%s\n" p.key p.description
@printf io "LaTeX label: %s\n" p.tex_label
@printf io "-----------------------------\n"
@printf io "value: [%+6f,...,%+6f]\n" p.value[1] p.value[end]
end
hasprior(p::Union{Parameter, ParameterAD, VectorParameter}) = !isnull(p.prior)
NullableOrPriorUnivariate = Union{NullablePriorUnivariate, ContinuousUnivariateDistribution}
NullableOrPriorMultivariate = Union{NullablePriorMultivariate, ContinuousMultivariateDistribution}
# We want to use value field from UnscaledParameters and
# SteadyStateParameters in computation, so we alias their union here.
UnscaledOrSteadyState = Union{UnscaledParameter, UnscaledParameterAD, SteadyStateParameter}
"""
```
ParamBoundsError <: Exception
```
A `ParamBoundsError` is thrown upon an attempt to assign a parameter value that is not
between `valuebounds`.
"""
mutable struct ParamBoundsError <: Exception
msg::String
end
ParamBoundsError() = ParamBoundsError("Value not between valuebounds")
Base.showerror(io::IO, ex::ParamBoundsError) = print(io, ex.msg)
"""
```
parameter{S,T,U<:Transform}(key::Symbol, value::S, valuebounds = (value,value),
transform_parameterization = (value,value),
transform = Untransformed(), prior = NullablePrior();
fixed = true, scaling::Function = identity, description = "",
tex_label::String = "")
```
By default, returns a fixed `UnscaledParameter` object with key `key`
and value `value`. If `scaling` is given, a `ScaledParameter` object
is returned.
"""
function parameter(key::Symbol,
value::Union{T, V}, #value::Union{S,V},
valuebounds::Interval{T} = (value,value),
transform_parameterization::Interval{T} = (value,value),
transform::U = Untransformed(),
prior::Union{NullableOrPriorUnivariate, NullableOrPriorMultivariate} = NullablePriorUnivariate();
fixed::Bool = true,
scaling::Function = identity,
regimes::Dict{Symbol,OrderedDict{Int64,Any}} = Dict{Symbol,OrderedDict{Int64,Any}}(),
description::String = "No description available.",
tex_label::String = "") where {V<:Vector, T <: Real, U <:Transform} #{V<:Vector, S<:Real, T <: Float64, U <:Transform}
# If fixed=true, force bounds to match and leave prior as null. We need to define new
# variable names here because of lexical scoping.
valuebounds_new = valuebounds
transform_parameterization_new = transform_parameterization
transform_new = transform
U_new = U
prior_new = prior
if fixed
# value[1] because need to deal with case in which value is a vector (but if only Float, [1] just takes the Float
transform_parameterization_new = (value[1],value[1]) # value is transformed already
transform_new = Untransformed() # fixed priors should stay untransformed
U_new = Untransformed
if isa(transform, Untransformed)
valuebounds_new = (value[1],value[1])
end
else
transform_parameterization_new = transform_parameterization
end
# ensure that we have a Nullable{Distribution}, if not construct one
prior_new = if isa(prior_new, NullableOrPriorUnivariate)
!isa(prior_new,NullablePriorUnivariate) ? NullablePriorUnivariate(prior_new) : prior_new
elseif isa(prior_new, NullableOrPriorMultivariate)
!isa(prior_new,NullablePriorMultivariate) ? NullablePriorMultivariate(prior_new) : prior_new
else
@error "Must be a PriorOrNullable or PriorOrNullableMultivariate"
end
if scaling == identity
if typeof(value) <: Number #Real
return UnscaledParameter{T,U_new}(key, value, valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, regimes, description, tex_label) #S
elseif typeof(value) <: Vector
return UnscaledVectorParameter{V,T,U_new}(key, value, valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, regimes, description, tex_label)
else
@error "Type of value not yet supported"
end
else
if typeof(value) <: Number #Real
return ScaledParameter{T,U_new}(key, value, scaling(value), valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, scaling, regimes, description, tex_label)
elseif typeof(value) <: Vector
return ScaledVectorParameter{V,T,U_new}(key, value, scaling(value), valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, scaling, regimes, description, tex_label)
end
end
end
function parameter(key::Symbol,
value::Union{T1, V}, #value::Union{S,V},
valuebounds::Interval{T2} = (value,value),
transform_parameterization::Interval{T3} = (value,value),
transform::U = Untransformed(),
prior::Union{NullableOrPriorUnivariate, NullableOrPriorMultivariate} = NullablePriorUnivariate();
fixed::Bool = true,
scaling::Function = identity,
regimes::Dict{Symbol,OrderedDict{Int64,Any}} = Dict{Symbol,OrderedDict{Int64,Any}}(),
description::String = "No description available.",
tex_label::String = "") where {V<:Vector, T1 <: Real, T2 <: Real, T3 <: Real, U <:Transform}
warn_str = "The element types of the fields `value` ($(typeof(value))), `valuebounds` ($(eltype(valuebounds))), " *
"and `transform_parameterization` ($(eltype(transform_parameterization))) do not match. " *
"Attempting to convert all types to the same type as `value`. Note that the element type for the prior " *
"distribution should also be $(typeof(value))."
@warn warn_str
valuebounds_new = (convert(T1, valuebounds[1]), convert(T1, valuebounds[2]))
transform_parameterization_new = (convert(T1, transform_parameterization[1]),
convert(T1, transform_parameterization[2]))
return parameter(key, value, valuebounds_new, transform_parameterization_new,
transform, prior; fixed = fixed, scaling = scaling,
regimes = regimes, description = description, tex_label = tex_label)
end
function parameter_ad(key::Symbol,
value::Union{S,V},
valuebounds::Interval{T} = (value,value),
transform_parameterization::Interval{T} = (value,value),
transform::U = Untransformed(),
prior::Union{NullableOrPriorUnivariate, NullableOrPriorMultivariate} = NullablePriorUnivariate();
fixed::Bool = true,
scaling::Function = identity,
regimes::Dict{Symbol,OrderedDict{Int64,Any}} = Dict{Symbol,OrderedDict{Int64,Any}}(),
description::String = "No description available.",
tex_label::String = "") where {V<:Vector, S<:Real, T <: Float64, U <:Transform}
# If fixed=true, force bounds to match and leave prior as null. We need to define new
# variable names here because of lexical scoping.
valuebounds_new = valuebounds
transform_parameterization_new = transform_parameterization
transform_new = transform
U_new = U
prior_new = prior
if fixed
# value[1] because need to deal with case in which value is a vector (but if only Float, [1] just takes the Float
transform_parameterization_new = (value[1],value[1]) # value is transformed already
transform_new = Untransformed() # fixed priors should stay untransformed
U_new = Untransformed
if isa(transform, Untransformed)
valuebounds_new = (value[1],value[1])
end
else
transform_parameterization_new = transform_parameterization
end
# ensure that we have a Nullable{Distribution}, if not construct one
prior_new = if isa(prior_new, NullableOrPriorUnivariate)
!isa(prior_new,NullablePriorUnivariate) ? NullablePriorUnivariate(prior_new) : prior_new
elseif isa(prior_new, NullableOrPriorMultivariate)
!isa(prior_new,NullablePriorMultivariate) ? NullablePriorMultivariate(prior_new) : prior_new
else
@error "Must be a PriorOrNullable or PriorOrNullableMultivariate"
end
if scaling == identity
if typeof(value) <: Real
return UnscaledParameterAD{S,T,U_new}(key, value, valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, regimes, description, tex_label) #S
elseif typeof(value) <: Vector
return UnscaledVectorParameter{V,T,U_new}(key, value, valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, regimes, description, tex_label)
else
@error "Type of value not yet supported"
end
else
if typeof(value) <: Real
return ScaledParameterAD{S,T,U_new}(key, value, scaling(value), valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, scaling, regimes, description, tex_label)
elseif typeof(value) <: Vector
return ScaledVectorParameter{V,T,U_new}(key, value, scaling(value), valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, scaling, regimes, description, tex_label)
end
end
end
function parameter(key::Symbol,
prior::Union{ContinuousUnivariateDistribution, ContinuousMultivariateDistribution};
fixed::Bool = false,
description::String = "No description available",
tex_label::String = "")
val = length(prior) > 1 ? repeat([NaN], length(prior)) : NaN
return parameter(key, val, (NaN, NaN), (NaN, NaN), Untransformed(), prior, fixed = fixed, scaling = identity, description = description, tex_label = tex_label)
end
"""
```
SteadyStateParameter(key::Symbol, value::T; description::String = "",
tex_label::String = "") where {T <: Number}
```
SteadyStateParameter constructor with optional `description` and `tex_label` arguments.
"""
function SteadyStateParameter(key::Symbol, value::T;
description::String = "No description available",
tex_label::String = "") where {T <: Number}
return SteadyStateParameter(key, value, description, tex_label)
end
"""
```
parameter(p::UnscaledParameter{S,T,U}, newvalue::S) where {S<:Real,T<:Number,U<:Transform}
```
Returns an UnscaledParameter with value field equal to `newvalue`. If `p` is a fixed
parameter, it is returned unchanged.
"""
function parameter(p::UnscaledParameter{T,U}, newvalue::T) where {T <: Number, U <: Transform}
p.fixed && return p # if the parameter is fixed, don't change its value
a,b = p.valuebounds
if !(a <= newvalue <= b)
throw(ParamBoundsError("New value of $(string(p.key)) ($(newvalue)) is out of bounds ($(p.valuebounds))"))
end
UnscaledParameter{T,U}(p.key, newvalue, p.valuebounds, p.transform_parameterization,
p.transform, p.prior, p.fixed, p.regimes, p.description, p.tex_label)
end
function parameter_ad(p::UnscaledParameterAD{S,T,U}, newvalue::Snew;
change_value_type::Bool = false) where {S<:Real, Snew<:Real, T <: Number, U <: Transform}
p.fixed && return p # if the parameter is fixed, don't change its value
if !change_value_type && (typeof(p.value) != typeof(newvalue))
error("Type of newvalue $(newvalue) does not match the type of the current value for parameter $(string(p.key)). Set keyword change_value_type = true if you want to overwrite the type of the parameter value.")
end
a,b = p.valuebounds
if !(a <= newvalue <= b)
throw(ParamBoundsError("New value of $(string(p.key)) ($(newvalue)) is out of bounds ($(p.valuebounds))"))
end
if change_value_type
UnscaledParameterAD{Snew,T,U}(p.key, newvalue, p.valuebounds, p.transform_parameterization,
p.transform, p.prior, p.fixed, p.regimes, p.description, p.tex_label)
else
UnscaledParameterAD{S,T,U}(p.key, newvalue, p.valuebounds, p.transform_parameterization,
p.transform, p.prior, p.fixed, p.regimes, p.description, p.tex_label)
end
end
function parameter(p::UnscaledVectorParameter{V,T,U}, newvalue::V) where {V <: Vector, T <: Number, U <: Transform}
p.fixed && return p # if the parameter is fixed, don't change its value
a,b = p.valuebounds
if !all(a .<= newvalue .<= b)
throw(ParamBoundsError("New value of $(string(p.key)) ($(newvalue)) is out of bounds ($(p.valuebounds))"))
end
UnscaledVectorParameter{V,T,U}(p.key, newvalue, p.valuebounds, p.transform_parameterization,
p.transform, p.prior, p.fixed, p.regimes, p.description, p.tex_label)
end
"""
```
parameter(p::ScaledParameter{S,T,U}, newvalue::S) where {S<:Real, T<:Number,U<:Transform}
```
Returns a ScaledParameter with value field equal to `newvalue` and scaledvalue field equal
to `p.scaling(newvalue)`. If `p` is a fixed parameter, it is returned unchanged.
"""
function parameter(p::ScaledParameter{T,U}, newvalue::T) where {T <: Number, U <: Transform} #S:<Real, Snew:< Real
p.fixed && return p # if the parameter is fixed, don't change its value
a,b = p.valuebounds
if !(a <= newvalue <= b)
throw(ParamBoundsError("New value of $(string(p.key)) ($(newvalue)) is out of bounds ($(p.valuebounds))"))
end
ScaledParameter{T,U}(p.key, newvalue, p.scaling(newvalue), p.valuebounds,
p.transform_parameterization, p.transform, p.prior, p.fixed,
p.scaling, p.regimes, p.description, p.tex_label)
end
function parameter_ad(p::ScaledParameterAD{S,T,U}, newvalue::Snew;
change_value_type::Bool = false) where {S<:Real, Snew<:Real, T<:Number, U<:Transform}
p.fixed && return p # if the parameter is fixed, don't change its value
if !change_value_type && (typeof(p.value) != typeof(newvalue))
error("Type of newvalue $(newvalue) does not match value of parameter $(string(p.key)).")
end
a,b = p.valuebounds
if !(a <= newvalue <= b)
throw(ParamBoundsError("New value of $(string(p.key)) ($(newvalue)) is out of bounds ($(p.valuebounds))"))
end
if change_value_type
ScaledParameterAD{Snew,T,U}(p.key, newvalue, p.scaling(newvalue), p.valuebounds,
p.transform_parameterization, p.transform, p.prior, p.fixed,
p.scaling, p.regimes, p.description, p.tex_label)
else
ScaledParameterAD{S,T,U}(p.key, newvalue, p.scaling(newvalue), p.valuebounds,
p.transform_parameterization, p.transform, p.prior, p.fixed,
p.scaling, p.regimes, p.description, p.tex_label)
end
end
function parameter(p::ScaledVectorParameter{V,T,U}, newvalue::V) where {V <: Vector, T <: Number, U <: Transform}
p.fixed && return p # if the parameter is fixed, don't change its value
a,b = p.valuebounds
if !all(a .<= newvalue .<= b)
throw(ParamBoundsError("New value of $(string(p.key)) ($(newvalue)) is out of bounds ($(p.valuebounds))"))
end
ScaledVectorParameter{V,T,U}(p.key, newvalue, p.scaling.(newvalue), p.valuebounds,
p.transform_parameterization, p.transform, p.prior, p.fixed,
p.scaling, p.regimes, p.description, p.tex_label)
end
function Base.show(io::IO, p::Parameter{T,U}) where {T, U} #S,T,U
@printf io "%s\n" typeof(p)
@printf io "(:%s)\n%s\n" p.key p.description
@printf io "LaTeX label: %s\n" p.tex_label
@printf io "-----------------------------\n"
#@printf io "real value: %+6f\n" transform_to_real_line(p)
@printf io "unscaled, untransformed value: %+6f\n" p.value
isa(p,ScaledParameter) && @printf "scaled, untransformed value: %+6f\n" p.scaledvalue
#!isa(U(),Untransformed) && @printf io "transformed value: %+6f\n" p.value
if hasprior(p)
@printf io "prior distribution:\n\t%s\n" get(p.prior)
else
@printf io "prior distribution:\n\t%s\n" "no prior"
end
@printf io "transformation for csminwel:\n\t%s" U()
@printf io "parameter is %s\n" p.fixed ? "fixed" : "not fixed"
end
function Base.show(io::IO, p::ParameterAD{S,T,U}) where {S,T,U}
@printf io "%s\n" typeof(p)
@printf io "(:%s)\n%s\n" p.key p.description
@printf io "LaTeX label: %s\n" p.tex_label
@printf io "-----------------------------\n"
#@printf io "real value: %+6f\n" transform_to_real_line(p)
@printf io "unscaled, untransformed value: %+6f\n" p.value
isa(p,ScaledParameter) && @printf "scaled, untransformed value: %+6f\n" p.scaledvalue
#!isa(U(),Untransformed) && @printf io "transformed value: %+6f\n" p.value
if hasprior(p)
@printf io "prior distribution:\n\t%s\n" get(p.prior)
else
@printf io "prior distribution:\n\t%s\n" "no prior"
end
@printf io "transformation for csminwel:\n\t%s" U()
@printf io "parameter is %s\n" p.fixed ? "fixed" : "not fixed"
end
function Base.show(io::IO, p::VectorParameter{V,T,U}) where {V,T, U}
@printf io "%s\n" typeof(p)
@printf io "(:%s)\n%s\n" p.key p.description
@printf io "LaTeX label: %s\n" p.tex_label
@printf io "-----------------------------\n"
#@printf io "real value: %+6f\n" transform_to_real_line(p)
join([@printf io "%+6f\n" x for x in p.value], ", ")
#isa(p,ScaledParameter) && @printf "scaled, untransformed value: %+6f\n" p.scaledvalue
#!isa(U(),Untransformed) && @printf io "transformed value: %+6f\n" p.value
if hasprior(p)
@printf io "prior distribution:\n\t%s\n" get(p.prior)
else
@printf io "prior distribution:\n\t%s\n" "no prior"
end
@printf io "transformation for csminwel:\n\t%s" U()
@printf io "parameter is %s\n" p.fixed ? "fixed" : "not fixed"
end
function Base.show(io::IO, p::SteadyStateParameter{T}) where {T}
@printf io "%s\n" typeof(p)
@printf io "(:%s)\n%s\n" p.key p.description
@printf io "LaTeX label: %s\n" p.tex_label
@printf io "-----------------------------\n"
@printf io "value: %+6f\n" p.value
end
function Base.show(io::IO, p::SteadyStateParameterGrid{T}) where {T}
@printf io "%s\n" typeof(p)
@printf io "(:%s)\n%s\n" p.key p.description
@printf io "LaTeX label: %s\n" p.tex_label
@printf io "-----------------------------\n"
@printf io "value: [%f,...,%f]" p.value[1] p.value[end]
end
"""
```
transform_to_model_space{S<:Real,T<:Number, U<:Transform}(p::Parameter{S,T,U}, x::S)
```
Transforms `x` from the real line to lie between `p.valuebounds` without updating `p.value`.
The transformations are defined as follows, where (a,b) = p.transform_parameterization and c
a scalar (default=1):
- Untransformed: `x`
- SquareRoot: `(a+b)/2 + (b-a)/2 * c * x/sqrt(1 + c^2 * x^2)`
- Exponential: `a + exp(c*(x-b))`
"""
transform_to_model_space(p::ParameterAD{S,<:Number,Untransformed}, x::S) where S = x
function transform_to_model_space(p::ParameterAD{S,<:Number,SquareRoot}, x::S) where S
(a,b), c = p.transform_parameterization, one(S)
(a+b)/2 + (b-a)/2*c*x/sqrt(1 + c^2 * x^2)
end
transform_to_model_space(p::Parameter{T,Untransformed}, x::T) where T = x
function transform_to_model_space(p::Parameter{T,SquareRoot}, x::T) where T
(a,b), c = p.transform_parameterization, one(T)
(a+b)/2 + (b-a)/2*c*x/sqrt(1 + c^2 * x^2)
end
function transform_to_model_space(p::ParameterAD{S,<:Number,Exponential}, x::S) where S
(a,b), c = p.transform_parameterization, one(S)
a + exp(c*(x-b))
end
function transform_to_model_space(p::Parameter{T,Exponential}, x::T) where T
(a,b), c = p.transform_parameterization, one(T)
a + exp(c*(x-b))
end
@inline function transform_to_model_space(pvec::ParameterVector{T}, values::Vector{T};
regime_switching::Bool = false) where T
if regime_switching
# Transform values in the first regime
output = similar(values)
plen = length(pvec)
map!(transform_to_model_space, output, pvec, values[1:plen])
# Now transform values in the second regime and on
i = 0
for p in pvec
if !isempty(p.regimes)
for (k, v) in p.regimes[:value]
if k != 1 # Skip the first regime.
i += 1 # `values` stores regime values (after the first regime) beside each other.
output[plen + i] = transform_to_model_space(p, values[plen + i])
end
end
end
end
return output
else
return map(transform_to_model_space, pvec, values)
end
end
@inline function transform_to_model_space(pvec::ParameterVector, values::Vector{S};
regime_switching::Bool = false) where S
if regime_switching
# Transform values in the first regime
output = similar(values)
plen = length(pvec)
map!(transform_to_model_space, output, pvec, values[1:plen])
# Now transform values in the second regime and on
i = 0
for p in pvec
if !isempty(p.regimes)
for (k, v) in p.regimes[:value]
if k != 1 # Skip the first regime.
i += 1 # `values` stores regime values (after the first regime) beside each other.
output[plen + i] = transform_to_model_space(p, values[plen + i])
end
end
end
end
return output
else
return map(transform_to_model_space, pvec, values)
end
end
"""
```
differentiate_transform_to_model_space{S<:Real,T<:Number, U<:Transform}(p::Parameter{S,T,U}, x::S)
```
Differentiates the transform of `x` from the real line to lie between `p.valuebounds`
The transformations are defined as follows, where (a,b) = p.transform_parameterization and c
a scalar (default=1):
- Untransformed: `x`
- SquareRoot: `(a+b)/2 + (b-a)/2 * c * x/sqrt(1 + c^2 * x^2)`
- Exponential: `a + exp(c*(x-b))`
Their gradients are therefore
- Untransformed: `1`
- SquareRoot: `(b-a)/2 * c / (1 + c^2 * x^2)^(3/2)`
- Exponential: `c * exp(c*(x-b))`
"""
differentiate_transform_to_model_space(p::ParameterAD{S,<:Number,Untransformed}, x::S) where S = one(S)
function differentiate_transform_to_model_space(p::ParameterAD{S,<:Number,SquareRoot}, x::S) where S
(a,b), c = p.transform_parameterization, one(S)
(b-a)/2 * c / (1 + c^2 * x^2)^(3/2)
end
function differentiate_transform_to_model_space(p::ParameterAD{S,<:Number,Exponential}, x::S) where S
(a,b), c = p.transform_parameterization, one(S)
c * exp(c*(x-b))
end
differentiate_transform_to_model_space(pvec::ParameterVector, values::Vector{S}) where S = map(differentiate_transform_to_model_space, pvec, values)
"""
```
transform_to_real_line(p::Parameter{S,T,U}, x::S = p.value) where {S<:Real, T<:Number, U<:Transform}
```
Transforms `p.value` from model space (between `p.valuebounds`) to the real line, without updating
`p.value`. The transformations are defined as follows,
where (a,b) = p.transform_parameterization, c a scalar (default=1), and x = p.value:
- Untransformed: x
- SquareRoot: (1/c)*cx/sqrt(1 - cx^2), where cx = 2 * (x - (a+b)/2)/(b-a)
- Exponential: b + (1 / c) * log(x-a)
"""
transform_to_real_line(p::ParameterAD{S,<:Number,Untransformed}, x::S = p.value) where S = x
function transform_to_real_line(p::ParameterAD{S,<:Number,SquareRoot}, x::S = p.value) where S
(a,b), c = p.transform_parameterization, one(S)
cx = 2. * (x - (a+b)/2.)/(b-a)
if cx^2 >1
println("Parameter is: $(p.key)")
println("a is $a")
println("b is $b")
println("x is $x")
println("cx is $cx")
error("invalid parameter value")
end
(1/c)*cx/sqrt(1 - cx^2)
end
function transform_to_real_line(p::ParameterAD{S,<:Number,Exponential}, x::S = p.value) where S
(a,b),c = p.transform_parameterization,one(S)
b + (1 ./ c) * log(x-a)
end
transform_to_real_line(pvec::ParameterVector, values::Vector{S}) where S = map(transform_to_real_line, pvec, values)
transform_to_real_line(pvec::ParameterVector{S}) where S = map(transform_to_real_line, pvec)
transform_to_real_line(p::Parameter{T,Untransformed}, x::T = p.value) where T = x
function transform_to_real_line(p::Parameter{T,SquareRoot}, x::T = p.value) where T
(a,b), c = p.transform_parameterization, one(T)
cx = 2. * (x - (a+b)/2.)/(b-a)
if cx^2 >1
println("Parameter is: $(p.key)")
println("a is $a")
println("b is $b")
println("x is $x")
println("cx is $cx")
error("invalid paramter value")
end
(1/c)*cx/sqrt(1 - cx^2)
end
function transform_to_real_line(p::Parameter{T,Exponential}, x::T = p.value) where T
(a,b),c = p.transform_parameterization,one(T)
b + (1 ./ c) * log(x-a)
end
@inline function transform_to_real_line(pvec::ParameterVector{T}, values::Vector{T}; regime_switching::Bool = false) where T
if regime_switching
# Transform values in the first regime
output = similar(values)
plen = length(pvec)
map!(transform_to_real_line, output, pvec, values[1:plen])
# Now transform values in the second regime and on
i = 0
for p in pvec
if !isempty(p.regimes)
for (k, v) in p.regimes[:value]
if k != 1 # Skip the first regime.
i += 1 # `values` stores regime values (after the first regime) beside each other.
output[plen + i] = transform_to_real_line(p, values[plen + i])
end
end
end
end
return output
else
map(transform_to_real_line, pvec, values)
end
end
@inline function transform_to_real_line(pvec::ParameterVector{T}; regime_switching::Bool = false) where T
if regime_switching
values = get_values(pvec) # regime-switching parameters returned by default
# Transform values in the first regime
plen = length(pvec) # since values is not passed, we can mutate values directly to avoid extra allocations
map!(transform_to_real_line, (@view values[1:plen]), pvec, values[1:plen])
# Now transform values in the second regime and on
i = 0
for p in pvec
if !isempty(p.regimes)
for (k, v) in p.regimes[:value]
if k != 1 # Skip the first regime.
i += 1 # `values` stores regime values (after the first regime) beside each other.
values[plen + i] = transform_to_real_line(p, values[plen + i])
end
end
end
end
return values
else
map(transform_to_real_line, pvec)
end
end
"""
```
differentiate_transform_to_real_line{S<:Real,T<:Number, U<:Transform}(p::Parameter{S,T,U}, x::S)
```
Differentiates the transform of `x` from the model space lying between `p.valuebounds` to the real line.
The transformations are defined as follows, where (a,b) = p.transform_parameterization and c
a scalar (default=1):
- Untransformed: x
- SquareRoot: (1/c)*cx/sqrt(1 - cx^2), where cx = 2 * (x - (a+b)/2)/(b-a)
- Exponential: b + (1 / c) * log(x-a)
Their gradients are therefore
- Untransformed: `1`
- SquareRoot: `(1/c) * (1 / ( 1 - cx^2)^(-3/2)) * (2/(b-a))`
- Exponential: `1 / (c * (x - a))`
"""
differentiate_transform_to_real_line(p::ParameterAD{S,<:Number,Untransformed}, x::S) where S = one(S)
function differentiate_transform_to_real_line(p::ParameterAD{S,<:Number,SquareRoot}, x::S) where S