-
Notifications
You must be signed in to change notification settings - Fork 10
/
CMBLensingPythonPlotExt.jl
349 lines (296 loc) · 10.1 KB
/
CMBLensingPythonPlotExt.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
module CMBLensingPythonPlotExt
using CMBLensing
if isdefined(Base, :get_extension)
using PythonPlot
using PythonPlot.PythonCall
else
using ..PythonPlot
using ..PythonPlot.PythonCall
end
using FFTW
using Loess
using Markdown
using Measurements
using StatsBase
### overloaded 1D plotting
for plot in (:(PythonPlot.plot), :(PythonPlot.loglog), :(PythonPlot.semilogx), :(PythonPlot.semilogy))
# Cℓs
@eval function ($plot)(ic::Cℓs, args...; kwargs...)
($plot)(ic.ℓ, ic.Cℓ, args...; kwargs...)
end
@eval function ($plot)(ic::NamedTuple{<:Any,<:NTuple{<:Any,<:Cℓs}}, args...; kwargs...)
($plot).(values(ic), args...; kwargs...)
end
@eval function ($plot)(ic::Cℓs{<:Measurement}, args...; kwargs...)
errorbar(ic.ℓ, Measurements.value.(ic.Cℓ), Measurements.uncertainty.(ic.Cℓ), args...; marker=".", ls="", capsize=2, kwargs...)
($plot) in [:loglog,:semilogx] && xscale("log")
($plot) in [:loglog,:semilogy] && yscale("log")
end
# Loess-interpolated
@eval function ($plot)(f::Function, m::Loess.LoessModel, args...; label=nothing, kwargs...)
l, = ($plot)(m.xs, f.(m.ys), ".", args...; kwargs...)
xs′ = vcat(map(1:length(m.xs)-1) do i
collect(range(m.xs[i],m.xs[i+1],length=10))[1:end-1]
end..., [last(m.xs)])
($plot)(xs′, f.(m.(xs′)), args...; c=l.get_color(), label, kwargs...)
end
@eval ($plot)(m::Loess.LoessModel, args...; kwargs...) = ($plot)(identity, m, args...; kwargs...)
# 1D KDE
@eval function ($plot)(f::Function, k::CMBLensing.GetDistKDE{1}, args...; kwargs...)
($plot)(k.kde.x, f.(k.kde.P), args...; kwargs...)
end
@eval ($plot)(k::CMBLensing.GetDistKDE{1}, args...; kwargs...) = ($plot)(identity, k, args...; kwargs...)
end
# 2D KDE
function PythonPlot.plot(k::CMBLensing.GetDistKDE{2}, args...; color=nothing, label=nothing, levels=[0.95,0.68], filled=true, kwargs...)
@unpack colors = pyimport("matplotlib")
args = k.kde.x, k.kde.y, k.kde.P, [pyconvert(Array, k.kde.getContourLevels(levels)); Inf]
if color == nothing
color = gca()._get_lines.get_next_color()
end
filled && contourf(args...; colors=[(pyconvert(Tuple, colors.to_rgb(color))..., α) for α in (0.4, 0.8)], kwargs...)
contour(args...; colors=color, label, kwargs...)
end
# Cℓ band
function PythonPlot.fill_between(ic::Cℓs{<:Measurement}, args...; kwargs...)
fill_between(
ic.ℓ,
((@. Measurements.value(ic.Cℓ) - x * Measurements.uncertainty(ic.Cℓ)) for x in (-1,1))...,
args...; kwargs...
)
end
### plotting CartesianFields
pretty_name(s) = pretty_name(Val.(Symbol.(split(string(s),"")))...)
pretty_name(::Val{s}, b::Val) where {s} = "$s "*pretty_name(b)
pretty_name(::Val{:x}) = "Map"
pretty_name(::Val{:l}) = "Fourier"
function _plot(f, ax, k, title, vlim, vscale, cmap; cbar=true, units=:deg, ticklabels=true, axeslabels=false, kwargs...)
@unpack Nx, Ny = fieldinfo(f)
ismap = endswith(string(k), "x")
# default values
if title == nothing
if f isa FlatS0
title = pretty_name(string(k)[2])
else
title = pretty_name(k)
end
if f isa LambertField
title *= " ($(Ny)x$(Nx) @ $(f.θpix)')"
elseif f isa EquiRectField
title *= " ($(Ny)x$(Nx))"
end
end
if vlim == nothing
vlim = ismap ? :sym : :asym
end
if vscale == nothing
vscale = ismap ? :linear : :log
end
if cmap == nothing
if ismap
cmap = get_cmap("RdBu_r")
else
cmap = get_cmap("viridis")
cmap.set_bad("lightgray")
end
end
# build array
if ismap
arr = Array(f[k])
else
arr = abs.(ifftshift(CMBLensing.unfold(Array(f[k]), Ny)))
end
if vscale == :log
arr[arr .== 0] .= NaN
end
# auto vlim's
if vlim==:sym
vmax = quantile(abs.(arr[@. !isnan(arr)][:]),0.999)
vmin = -vmax
elseif vlim==:asym
vmin, vmax = (quantile(arr[@. !isnan(arr)][:],q) for q=(0.001,0.999))
elseif isa(vlim,Tuple)
vmin, vmax = vlim
else
vmax = vlim
vmin = -vmax
end
# make the plot
if ismap
if f isa LambertField
extent = [-Nx,Nx,-Ny,Ny] .* f.θpix / 2 / Dict(:deg=>60,:arcmin=>1)[units]
aspect = 1
elseif f isa EquiRectField
extent = rad2deg.([f.φspan..., reverse(f.θspan)...]) .* Dict(:deg=>1,:arcmin=>60)[units]
aspect = abs(-(f.φspan...)) / abs(-(f.θspan...)) * sin(mean(f.θspan))
end
else
extent = [-1,1,-1,1] .* fieldinfo(f).nyquist
aspect = 1
end
norm = vscale == :log ? matplotlib.colors.LogNorm(;vmin,vmax) : matplotlib.colors.Normalize(;vmin,vmax)
cax = ax.matshow(
clamp.(arr, vmin, vmax);
extent, aspect, cmap, norm,
rasterized=true,
kwargs...
)
# annonate
if cbar
colorbar(cax,ax=ax,pad=0.01)
end
ax.set_title(title, y=1)
if ticklabels
if ismap
u = Dict(:deg=>"°", :arcmin=>"′")[units]
ax.xaxis.set_major_formatter("{x}"*u)
ax.yaxis.set_major_formatter("{x}"*u)
if axeslabels
if f isa LambertField
ax.set_xlabel("x")
ax.set_ylabel("y")
elseif f isa EquiRectField
ax.set_xlabel(L"\phi")
ax.set_ylabel(L"\theta")
end
end
else
ax.set_xlabel(raw"$\ell_x$")
ax.set_ylabel(raw"$\ell_y$")
ax.tick_params(axis="x", rotation=45)
end
ax.tick_params(labeltop=false, labelbottom=true)
else
ax.tick_params(labeltop=false, labelleft=false)
end
end
@doc doc"""
plot(f::Field; kwargs...)
plot(fs::VecOrMat{\<:Field}; kwarg...)
Plotting fields.
"""
PythonPlot.plot(f::Field; kwargs...) = plot([f]; kwargs...)
function PythonPlot.plot(D::DiagOp; kwargs...)
props = _sub_components[findfirst(((k,v),)->diag(D) isa @eval($k), _sub_components)][2]
plot(
[diag(D)];
which = permutedims([Symbol(p) for (p,_) in props if endswith(p,r"[lx]")]),
kwargs...
)
end
function PythonPlot.plot(
fs :: AbstractVecOrMat{F};
plotsize = 4,
which = default_which(fs),
title = nothing,
vlim = nothing,
vscale = nothing,
cmap = nothing,
return_all = false,
aspect = nothing,
kwargs...
) where {F<:CartesianField}
(m,n) = size(tuple.(fs, which)[:,:])
if isnothing(aspect)
aspect = all('x' in string(w) for w in [""] .* string.(which)) ? fs[1].Nx / fs[1].Ny : 1
end
figsize = plotsize .* [1.4 * n * aspect, m]
fig, axs = subplots(m, n; figsize, squeeze=false)
axs = getindex.(Ref(PyArray(axs)), 1:m, (1:n)') # see https://github.com/JuliaPy/PythonCall.jl/pull/487#issuecomment-456998345
_plot.(fs,axs,which,title,vlim,vscale,cmap; kwargs...)
if return_all
(fig, axs, which)
else
maybe_return_fig(fig)
end
end
default_which(::AbstractVecOrMat{<:CartesianS0}) = [:Ix]
default_which(::AbstractVecOrMat{<:CartesianS2}) = [:Ex :Bx]
default_which(::AbstractVecOrMat{<:EquiRectS2}) = [:Qx :Ux]
default_which(::AbstractVecOrMat{<:CartesianS02}) = [:Ix :Ex :Bx]
function default_which(fs::AbstractVecOrMat{<:CartesianField})
try
CMBLensing.ensuresame((default_which([f]) for f in fs)...)
catch x
x isa AssertionError ? throw(ArgumentError("Must specify `which` argument by hand for plotting this combination of fields.")) : rethrow()
end
end
### animations of CartesianFields
@doc doc"""
animate(fields::Vector{\<:Vector{\<:Field}}; interval=50, motionblur=false, kwargs...)
"""
CMBLensing.animate(f::AbstractVecOrMat{<:CartesianField}; kwargs...) = animate([f]; kwargs...)
CMBLensing.animate(annonate::Function, args...; kwargs...) = animate(args...; annonate=annonate, kwargs...)
function CMBLensing.animate(fields::AbstractVecOrMat{<:AbstractVecOrMat{<:CartesianField}}; fps=25, motionblur=false, annonate=nothing, filename=nothing, kwargs...)
fig, axs, which = plot(first.(fields); return_all=true, kwargs...)
motionblur = (motionblur == true) ? [0.1, 0.5, 1, 0.5, 0.1] : (motionblur == false) ? [1] : motionblur
if (annonate!=nothing); annonate(fig,axs,which); end
ani = pyimport("matplotlib.animation").FuncAnimation(
fig,
function (i)
for (f,ax,k) in tuple.(fields,axs,which)
if length(f)>1
img = ax.images[0]
img.set_data(sum(x*getindex(f[mod1(i-j+1,length(f))],k) for (j,x) in enumerate(motionblur)) / sum(motionblur))
end
end
first.(getproperty.(axs,:images))[:]
end,
1:maximum(length.(fields)[:]),
interval=1000/fps, blit=true
)
PythonPlot.close()
if filename!=nothing
ani.save(filename,writer="imagemagick",savefig_kwargs=Dict(:facecolor=>fig.get_facecolor()))
if endswith(filename,".gif")
run(`convert -layers Optimize $filename $filename`)
end
end
HTML(ani.to_html5_video())
end
### plotting HealpixFields
function PythonPlot.plot(f::HealpixMap; kwargs...)
pyimport("healpy").projview(
pyimport("numpy").array(Array(f.arr));
cmap = "RdBu_r",
graticule = true,
graticule_labels = true,
xlabel = L"\phi",
ylabel = L"\theta",
custom_ytick_labels = ["$(θ)°" for θ in 150:-30:30],
latitude_grid_spacing = 30,
cb_orientation = "vertical",
projection_type = "mollweide",
kwargs...
)
maybe_return_fig()
end
### convenience
# for plotting in environments that only show a plot if its the last thing returned
function PythonPlot.figure(plotfn::Function, args...; kwargs...)
figure(args...; kwargs...)
plotfn()
gcf()
end
function maybe_return_fig(fig = gcf())
if isdefined(Main,:IJulia) && Main.IJulia.inited
nothing # on IJulia, returning the figure can lead to it getting displayed twice
else
fig # returning the figure works on Juno/VSCode/Pluto
end
end
### chains
"""
plot_kde(samples; [boundary, normalize, smooth_scale_2D], kwargs...)
Plot a Kernel Density Estimate PDF for a set of 1D or 2D samples.
`boundary`, `normalize`, and `smooth_scale_2D` keyword arguments are
passed to to the underlying call to [`kde`](@ref), and all others are
passed to the underlying call to `plot`.
Based on Python [GetDist](https://getdist.readthedocs.io/en/latest/intro.html),
which must be installed.
"""
function plot_kde(samples; boundary=nothing, normalize=nothing, smooth_scale_2D=nothing, kwargs...)
kde_kwargs = filter(!isnothing∘last, Dict(pairs((;boundary,normalize,smooth_scale_2D))))
plot(kde(samples; kde_kwargs...); kwargs...)
end
end