plot.py 13.2 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
from __future__ import division
import numpy as np
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
3
from ..import Field, RGSpace, HPSpace, GLSpace, PowerSpace, dobj
Martin Reinecke's avatar
Martin Reinecke committed
4
5
6
7
8
9
10
11
12
13
14
import os

# relevant properties:
# - x/y size
# - x/y/z log
# - x/y/z min/max
# - colorbar/colormap
# - axis on/off
# - title
# - axis labels

Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
15

Martin Reinecke's avatar
Martin Reinecke committed
16
17
18
def _mollweide_helper(xsize):
    xsize = int(xsize)
    ysize = xsize//2
Martin Reinecke's avatar
Martin Reinecke committed
19
    res = np.full(shape=(ysize, xsize), fill_value=np.nan, dtype=np.float64)
Martin Reinecke's avatar
Martin Reinecke committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
    xc = (xsize-1)*0.5
    yc = (ysize-1)*0.5
    u, v = np.meshgrid(np.arange(xsize), np.arange(ysize))
    u = 2*(u-xc)/(xc/1.02)
    v = (v-yc)/(yc/1.02)

    mask = np.where((u*u*0.25 + v*v) <= 1.)
    t1 = v[mask]
    theta = 0.5*np.pi-(
        np.arcsin(2/np.pi*(np.arcsin(t1) + t1*np.sqrt((1.-t1)*(1+t1)))))
    phi = -0.5*np.pi*u[mask]/np.maximum(np.sqrt((1-t1)*(1+t1)), 1e-6)
    phi = np.where(phi < 0, phi+2*np.pi, phi)
    return res, mask, theta, phi

Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
34

Martin Reinecke's avatar
Martin Reinecke committed
35
36
37
38
39
40
41
42
43
def _find_closest(A, target):
    # A must be sorted
    idx = A.searchsorted(target)
    idx = np.clip(idx, 1, len(A)-1)
    left = A[idx-1]
    right = A[idx]
    idx -= target - left < right - target
    return idx

Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
44

Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
45
def _mpl_makeplot(name):
46
    import matplotlib.pyplot as plt
Martin Reinecke's avatar
Martin Reinecke committed
47
    if dobj.rank != 0:
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
48
        return
Martin Reinecke's avatar
Martin Reinecke committed
49
50
51
52
    if name is None:
        plt.show()
        return
    extension = os.path.splitext(name)[1]
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
53
    if extension == ".pdf":
Martin Reinecke's avatar
Martin Reinecke committed
54
55
        plt.savefig(name)
        plt.close()
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
56
    elif extension == ".png":
Martin Reinecke's avatar
Martin Reinecke committed
57
58
        plt.savefig(name)
        plt.close()
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
59
60
61
62
63
64
65
66
67
68
    # elif extension==".html":
        # import mpld3
        # mpld3.save_html(plt.gcf(),fileobj=name,no_extras=True)
        # import plotly.offline as py
        # import plotly.tools as tls
        # plotly_fig = tls.mpl_to_plotly(plt.gcf())
        # py.plot(plotly_fig,filename=name)
        # py.plot_mpl(plt.gcf(),filename=name)
        # import bokeh
        # bokeh.mpl.to_bokeh(plt.gcf())
Martin Reinecke's avatar
Martin Reinecke committed
69
70
71
    else:
        raise ValueError("file format not understood")

Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
72

Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
73
def _mpl_limit_xy(**kwargs):
Martin Reinecke's avatar
Martin Reinecke committed
74
    import matplotlib.pyplot as plt
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
75
    x1, x2, y1, y2 = plt.axis()
Martin Reinecke's avatar
Martin Reinecke committed
76
77
78
79
    x1 = _get_kw("xmin", x1, **kwargs)
    x2 = _get_kw("xmax", x2, **kwargs)
    y1 = _get_kw("ymin", y1, **kwargs)
    y2 = _get_kw("xmax", y2, **kwargs)
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
80
81
    plt.axis((x1, x2, y1, y2))

