plot.py 11.7 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from __future__ import division
import numpy as np
from ..import Field, RGSpace, HPSpace, GLSpace, PowerSpace
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
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def _mollweide_helper(xsize):
    xsize = int(xsize)
    ysize = xsize//2
    res = np.full(shape=(ysize, xsize), fill_value=np.nan,
                  dtype=np.float64)
    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
35

Martin Reinecke's avatar
Martin Reinecke committed
36
37
38
39
40
41
42
43
44
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
45

Martin Reinecke's avatar
Martin Reinecke committed
46
def _makeplot(name):
47
    import matplotlib.pyplot as plt
Martin Reinecke's avatar
Martin Reinecke committed
48
49
50
51
    if name is None:
        plt.show()
        return
    extension = os.path.splitext(name)[1]
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
52
    if extension == ".pdf":
Martin Reinecke's avatar
Martin Reinecke committed
53
54
        plt.savefig(name)
        plt.close()
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
55
    elif extension == ".png":
Martin Reinecke's avatar
Martin Reinecke committed
56
57
        plt.savefig(name)
        plt.close()
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
58
59
60
61
62
63
64
65
66
67
    # 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
68
69
70
    else:
        raise ValueError("file format not understood")

Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
71

Martin Reinecke's avatar
Martin Reinecke committed
72
73
def _limit_xy(**kwargs):
    import matplotlib.pyplot as plt
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
74
    x1, x2, y1, y2 = plt.axis()
Martin Reinecke's avatar
Martin Reinecke committed
75
76
77
78
79
80
81
82
    if (kwargs.get("xmin")) is not None:
        x1 = kwargs.get("xmin")
    if (kwargs.get("xmax")) is not None:
        x2 = kwargs.get("xmax")
    if (kwargs.get("ymin")) is not None:
        y1 = kwargs.get("ymin")
    if (kwargs.get("ymax")) is not None:
        y2 = kwargs.get("ymax")
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
83
84
    plt.axis((x1, x2, y1, y2))

Martin Reinecke's avatar
Martin Reinecke committed
85

