/
history.jl
325 lines (253 loc) · 8.52 KB
/
history.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
using RecipesBase
import Base: getindex, setindex!, push!, keys, show
export ConvergenceHistory
export nprods, niters, nrests
########
# Type #
########
"""
Store general and in-depth information about an iterative method.
# Fields
`mvps::Int`: number of matrix vector products.
`mtvps::Int`: number of transposed matrix-vector products
`iters::Int`: iterations taken by the method.
`restart::T`: restart relevant information.
* `T == Int`: iterations per restart.
* `T == Nothing`: methods without restarts.
`isconverged::Bool`: convergence of the method.
`data::Dict{Symbol,Any}`: Stores all the information stored during the method execution.
It stores tolerances, residuals and other information, e.g. Ritz values in [`svdl`](@ref).
# Constructors
ConvergenceHistory()
ConvergenceHistory(restart)
Create `ConvergenceHistory` with empty fields.
# Arguments
`restart`: number of iterations per restart.
# Plots
Supports plots using the `Plots.jl` package via a type recipe. Vectors are
ploted as series and matrices as scatterplots.
# Implements
`Base`: `getindex`, `setindex!`, `push!`
"""
mutable struct ConvergenceHistory{T,K}
mvps::Int
mtvps::Int
iters::Int
restart::K
isconverged::Bool
data::Dict{Symbol, Any}
end
function ConvergenceHistory(;restart=nothing, partial=false)
ConvergenceHistory{!partial,typeof(restart)}(
0,0,0,restart,false,Dict{Symbol, Any}()
)
end
"""
Stores information of the current iteration.
"""
const PartialHistory = ConvergenceHistory{false}
"""
Stores the information of all the iterations.
"""
const CompleteHistory = ConvergenceHistory{true}
"""
History without resets.
"""
const UnrestartedHistory{T} = ConvergenceHistory{T, Nothing}
"""
History with resets.
"""
const RestartedHistory{T} = ConvergenceHistory{T, Int}
#############
# Functions #
#############
function show(io::IO, ch::ConvergenceHistory)
print(io, ch.isconverged ? "Converged" : "Not converged",
" after ", ch.iters, " iterations.")
end
"""
getindex(ch, s)
Get collection or tolerance associated with key `s` in `ch::ConvergenceHistory`.
getindex(ch, s, kwargs...)
Access elements of the collection associated with key `s` in `ch::ConvergenceHistory`.
"""
getindex(ch::ConvergenceHistory, s::Symbol) = ch.data[s]
getindex(ch::ConvergenceHistory, s::Symbol, kwargs...) = ch.data[s][kwargs...]
"""
setindex!(ch, tol, s)
Set tolerance value associated with `s` in `ch::ConvergenceHistory` to `tol`.
setindex!(ch, val, s, kwargs...)
Set collection element associated with key `s` in `ch::ConvergenceHistory` to val.
"""
setindex!(ch::ConvergenceHistory, val, s::Symbol) = ch.data[s] = val
setindex!(ch::ConvergenceHistory, val, s::Symbol, kwargs...) = ch.data[s][kwargs...] = val
"""
push!(ch, key, val)
Push contents of `val` to collection associated with `key` in `ch::ConvergenceHistory`.
"""
function push!(ch::ConvergenceHistory, key::Symbol, vec::Union{Vector,Tuple})
matrix = ch.data[key]
width = size(matrix,2)
iter = isa(ch,CompleteHistory) ? ch.iters : 1
base = (iter-1)*width
for i in 1:min(width,length(vec))
matrix[base+i] = vec[i]
end
end
push!(ch::ConvergenceHistory, key::Symbol, data) = push_custom_data!(ch, key, data)
push_custom_data!(ch::PartialHistory, key::Symbol, data) = ch.data[key] = data
push_custom_data!(ch::CompleteHistory, key::Symbol, data) = ch.data[key][ch.iters] = data
"""
reserve!(ch, key, maxiter)
reserve!(typ, key, maxiter)
reserve!(ch, key, maxiter, size)
reserve!(typ, ch, key, maxiter, size)
Reserve space for per iteration data in `ch`. If size is provided, instead of a
vector it will reserve matrix of dimensions `(maxiter, size)`.
# Arguments
`typ::Type`: Type of the elements to store. Defaults to `Float64` when not given.
`ch::ConvergenceHistory`: convergence history.
`key::Union{Symbol,Vector{Symbol}}`: key used to identify the data.
`maxiter::Int`: number of iterations to save space for.
`size::Int`: number of elements to store with the `key` identifier.
"""
function reserve!(ch::ConvergenceHistory, keys::Vector{Symbol}, kwargs...)
for key in keys
reserve!(ch, key, kwargs...)
end
end
function reserve!(ch::ConvergenceHistory, key::Symbol, kwargs...)
reserve!(Float64, ch, key, kwargs...)
end
function reserve!(typ::Type, ch::ConvergenceHistory, key::Symbol, kwargs...)
_reserve!(typ, ch, key, kwargs...)
end
# If PartialHistory, there's no need to store a vector or matrix, instead
# store nothing or store a vector respectively.
_reserve!(typ::Type, ch::PartialHistory, key::Symbol, ::Int) = nothing
function _reserve!(typ::Type, ch::PartialHistory, key::Symbol, ::Int, size::Int)
ch.data[key] = Vector{typ}(undef, size)
end
function _reserve!(typ::Type, ch::CompleteHistory, key::Symbol, len::Int)
ch.data[key] = Vector{typ}(undef, len)
end
function _reserve!(typ::Type, ch::CompleteHistory, key::Symbol, len::Int, size::Int)
ch.data[key] = Matrix{typ}(undef, len, size)
end
"""
shrink!(ml)
shrinks the reserved space for `ConvergenceHistory` `ch` to the space actually used to log.
"""
shrink!(::PartialHistory) = nothing
function shrink!(ch::CompleteHistory)
for key in keys(ch)
elem = ch.data[key]
if isa(elem, Vector)
resize!(elem, ch.iters)
elseif isa(elem, Matrix)
ch.data[key] = elem[1:ch.iters, :]
end
end
end
"""
nextiter!(ml)
Adds one the the number of iterations in [`ConvergenceHistory`](@ref) `ch`. This is
necessary to avoid overwriting information with `push!(ml)`. It is also able
to update other information of the method.
"""
function nextiter!(ch::ConvergenceHistory; mvps=0,mtvps=0)
ch.iters+=1
ch.mvps+=mvps
ch.mtvps+=mtvps
end
"""
keys(ch)
Key iterator of the per iteration data logged in `ConvergenceHistory` `ch`.
"""
keys(ch::ConvergenceHistory) = keys(ch.data)
"""
setconv(ml, val)
Set `val` as convergence status of the method in [`ConvergenceHistory`](@ref) ch.
"""
setconv(ch::ConvergenceHistory, val::Bool) = ch.isconverged=val
"""
nprods(ch)
Number of matrix-vector products plus transposed matrix-vector products
logged in `ConvergenceHistory` `ch`.
"""
nprods(ch::ConvergenceHistory) = ch.mvps+ch.mtvps
"""
niters(ch)
Number of iterations logged in `ConvergenceHistory` `ch`.
"""
niters(ch::ConvergenceHistory) = ch.iters
"""
nrests(ch)
Number of restarts logged in `ConvergenceHistory` `ch`.
"""
nrests(ch::RestartedHistory) = Int(ceil(ch.iters/ch.restart))
#########
# Plots #
#########
"""
plotable(x)
Determine whether a collection `x` is plotable. Only vectors and matrices are
such objects.
"""
plotable(::VecOrMat{T}) where {T <: Real} = true
plotable(::Any) = false
# Plot entire ConvergenceHistory. `sep` is the color of the restart separator.
@recipe function chef(ch::CompleteHistory; sep = :white)
candidates = collect(values(ch.data))
plotables = convert(Vector{Bool}, map(plotable, candidates))
n = length(filter(identity, plotables))
n > 0 || error("No plotables")
frame = 1
layout := (n, 1)
for (name, draw) in collect(ch.data)[plotables]
@series begin
isa(draw, Vector) && (seriestype:= :line; label:="$name")
isa(draw, Matrix) && (seriestype:= :scatter; title:="$name"; label:="")
subplot := frame
map(x->isnan(x) ? typeof(x)(0) : x,draw)
end
if isa(ch, RestartedHistory)
label := ""
linecolor := sep
left=1
maxy = round(maximum(draw); digits=2)
miny = round(minimum(draw); digits=2)
for restart in 2:nrests(ch)
@series begin
left+=ch.restart
subplot := frame
[left,left],[miny,maxy]
end
end
end
frame+=1
end
end
# Plot collection `ch[name]`. `sep` is the color of the restart separator.
@recipe function chef(ch::CompleteHistory, name::Symbol; sep = :white)
draw = ch[name]
plotable(draw) || error("Not plotable")
isa(draw, Vector) && (seriestype-->:line; label-->"$name")
isa(draw, Matrix) && (seriestype-->:scatter; title-->"$name"; label-->"")
@series begin
draw
end
if isa(ch, RestartedHistory)
label := ""
linecolor := sep
left=1
maxy = round(maximum(draw); digits=2)
miny = round(minimum(draw); digits=2)
for restart in 2:nrests(ch)
@series begin
left+=ch.restart
[left,left],[miny,maxy]
end
end
end
end