Martin Reinecke's avatar
Martin Reinecke committed
82

Martin Reinecke's avatar
Martin Reinecke committed
83
84
85
86
87
88
89
90
91
def _register_cmaps():
    try:
        if _register_cmaps._cmaps_registered:
            return
    except AttributeError:
        _register_cmaps._cmaps_registered = True

    from matplotlib.colors import LinearSegmentedColormap
    import matplotlib.pyplot as plt
Martin Reinecke's avatar
Martin Reinecke committed
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
    planckcmap = {'red':   ((0., 0., 0.), (.4, 0., 0.), (.5, 1., 1.),
                            (.7, 1., 1.), (.8, .83, .83), (.9, .67, .67),
                            (1., .5, .5)),
                  'green': ((0., 0., 0.), (.2, 0., 0.), (.3, .3, .3),
                            (.4, .7, .7), (.5, 1., 1.), (.6, .7, .7),
                            (.7, .3, .3), (.8, 0., 0.), (1., 0., 0.)),
                  'blue':  ((0., .5, .5), (.1, .67, .67), (.2, .83, .83),
                            (.3, 1., 1.), (.5, 1., 1.), (.6, 0., 0.),
                            (1., 0., 0.))}
    he_cmap = {'red':   ((0., 0., 0.), (.167, 0., 0.), (.333, .5, .5),
                         (.5, 1., 1.), (1., 1., 1.)),
               'green': ((0., 0., 0.), (.5, 0., 0.), (.667, .5, .5),
                         (.833, 1., 1.), (1., 1., 1.)),
               'blue':  ((0., 0., 0.), (.167, 1., 1.), (.333, .5, .5),
                         (.5, 0., 0.), (1., 1., 1.))}
    fd_cmap = {'red':   ((0., .35, .35), (.1, .4, .4), (.2, .25, .25),
                         (.41, .47, .47), (.5, .8, .8), (.56, .96, .96),
                         (.59, 1., 1.), (.74, .8, .8), (.8, .8, .8),
                         (.9, .5, .5), (1., .4, .4)),
               'green': ((0., 0., 0.), (.2, 0., 0.), (.362, .88, .88),
                         (.5, 1., 1.), (.638, .88, .88), (.8, .25, .25),
                         (.9, .3, .3), (1., .2, .2)),
               'blue':  ((0., .35, .35), (.1, .4, .4), (.2, .8, .8),
                         (.26, .8, .8), (.41, 1., 1.), (.44, .96, .96),
                         (.5, .8, .8), (.59, .47, .47), (.8, 0., 0.),
                         (1., 0., 0.))}
    fdu_cmap = {'red':   ((0., 1., 1.), (0.1, .8, .8), (.2, .65, .65),
                          (.41, .6, .6), (.5, .7, .7), (.56, .96, .96),
                          (.59, 1., 1.), (.74, .8, .8), (.8, .8, .8),
                          (.9, .5, .5), (1., .4, .4)),
                'green': ((0., .9, .9), (.362, .95, .95), (.5, 1., 1.),
                          (.638, .88, .88), (.8, .25, .25), (.9, .3, .3),
                          (1., .2, .2)),
                'blue':  ((0., 1., 1.), (.1, .8, .8), (.2, 1., 1.),
                          (.41, 1., 1.), (.44, .96, .96), (.5, .7, .7),
                          (.59, .42, .42), (.8, 0., 0.), (1., 0., 0.))}
    pm_cmap = {'red':   ((0., 1., 1.), (.1, .96, .96), (.2, .84, .84),
                         (.3, .64, .64), (.4, .36, .36), (.5, 0., 0.),
                         (1., 0., 0.)),
               'green': ((0., .5, .5), (.1, .32, .32), (.2, .18, .18),
                         (.3, .8, .8),  (.4, .2, .2), (.5, 0., 0.),
                         (.6, .2, .2), (.7, .8, .8), (.8, .18, .18),
                         (.9, .32, .32), (1., .5, .5)),
               'blue':  ((0., 0., 0.), (.5, 0., 0.), (.6, .36, .36),
                         (.7, .64, .64), (.8, .84, .84), (.9, .96, .96),
                         (1., 1., 1.))}
