-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParameterTable.jl
More file actions
284 lines (230 loc) · 8.53 KB
/
ParameterTable.jl
File metadata and controls
284 lines (230 loc) · 8.53 KB
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
abstract type AbstractParameterTable end
############################################################################################
### Types
############################################################################################
mutable struct ParameterTable{C, V} <: AbstractParameterTable
columns::C
variables::V
end
############################################################################################
### Constructors
############################################################################################
# constuct an empty table
function ParameterTable(::Nothing)
columns = Dict{Symbol, Any}(
:from => Vector{Symbol}(),
:parameter_type => Vector{Symbol}(),
:to => Vector{Symbol}(),
:free => Vector{Bool}(),
:value_fixed => Vector{Float64}(),
:start => Vector{Float64}(),
:estimate => Vector{Float64}(),
:identifier => Vector{Symbol}(),
:start => Vector{Float64}(),
)
variables = Dict{Symbol, Any}(
:latent_vars => Vector{Symbol}(),
:observed_vars => Vector{Symbol}(),
:sorted_vars => Vector{Symbol}(),
)
return ParameterTable(columns, variables)
end
############################################################################################
### Convert to other types
############################################################################################
import Base.Dict
function Dict(partable::ParameterTable)
return partable.columns
end
function DataFrame(partable::ParameterTable; columns = nothing)
if isnothing(columns)
columns = keys(partable.columns)
end
out = DataFrame([key => partable.columns[key] for key in columns])
return DataFrame(out)
end
############################################################################################
### Pretty Printing
############################################################################################
function Base.show(io::IO, partable::ParameterTable)
relevant_columns = [
:from,
:parameter_type,
:to,
:free,
:value_fixed,
:start,
:estimate,
:se,
:identifier,
]
existing_columns = [haskey(partable.columns, key) for key in relevant_columns]
as_matrix =
hcat([partable.columns[key] for key in relevant_columns[existing_columns]]...)
pretty_table(
io,
as_matrix,
header = (
relevant_columns[existing_columns],
eltype.([partable.columns[key] for key in relevant_columns[existing_columns]]),
),
tf = PrettyTables.tf_compact,
)
if haskey(partable.variables, :latent_vars)
print(io, "Latent Variables: $(partable.variables[:latent_vars]) \n")
end
if haskey(partable.variables, :observed_vars)
print(io, "Observed Variables: $(partable.variables[:observed_vars]) \n")
end
end
############################################################################################
### Additional Methods
############################################################################################
# Iteration --------------------------------------------------------------------------------
Base.getindex(partable::ParameterTable, i::Int) = (
partable.columns[:from][i],
partable.columns[:parameter_type][i],
partable.columns[:to][i],
partable.columns[:free][i],
partable.columns[:value_fixed][i],
partable.columns[:identifier][i],
)
function Base.length(partable::ParameterTable)
len = missing
for key in keys(partable.columns)
len = length(partable.columns[key])
break
end
return len
end
# Sorting ----------------------------------------------------------------------------------
struct CyclicModelError <: Exception
msg::AbstractString
end
Base.showerror(io::IO, e::CyclicModelError) = print(io, e.msg)
import Base.sort!, Base.sort
function sort!(partable::ParameterTable)
variables = [partable.variables[:latent_vars]; partable.variables[:observed_vars]]
is_regression =
(partable.columns[:parameter_type] .== :→) .&
(partable.columns[:from] .!= Symbol("1"))
to = partable.columns[:to][is_regression]
from = partable.columns[:from][is_regression]
sorted_variables = Vector{Symbol}()
sorted = false
while !sorted
acyclic = false
for (i, variable) in enumerate(variables)
if !(variable ∈ to)
push!(sorted_variables, variable)
deleteat!(variables, i)
delete_edges = from .!= variable
to = to[delete_edges]
from = from[delete_edges]
acyclic = true
end
end
if !acyclic
throw(CyclicModelError("your model is cyclic and therefore can not be ordered"))
end
acyclic = false
if length(variables) == 0
sorted = true
end
end
push!(partable.variables, :sorted_vars => sorted_variables)
return partable
end
function sort(partable::ParameterTable)
new_partable = deepcopy(partable)
sort!(new_partable)
return new_partable
end
# add a row --------------------------------------------------------------------------------
import Base.push!
function push!(partable::ParameterTable, d::AbstractDict)
for key in keys(d)
push!(partable.columns[key], d[key])
end
end
push!(partable::ParameterTable, d::Nothing) = nothing
############################################################################################
### Update Partable from Fitted Model
############################################################################################
# update generic ---------------------------------------------------------------------------
function update_partable!(
partable::ParameterTable,
model_identifier::AbstractDict,
vec,
column,
)
new_col = Vector{eltype(vec)}(undef, length(partable))
for (i, identifier) in enumerate(partable.columns[:identifier])
if !(identifier == :const)
new_col[i] = vec[model_identifier[identifier]]
elseif identifier == :const
new_col[i] = zero(eltype(vec))
end
end
push!(partable.columns, column => new_col)
return partable
end
"""
update_partable!(partable::AbstractParameterTable, sem_fit::SemFit, vec, column)
Write `vec` to `column` of `partable`.
# Arguments
- `vec::Vector`: has to be in the same order as the `model` parameters
"""
update_partable!(partable::AbstractParameterTable, sem_fit::SemFit, vec, column) =
update_partable!(partable, identifier(sem_fit), vec, column)
# update estimates -------------------------------------------------------------------------
"""
update_estimate!(
partable::AbstractParameterTable,
sem_fit::SemFit)
Write parameter estimates from `sem_fit` to the `:estimate` column of `partable`
"""
update_estimate!(partable::AbstractParameterTable, sem_fit::SemFit) =
update_partable!(partable, sem_fit, sem_fit.solution, :estimate)
# update starting values -------------------------------------------------------------------
"""
update_start!(partable::AbstractParameterTable, sem_fit::SemFit)
update_start!(partable::AbstractParameterTable, model::AbstractSem, start_val; kwargs...)
Write starting values from `sem_fit` or `start_val` to the `:estimate` column of `partable`.
# Arguments
- `start_val`: either a vector of starting values or a function to compute starting values
from `model`
- `kwargs...`: are passed to `start_val`
"""
update_start!(partable::AbstractParameterTable, sem_fit::SemFit) =
update_partable!(partable, sem_fit, sem_fit.start_val, :start)
function update_start!(
partable::AbstractParameterTable,
model::AbstractSem,
start_val;
kwargs...,
)
if !(start_val isa Vector)
start_val = start_val(model; kwargs...)
end
return update_partable!(partable, identifier(model), start_val, :start)
end
# update partable standard errors ----------------------------------------------------------
"""
update_se_hessian!(
partable::AbstractParameterTable,
sem_fit::SemFit;
hessian = :finitediff)
Write hessian standard errors computed for `sem_fit` to the `:se` column of `partable`
# Arguments
- `hessian::Symbol`: how to compute the hessian, see [se_hessian](@ref) for more information.
# Examples
"""
function update_se_hessian!(
partable::AbstractParameterTable,
sem_fit::SemFit;
hessian = :finitediff,
)
se = se_hessian(sem_fit; hessian = hessian)
return update_partable!(partable, sem_fit, se, :se)
end