Martin Reinecke's avatar
Martin Reinecke committed
86
87
88
89
90
91
92
93
94
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    planckcmap = {'red':   ((0.0, 0.0, 0.0),
                            (0.4, 0.0, 0.0),
                            (0.5, 1.0, 1.0),
                            (0.7, 1.0, 1.0),
                            (0.8, 0.83, 0.83),
                            (0.9, 0.67, 0.67),
                            (1.0, 0.5, 0.5)),
                  'green': ((0.0, 0.0, 0.0),
                            (0.2, 0.0, 0.0),
                            (0.3, 0.3, 0.3),
                            (0.4, 0.7, 0.7),
                            (0.5, 1.0, 1.0),
                            (0.6, 0.7, 0.7),
                            (0.7, 0.3, 0.3),
                            (0.8, 0.0, 0.0),
                            (1.0, 0.0, 0.0)),
                  'blue':  ((0.0, 0.5, 0.5),
                            (0.1, 0.67, 0.67),
                            (0.2, 0.83, 0.83),
                            (0.3, 1.0, 1.0),
                            (0.5, 1.0, 1.0),
                            (0.6, 0.0, 0.0),
                            (1.0, 0.0, 0.0))}
    he_cmap = {'red':   ((0.0, 0.0, 0.0),
Martin Reinecke's avatar
Martin Reinecke committed
119
120
121
122
                         (0.167, 0.0, 0.0),
                         (0.333, 0.5, 0.5),
                         (0.5, 1.0, 1.0),
                         (1.0, 1.0, 1.0)),
Martin Reinecke's avatar
Martin Reinecke committed
123
               'green': ((0.0, 0.0, 0.0),
Martin Reinecke's avatar
Martin Reinecke committed
124
125
126
127
                         (0.5, 0.0, 0.0),
                         (0.667, 0.5, 0.5),
                         (0.833, 1.0, 1.0),
                         (1.0, 1.0, 1.0)),
Martin Reinecke's avatar
Martin Reinecke committed
128
               'blue':  ((0.0, 0.0, 0.0),
Martin Reinecke's avatar
Martin Reinecke committed
129
130
131
                         (0.167, 1.0, 1.0),
                         (0.333, 0.5, 0.5),
                         (0.5, 0.0, 0.0),
Martin Reinecke's avatar
Martin Reinecke committed
132
133
                         (1.0, 1.0, 1.0))}
    fd_cmap = {'red':   ((0.0, 0.35, 0.35),
Martin Reinecke's avatar
Martin Reinecke committed
134
135
136
137
138
139
140
141
142
143
                         (0.1, 0.4, 0.4),
                         (0.2, 0.25, 0.25),
                         (0.41, 0.47, 0.47),
                         (0.5, 0.8, 0.8),
                         (0.56, 0.96, 0.96),
                         (0.59, 1.0, 1.0),
                         (0.74, 0.8, 0.8),
                         (0.8, 0.8, 0.8),
                         (0.9, 0.5, 0.5),
                         (1.0, 0.4, 0.4)),
Martin Reinecke's avatar
Martin Reinecke committed
144
               'green': ((0.0, 0.0, 0.0),
Martin Reinecke's avatar
Martin Reinecke committed
145
146
147
148
149
150
151
                         (0.2, 0.0, 0.0),
                         (0.362, 0.88, 0.88),
                         (0.5, 1.0, 1.0),
                         (0.638, 0.88, 0.88),
                         (0.8, 0.25, 0.25),
                         (0.9, 0.3, 0.3),
                         (1.0, 0.2, 0.2)),
Martin Reinecke's avatar
Martin Reinecke committed
152
               'blue':  ((0.0, 0.35, 0.35),
Martin Reinecke's avatar
Martin Reinecke committed
153
154
155
156
157
158
159
160
                         (0.1, 0.4, 0.4),
                         (0.2, 0.8, 0.8),
                         (0.26, 0.8, 0.8),
                         (0.41, 1.0, 1.0),
                         (0.44, 0.96, 0.96),
                         (0.5, 0.8, 0.8),
                         (0.59, 0.47, 0.47),
                         (0.8, 0.0, 0.0),
Martin Reinecke's avatar
Martin Reinecke committed
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
                         (1.0, 0.0, 0.0))}
    fdu_cmap = {'red':   ((0.0, 1.0, 1.0),
                          (0.1, 0.8, 0.8),
                          (0.2, 0.65, 0.65),
                          (0.41, 0.6, 0.6),
                          (0.5, 0.7, 0.7),
                          (0.56, 0.96, 0.96),
                          (0.59, 1.0, 1.0),
                          (0.74, 0.8, 0.8),
                          (0.8, 0.8, 0.8),
                          (0.9, 0.5, 0.5),
                          (1.0, 0.4, 0.4)),
                'green': ((0.0, 0.9, 0.9),
                          (0.2, 0.65, 0.65),
                          (0.362, 0.95, 0.95),
                          (0.5, 1.0, 1.0),
                          (0.638, 0.88, 0.88),
                          (0.8, 0.25, 0.25),
                          (0.9, 0.3, 0.3),
                          (1.0, 0.2, 0.2)),
                'blue':  ((0.0, 1.0, 1.0),
                          (0.1, 0.8, 0.8),
                          (0.2, 1.0, 1.0),
                          (0.41, 1.0, 1.0),
                          (0.44, 0.96, 0.96),
                          (0.5, 0.7, 0.7),
                          (0.59, 0.42, 0.42),
                          (0.8, 0.0, 0.0),
                          (1.0, 0.0, 0.0))}
    pm_cmap = {'red':   ((0.0, 1.0, 1.0),
Martin Reinecke's avatar
Martin Reinecke committed
191
192
193
194
195
196
                         (0.1, 0.96, 0.96),
                         (0.2, 0.84, 0.84),
                         (0.3, 0.64, 0.64),
                         (0.4, 0.36, 0.36),
                         (0.5, 0.0, 0.0),
                         (1.0, 0.0, 0.0)),
Martin Reinecke's avatar
Martin Reinecke committed
197
               'green': ((0.0, 0.5, 0.5),
Martin Reinecke's avatar
Martin Reinecke committed
198
199
200
201
202
203
204
205
206
207
                         (0.1, 0.32, 0.32),
                         (0.2, 0.18, 0.18),
                         (0.3, 0.08, 0.08),
                         (0.4, 0.02, 0.02),
                         (0.5, 0.0, 0.0),
                         (0.6, 0.02, 0.02),
                         (0.7, 0.08, 0.08),
                         (0.8, 0.18, 0.18),
                         (0.9, 0.32, 0.32),
                         (1.0, 0.5, 0.5)),
Martin Reinecke's avatar
Martin Reinecke committed
208
               'blue':  ((0.0, 0.0, 0.0),
Martin Reinecke's avatar
Martin Reinecke committed
209
210
211
212
213
                         (0.5, 0.0, 0.0),
                         (0.6, 0.36, 0.36),
                         (0.7, 0.64, 0.64),
                         (0.8, 0.84, 0.84),
                         (0.9, 0.96, 0.96),
Martin Reinecke's avatar
Martin Reinecke committed
214
                         (1.0, 1.0, 1.0))}