Martin Reinecke's avatar
Martin Reinecke committed
138
139
140

    plt.register_cmap(cmap=LinearSegmentedColormap("Planck-like", planckcmap))
    plt.register_cmap(cmap=LinearSegmentedColormap("High Energy", he_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
141
    plt.register_cmap(cmap=LinearSegmentedColormap("Faraday Map", fd_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
142
143
    plt.register_cmap(cmap=LinearSegmentedColormap("Faraday Uncertainty",
                                                   fdu_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
144
    plt.register_cmap(cmap=LinearSegmentedColormap("Plus Minus", pm_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
145

Martin Reinecke's avatar
Martin Reinecke committed
146

Martin Reinecke's avatar
Martin Reinecke committed
147
def _get_kw(kwname, kwdefault=None, **kwargs):
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
148
149
    res = kwargs.get(kwname)
    return kwdefault if res is None else res
Martin Reinecke's avatar
Martin Reinecke committed
150
151


Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
152
def _mpl_plot(f, **kwargs):
153
    import matplotlib.pyplot as plt
Martin Reinecke's avatar
Martin Reinecke committed
154
    _register_cmaps()
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
155
    if not isinstance(f, Field):
Martin Reinecke's avatar
Martin Reinecke committed
156
        raise TypeError("incorrect data type")
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
157
    if len(f.domain) != 1:
Martin Reinecke's avatar
Martin Reinecke committed
158
159
160
        raise ValueError("input field must have exactly one domain")

    dom = f.domain[0]
Martin Reinecke's avatar
Martin Reinecke committed
161
    fig = plt.figure()
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
162
    ax = fig.add_subplot(1, 1, 1)
Martin Reinecke's avatar
Martin Reinecke committed
163

Martin Reinecke's avatar
Martin Reinecke committed
164
165
    xsize = _get_kw("xsize", 6, **kwargs)
    ysize = _get_kw("ysize", 6, **kwargs)
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
166
    fig.set_size_inches(xsize, ysize)
Martin Reinecke's avatar
Martin Reinecke committed
167
168
169
170
    ax.set_title(_get_kw("title", "", **kwargs))
    ax.set_xlabel(_get_kw("xlabel", "", **kwargs))
    ax.set_ylabel(_get_kw("ylabel", "", **kwargs))
    cmap = _get_kw("colormap", plt.rcParams['image.cmap'], **kwargs)
Martin Reinecke's avatar
Martin Reinecke committed
171
    if isinstance(dom, RGSpace):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
172
        if len(dom.shape) == 1:
Martin Reinecke's avatar
Martin Reinecke committed
173
174
            npoints = dom.shape[0]
            dist = dom.distances[0]
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
175
            xcoord = np.arange(npoints, dtype=np.float64)*dist
Martin Reinecke's avatar
Martin Reinecke committed
176
            ycoord = dobj.to_global_data(f.val)
Martin Reinecke's avatar
Martin Reinecke committed
177
            plt.plot(xcoord, ycoord)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
178
179
            _mpl_limit_xy(**kwargs)
            _mpl_makeplot(kwargs.get("name"))
Martin Reinecke's avatar
Martin Reinecke committed
180
            return
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
181
        elif len(dom.shape) == 2:
Martin Reinecke's avatar
Martin Reinecke committed
182
183
184
185
            nx = dom.shape[0]
            ny = dom.shape[1]
            dx = dom.distances[0]
            dy = dom.distances[1]
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
186
187
            xc = np.arange(nx, dtype=np.float64)*dx
            yc = np.arange(ny, dtype=np.float64)*dy
Martin Reinecke's avatar
Martin Reinecke committed
188
189
            im = ax.imshow(dobj.to_global_data(f.val),
                           extent=[xc[0], xc[-1], yc[0], yc[-1]],
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
190
                           vmin=kwargs.get("zmin"),
Martin Reinecke's avatar
Martin Reinecke committed
191
                           vmax=kwargs.get("zmax"), cmap=cmap, origin="lower")
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
192
193
194
195
            # from mpl_toolkits.axes_grid1 import make_axes_locatable
            # divider = make_axes_locatable(ax)
            # cax = divider.append_axes("right", size="5%", pad=0.05)
            # plt.colorbar(im,cax=cax)
Martin Reinecke's avatar
Martin Reinecke committed
196
            plt.colorbar(im)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
197
198
            _mpl_limit_xy(**kwargs)
            _mpl_makeplot(kwargs.get("name"))
Martin Reinecke's avatar
Martin Reinecke committed
199
200
            return
    elif isinstance(dom, PowerSpace):
Martin Reinecke's avatar
Martin Reinecke committed
201
        xcoord = dom.k_lengths
Martin Reinecke's avatar
Martin Reinecke committed
202
        ycoord = dobj.to_global_data(f.val)
Martin Reinecke's avatar
Martin Reinecke committed
203
204
205
206
        plt.xscale('log')
        plt.yscale('log')
        plt.title('power')
        plt.plot(xcoord, ycoord)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
207
208
        _mpl_limit_xy(**kwargs)
        _mpl_makeplot(kwargs.get("name"))
Martin Reinecke's avatar
Martin Reinecke committed
209
210
211
212
213
214
215
216
217
218
        return
    elif isinstance(dom, HPSpace):
        import pyHealpix
        xsize = 800
        res, mask, theta, phi = _mollweide_helper(xsize)

        ptg = np.empty((phi.size, 2), dtype=np.float64)
        ptg[:, 0] = theta
        ptg[:, 1] = phi
        base = pyHealpix.Healpix_Base(int(np.sqrt(f.val.size//12)), "RING")
Martin Reinecke's avatar
Martin Reinecke committed
219
        res[mask] = dobj.to_global_data(f.val)[base.ang2pix(ptg)]
Martin Reinecke's avatar
Martin Reinecke committed
220
        plt.axis('off')
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
221
        plt.imshow(res, vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
Martin Reinecke's avatar
Martin Reinecke committed
222
                   cmap=cmap, origin="lower")
Martin Reinecke's avatar
Martin Reinecke committed
223
        plt.colorbar(orientation="horizontal")
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
224
        _mpl_makeplot(kwargs.get("name"))
Martin Reinecke's avatar
Martin Reinecke committed
225
226
227
228
229
230
231
232
233
234
        return
    elif isinstance(dom, GLSpace):
        import pyHealpix
        xsize = 800
        res, mask, theta, phi = _mollweide_helper(xsize)
        ra = np.linspace(0, 2*np.pi, dom.nlon+1)
        dec = pyHealpix.GL_thetas(dom.nlat)
        ilat = _find_closest(dec, theta)
        ilon = _find_closest(ra, phi)
        ilon = np.where(ilon == dom.nlon, 0, ilon)
Martin Reinecke's avatar
Martin Reinecke committed
235
        res[mask] = dobj.to_global_data(f.val)[ilat*dom.nlon + ilon]
Martin Reinecke's avatar
Martin Reinecke committed
236
237

        plt.axis('off')
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
238
        plt.imshow(res, vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
Martin Reinecke's avatar
Martin Reinecke committed
239
                   cmap=cmap, origin="lower")
Martin Reinecke's avatar
Martin Reinecke committed
240
        plt.colorbar(orientation="horizontal")
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
241
        _mpl_makeplot(kwargs.get("name"))
Martin Reinecke's avatar
Martin Reinecke committed
242
243
244
        return

    raise ValueError("Field type not(yet) supported")
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
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


def _plotly_plot(f, **kwargs):
    if not isinstance(f, Field):
        raise TypeError("incorrect data type")
    if len(f.domain) != 1:
        raise ValueError("input field must have exactly one domain")

    dom = f.domain[0]
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    xsize = _get_kw("xsize", 6, **kwargs)
    ysize = _get_kw("ysize", 6, **kwargs)
    fig.set_size_inches(xsize, ysize)
    ax.set_title(_get_kw("title", "", **kwargs))
    ax.set_xlabel(_get_kw("xlabel", "", **kwargs))
    ax.set_ylabel(_get_kw("ylabel", "", **kwargs))
    cmap = _get_kw("colormap", plt.rcParams['image.cmap'], **kwargs)
    if isinstance(dom, RGSpace):
        if len(dom.shape) == 1:
            npoints = dom.shape[0]
            dist = dom.distances[0]
            xcoord = np.arange(npoints, dtype=np.float64)*dist
            ycoord = dobj.to_global_data(f.val)
            plt.plot(xcoord, ycoord)
            _mpl_limit_xy(**kwargs)
            _mpl_makeplot(kwargs.get("name"))
            return
        elif len(dom.shape) == 2:
            nx = dom.shape[0]
            ny = dom.shape[1]
            dx = dom.distances[0]
            dy = dom.distances[1]
            xc = np.arange(nx, dtype=np.float64)*dx
            yc = np.arange(ny, dtype=np.float64)*dy
            im = ax.imshow(dobj.to_global_data(f.val),
                           extent=[xc[0], xc[-1], yc[0], yc[-1]],
                           vmin=kwargs.get("zmin"),
                           vmax=kwargs.get("zmax"), cmap=cmap, origin="lower")
            # from mpl_toolkits.axes_grid1 import make_axes_locatable
            # divider = make_axes_locatable(ax)
            # cax = divider.append_axes("right", size="5%", pad=0.05)
            # plt.colorbar(im,cax=cax)
            plt.colorbar(im)
            _mpl_limit_xy(**kwargs)
            _mpl_makeplot(kwargs.get("name"))
            return
    elif isinstance(dom, PowerSpace):
        xcoord = dom.k_lengths
        ycoord = dobj.to_global_data(f.val)
        plt.xscale('log')
        plt.yscale('log')
        plt.title('power')
        plt.plot(xcoord, ycoord)
        _mpl_limit_xy(**kwargs)
        _mpl_makeplot(kwargs.get("name"))
        return
    elif isinstance(dom, HPSpace):
        import pyHealpix
        xsize = 800
        res, mask, theta, phi = _mollweide_helper(xsize)

        ptg = np.empty((phi.size, 2), dtype=np.float64)
        ptg[:, 0] = theta
        ptg[:, 1] = phi
        base = pyHealpix.Healpix_Base(int(np.sqrt(f.val.size//12)), "RING")
        res[mask] = dobj.to_global_data(f.val)[base.ang2pix(ptg)]
        plt.axis('off')
        plt.imshow(res, vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
                   cmap=cmap, origin="lower")
        plt.colorbar(orientation="horizontal")
        _mpl_makeplot(kwargs.get("name"))
        return
    elif isinstance(dom, GLSpace):
        import pyHealpix
        xsize = 800
        res, mask, theta, phi = _mollweide_helper(xsize)
        ra = np.linspace(0, 2*np.pi, dom.nlon+1)
        dec = pyHealpix.GL_thetas(dom.nlat)
        ilat = _find_closest(dec, theta)
        ilon = _find_closest(ra, phi)
        ilon = np.where(ilon == dom.nlon, 0, ilon)
        res[mask] = dobj.to_global_data(f.val)[ilat*dom.nlon + ilon]

        plt.axis('off')
        plt.imshow(res, vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
                   cmap=cmap, origin="lower")
        plt.colorbar(orientation="horizontal")
        _mpl_makeplot(kwargs.get("name"))
        return

    raise ValueError("Field type not(yet) supported")


def plot(f, **kwargs):
    extension = os.path.splitext(kwargs.get("name"))[1]
    if extension in [".html"]:
        _plotly_plot(f, **kwargs)
    elif extension in [".pdf", ".png"]:
        _mpl_plot(f, **kwargs)
    else:
        raise ValueError("unknown file name extension: " + extension)