Martin Reinecke's avatar
Martin Reinecke committed
215
216
217

    plt.register_cmap(cmap=LinearSegmentedColormap("Planck-like", planckcmap))
    plt.register_cmap(cmap=LinearSegmentedColormap("High Energy", he_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
218
    plt.register_cmap(cmap=LinearSegmentedColormap("Faraday Map", fd_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
219
220
    plt.register_cmap(cmap=LinearSegmentedColormap("Faraday Uncertainty",
                                                   fdu_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
221
    plt.register_cmap(cmap=LinearSegmentedColormap("Plus Minus", pm_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
222

Martin Reinecke's avatar
Martin Reinecke committed
223

Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
224
def plot(f, **kwargs):
225
    import matplotlib.pyplot as plt
Martin Reinecke's avatar
Martin Reinecke committed
226
    _register_cmaps()
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
227
    if not isinstance(f, Field):
Martin Reinecke's avatar
Martin Reinecke committed
228
        raise TypeError("incorrect data type")
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
229
    if len(f.domain) != 1:
Martin Reinecke's avatar
Martin Reinecke committed
230
231
232
        raise ValueError("input field must have exactly one domain")

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

Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
236
    xsize, ysize = 6, 6
Martin Reinecke's avatar
Martin Reinecke committed
237
238
239
240
    if kwargs.get("xsize") is not None:
        xsize = kwargs.get("xsize")
    if kwargs.get("ysize") is not None:
        ysize = kwargs.get("ysize")
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
241
    fig.set_size_inches(xsize, ysize)
Martin Reinecke's avatar
Martin Reinecke committed
242

Martin Reinecke's avatar
Martin Reinecke committed
243
244
245
246
247
248
    if kwargs.get("title") is not None:
        ax.set_title(kwargs.get("title"))
    if kwargs.get("xlabel") is not None:
        ax.set_xlabel(kwargs.get("xlabel"))
    if kwargs.get("ylabel") is not None:
        ax.set_ylabel(kwargs.get("ylabel"))
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
249
    cmap = plt.rcParams['image.cmap']
Martin Reinecke's avatar
Martin Reinecke committed
250
251
    if kwargs.get("colormap") is not None:
        cmap = kwargs.get("colormap")
Martin Reinecke's avatar
Martin Reinecke committed
252
    if isinstance(dom, RGSpace):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
253
        if len(dom.shape) == 1:
Martin Reinecke's avatar
Martin Reinecke committed
254
255
            npoints = dom.shape[0]
            dist = dom.distances[0]
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
256
            xcoord = np.arange(npoints, dtype=np.float64)*dist
Martin Reinecke's avatar
Martin Reinecke committed
257
258
            ycoord = f.val
            plt.plot(xcoord, ycoord)
Martin Reinecke's avatar
Martin Reinecke committed
259
260
            _limit_xy(**kwargs)
            _makeplot(kwargs.get("name"))
Martin Reinecke's avatar
Martin Reinecke committed
261
            return
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
262
        elif len(dom.shape) == 2:
Martin Reinecke's avatar
Martin Reinecke committed
263
264
265
266
            nx = dom.shape[0]
            ny = dom.shape[1]
            dx = dom.distances[0]
            dy = dom.distances[1]
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
267
268
269
270
            xc = np.arange(nx, dtype=np.float64)*dx
            yc = np.arange(ny, dtype=np.float64)*dy
            im = ax.imshow(f.val, extent=[xc[0], xc[-1], yc[0], yc[-1]],
                           vmin=kwargs.get("zmin"),
Martin Reinecke's avatar
Martin Reinecke committed
271
                           vmax=kwargs.get("zmax"), cmap=cmap, origin="lower")
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
272
273
274
275
            # 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
276
277
278
            plt.colorbar(im)
            _limit_xy(**kwargs)
            _makeplot(kwargs.get("name"))
Martin Reinecke's avatar
Martin Reinecke committed
279
280
281
282
283
284
285
286
            return
    elif isinstance(dom, PowerSpace):
        xcoord = dom.kindex
        ycoord = f.val
        plt.xscale('log')
        plt.yscale('log')
        plt.title('power')
        plt.plot(xcoord, ycoord)
Martin Reinecke's avatar
Martin Reinecke committed
287
288
        _limit_xy(**kwargs)
        _makeplot(kwargs.get("name"))
Martin Reinecke's avatar
Martin Reinecke committed
289
290
291
292
293
294
295
296
297
298
299
300
        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] = f.val[base.ang2pix(ptg)]
        plt.axis('off')
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
301
        plt.imshow(res, vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
Martin Reinecke's avatar
Martin Reinecke committed
302
                   cmap=cmap, origin="lower")
Martin Reinecke's avatar
Martin Reinecke committed
303
304
        plt.colorbar(orientation="horizontal")
        _makeplot(kwargs.get("name"))
Martin Reinecke's avatar
Martin Reinecke committed
305
306
307
308
309
310
311
312
313
314
315
316
317
        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] = f.val[ilat*dom.nlon + ilon]

        plt.axis('off')
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
318
        plt.imshow(res, vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
Martin Reinecke's avatar
Martin Reinecke committed
319
                   cmap=cmap, origin="lower")
Martin Reinecke's avatar
Martin Reinecke committed
320
321
        plt.colorbar(orientation="horizontal")
        _makeplot(kwargs.get("name"))
Martin Reinecke's avatar
Martin Reinecke committed
322
323
324
        return

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