plot.py 15.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
Martin Reinecke's avatar
Martin Reinecke committed
14
# Copyright(C) 2013-2018 Max-Planck-Society
15
16
17
18
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik
# and financially supported by the Studienstiftung des deutschen Volkes.

19
from __future__ import absolute_import, division, print_function
20

Martin Reinecke's avatar
Martin Reinecke committed
21
22
import os

23
24
import numpy as np

Martin Reinecke's avatar
fix    
Martin Reinecke committed
25
26
27
28
29
30
from . import dobj
from .compat import *
from .domains.gl_space import GLSpace
from .domains.hp_space import HPSpace
from .domains.power_space import PowerSpace
from .domains.rg_space import RGSpace
31
from .domain_tuple import DomainTuple
Martin Reinecke's avatar
fix    
Martin Reinecke committed
32
from .field import Field
33

Martin Reinecke's avatar
Martin Reinecke committed
34
35
36
37
38
39
40
41
# 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
Martin Reinecke committed
42
# - labels
Martin Reinecke's avatar
Martin Reinecke committed
43

Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
44

Martin Reinecke's avatar
Martin Reinecke committed
45
46
47
def _mollweide_helper(xsize):
    xsize = int(xsize)
    ysize = xsize//2
Martin Reinecke's avatar
Martin Reinecke committed
48
    res = np.full(shape=(ysize, xsize), fill_value=np.nan, dtype=np.float64)
Martin Reinecke's avatar
Martin Reinecke committed
49
    xc, yc = (xsize-1)*0.5, (ysize-1)*0.5
Martin Reinecke's avatar
Martin Reinecke committed
50
    u, v = np.meshgrid(np.arange(xsize), np.arange(ysize))
Martin Reinecke's avatar
Martin Reinecke committed
51
    u, v = 2*(u-xc)/(xc/1.02), (v-yc)/(yc/1.02)
Martin Reinecke's avatar
Martin Reinecke committed
52
53
54
55
56
57
58
59
60

    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
61

62
63

def _rgb_data(spectral_cube):
64
65
66
67
68
69
70
71
72
73
74
    def _eye_sensitivity(energy_bins, spacing=None):
        from scipy.ndimage import zoom
        rgb_high = np.load('frequency_sensitivity.npy')

        # if spacing != None:
        #     spacing = np.arange(0, 1, 1 / energy_bins)

        rgb = zoom(rgb_high.T[1:],(1,energy_bins/len(rgb_high.T[0])))


        return np.clip(rgb,1e-15, rgb.max())
75
76
77
78
79
80
81
    rgb = _eye_sensitivity(spectral_cube.shape[-1])
    rgb_data = np.tensordot(spectral_cube, rgb, axes=[-1, -1])
    rgb_data = np.log(rgb_data)
    rgb_data -= rgb_data.min()
    rgb_data /= rgb_data.max()
    return rgb_data

Martin Reinecke's avatar
Martin Reinecke committed
82
83
def _find_closest(A, target):
    # A must be sorted
Martin Reinecke's avatar
Martin Reinecke committed
84
85
    idx = np.clip(A.searchsorted(target), 1, len(A)-1)
    idx -= target - A[idx-1] < A[idx] - target
Martin Reinecke's avatar
Martin Reinecke committed
86
87
    return idx

Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
88

Martin Reinecke's avatar
Martin Reinecke committed
89
def _makeplot(name):
90
    import matplotlib.pyplot as plt
Martin Reinecke's avatar
Martin Reinecke committed
91
    if dobj.rank != 0:
92
        plt.close()
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
93
        return
Martin Reinecke's avatar
Martin Reinecke committed
94
95
    if name is None:
        plt.show()
96
        plt.close()
Martin Reinecke's avatar
Martin Reinecke committed
97
98
        return
    extension = os.path.splitext(name)[1]
99
    if extension in (".pdf", ".png", ".svg"):
Martin Reinecke's avatar
Martin Reinecke committed
100
101
102
103
104
        plt.savefig(name)
        plt.close()
    else:
        raise ValueError("file format not understood")

Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
105

Martin Reinecke's avatar
Martin Reinecke committed
106
def _limit_xy(**kwargs):
Martin Reinecke's avatar
Martin Reinecke committed
107
    import matplotlib.pyplot as plt
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
108
    x1, x2, y1, y2 = plt.axis()
clienhar's avatar
clienhar committed
109
110
111
112
    x1 = kwargs.pop("xmin", x1)
    x2 = kwargs.pop("xmax", x2)
    y1 = kwargs.pop("ymin", y1)
    y2 = kwargs.pop("ymax", y2)
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
113
114
    plt.axis((x1, x2, y1, y2))

Martin Reinecke's avatar
Martin Reinecke committed
115

Martin Reinecke's avatar
Martin Reinecke committed
116
117
118
119
120
121
122
123
124
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
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
    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
171
172
173

    plt.register_cmap(cmap=LinearSegmentedColormap("Planck-like", planckcmap))
    plt.register_cmap(cmap=LinearSegmentedColormap("High Energy", he_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
174
    plt.register_cmap(cmap=LinearSegmentedColormap("Faraday Map", fd_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
175
176
    plt.register_cmap(cmap=LinearSegmentedColormap("Faraday Uncertainty",
                                                   fdu_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
177
    plt.register_cmap(cmap=LinearSegmentedColormap("Plus Minus", pm_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
178

Martin Reinecke's avatar
Martin Reinecke committed
179

Martin Reinecke's avatar
Martin Reinecke committed
180
def _plot(f, ax, **kwargs):
181
    import matplotlib.pyplot as plt
Martin Reinecke's avatar
Martin Reinecke committed
182
    _register_cmaps()
183
184
185
    if isinstance(f, Field):
        f = [f]
    if not isinstance(f, list):
Martin Reinecke's avatar
Martin Reinecke committed
186
        raise TypeError("incorrect data type")
187
188
189
190
191
    for i, fld in enumerate(f):
        if not isinstance(fld, Field):
            raise TypeError("incorrect data type")
        if i == 0:
            dom = fld.domain
192
193
            if (len(dom) > 2) or (len(dom) < 1):
                raise ValueError("input field must have either one domain or additionally an energy direction")
194
195
196
197
        else:
            if fld.domain != dom:
                raise ValueError("domain mismatch")
            if not (isinstance(dom[0], PowerSpace) or
198
                    (isinstance(dom[0], RGSpace) and len(dom[0].shape) == 1)):
199
                raise ValueError("PowerSpace or 1D RGSpace required")
Martin Reinecke's avatar
Martin Reinecke committed
200

clienhar's avatar
clienhar committed
201
    label = kwargs.pop("label", None)
202
    if not isinstance(label, list):
Martin Reinecke's avatar
Martin Reinecke committed
203
        label = [label] * len(f)
Martin Reinecke's avatar
Martin Reinecke committed
204

Martin Reinecke's avatar
Martin Reinecke committed
205
    linewidth = kwargs.pop("linewidth", 1.)
Philipp Arras's avatar
Philipp Arras committed
206
    if not isinstance(linewidth, list):
Martin Reinecke's avatar
Martin Reinecke committed
207
        linewidth = [linewidth] * len(f)
Philipp Arras's avatar
Philipp Arras committed
208

clienhar's avatar
clienhar committed
209
    alpha = kwargs.pop("alpha", None)
Philipp Arras's avatar
Philipp Arras committed
210
    if not isinstance(alpha, list):
Martin Reinecke's avatar
Martin Reinecke committed
211
        alpha = [alpha] * len(f)
Philipp Arras's avatar
Philipp Arras committed
212

Philipp Arras's avatar
Philipp Arras committed
213
214
    foo = kwargs.pop("norm", None)
    norm = {} if foo is None else {'norm': foo}
215

clienhar's avatar
clienhar committed
216
217
218
219
    ax.set_title(kwargs.pop("title", ""))
    ax.set_xlabel(kwargs.pop("xlabel", ""))
    ax.set_ylabel(kwargs.pop("ylabel", ""))
    cmap = kwargs.pop("colormap", plt.rcParams['image.cmap'])
220
    if isinstance(dom, DomainTuple):
Jakob Knollmueller's avatar
bbugfix    
Jakob Knollmueller committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
        if len(dom) == 2:
            if isinstance(dom[1], RGSpace):
                if isinstance(dom[0],RGSpace):
                    if len(dom[0].shape) == 2:
                        nx, ny = dom[0].shape
                        dx, dy = dom[0].distances
                        rgb = _rgb_data(f[0].to_global_data())
                        im = ax.imshow(
                            rgb, extent=[0, nx * dx, 0, ny * dy], origin="lower", **norm)
                        # 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)
                        _limit_xy(**kwargs)
                        return
                if isinstance(dom[0],(HPSpace, GLSpace)):
                    import pyHealpix
                    xsize = 800
                    res, mask, theta, phi = _mollweide_helper(xsize)
                    res = np.full(shape=res.shape+(3,), fill_value=1., dtype=np.float64)
241
                    rgb = _rgb_data(f[0].to_global_data())
Jakob Knollmueller's avatar
bbugfix    
Jakob Knollmueller committed
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
                    if isinstance(dom[0], HPSpace):
                        ptg = np.empty((phi.size, 2), dtype=np.float64)
                        ptg[:, 0] = theta
                        ptg[:, 1] = phi
                        base = pyHealpix.Healpix_Base(int(np.sqrt(dom[0].size // 12)), "RING")
                        res[mask] = rgb[base.ang2pix(ptg)]
                    else:
                        ra = np.linspace(0, 2 * np.pi, dom[0].nlon + 1)
                        dec = pyHealpix.GL_thetas(dom[0].nlat)
                        ilat = _find_closest(dec, theta)
                        ilon = _find_closest(ra, phi)
                        ilon = np.where(ilon == dom[0].nlon, 0, ilon)
                        res[mask] = rgb[ilat * dom[0].nlon + ilon]
                    plt.axis('off')
                    plt.imshow(res, origin="lower")
257
                    return
Jakob Knollmueller's avatar
bbugfix    
Jakob Knollmueller committed
258
    dom = dom[0]
Martin Reinecke's avatar
Martin Reinecke committed
259
    if isinstance(dom, RGSpace):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
260
        if len(dom.shape) == 1:
Martin Reinecke's avatar
Martin Reinecke committed
261
262
            npoints = dom.shape[0]
            dist = dom.distances[0]
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
263
            xcoord = np.arange(npoints, dtype=np.float64)*dist
Martin Reinecke's avatar
Martin Reinecke committed
264
            for i, fld in enumerate(f):
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
265
                ycoord = fld.to_global_data()
Martin Reinecke's avatar
Martin Reinecke committed
266
267
                plt.plot(xcoord, ycoord, label=label[i],
                         linewidth=linewidth[i], alpha=alpha[i])
Martin Reinecke's avatar
Martin Reinecke committed
268
            _limit_xy(**kwargs)
269
270
            if label != ([None]*len(f)):
                plt.legend()
Martin Reinecke's avatar
Martin Reinecke committed
271
            return
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
272
        elif len(dom.shape) == 2:
Martin Reinecke's avatar
Martin Reinecke committed
273
274
            nx, ny = dom.shape
            dx, dy = dom.distances
Martin Reinecke's avatar
Martin Reinecke committed
275
276
277
278
            im = ax.imshow(
                f[0].to_global_data().T, extent=[0, nx*dx, 0, ny*dy],
                vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
                cmap=cmap, origin="lower", **norm)
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
279
280
281
282
            # 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
283
            plt.colorbar(im)
Martin Reinecke's avatar
Martin Reinecke committed
284
            _limit_xy(**kwargs)
Martin Reinecke's avatar
Martin Reinecke committed
285
286
287
288
            return
    elif isinstance(dom, PowerSpace):
        plt.xscale('log')
        plt.yscale('log')
Philipp Arras's avatar
Philipp Arras committed
289
        xcoord = dom.k_lengths
Martin Reinecke's avatar
Martin Reinecke committed
290
        for i, fld in enumerate(f):
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
291
            ycoord = fld.to_global_data()
Martin Reinecke's avatar
Martin Reinecke committed
292
293
            plt.plot(xcoord, ycoord, label=label[i],
                     linewidth=linewidth[i], alpha=alpha[i])
Martin Reinecke's avatar
Martin Reinecke committed
294
        _limit_xy(**kwargs)
295
296
        if label != ([None]*len(f)):
            plt.legend()
Martin Reinecke's avatar
Martin Reinecke committed
297
        return
Martin Reinecke's avatar
Martin Reinecke committed
298
    elif isinstance(dom, (HPSpace, GLSpace)):
Martin Reinecke's avatar
Martin Reinecke committed
299
300
301
        import pyHealpix
        xsize = 800
        res, mask, theta, phi = _mollweide_helper(xsize)
Martin Reinecke's avatar
Martin Reinecke committed
302
303
304
305
306
307
308
309
310
311
312
313
314
        if isinstance(dom, HPSpace):
            ptg = np.empty((phi.size, 2), dtype=np.float64)
            ptg[:, 0] = theta
            ptg[:, 1] = phi
            base = pyHealpix.Healpix_Base(int(np.sqrt(f[0].size//12)), "RING")
            res[mask] = f[0].to_global_data()[base.ang2pix(ptg)]
        else:
            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[0].to_global_data()[ilat*dom.nlon + ilon]
Martin Reinecke's avatar
Martin Reinecke committed
315
        plt.axis('off')
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
316
        plt.imshow(res, vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
Martin Reinecke's avatar
Martin Reinecke committed
317
                   cmap=cmap, origin="lower")
Martin Reinecke's avatar
Martin Reinecke committed
318
        plt.colorbar(orientation="horizontal")
Martin Reinecke's avatar
Martin Reinecke committed
319
320
        return
    raise ValueError("Field type not(yet) supported")
Martin Reinecke's avatar
Martin Reinecke committed
321

Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
class Plot(object):
    def __init__(self):
        self._plots = []
        self._kwargs = []

    def add(self, f, **kwargs):
        """Add a figure to the current list of plots.

        Notes
        -----
        After doing one or more calls `plot()`, one also needs to call
        `plot_finish()` to output the result.

        Parameters
        ----------
        f: Field, or list of Field objects
            If `f` is a single Field, it must live over a single `RGSpace`,
            `PowerSpace`, `HPSpace`, `GLSPace`.
            If it is a list, all list members must be Fields living over the
            same one-dimensional `RGSpace` or `PowerSpace`.
        title: string
            title of the plot
        xlabel: string
            label for the x axis
        ylabel: string
            label for the y axis
        [xyz]min, [xyz]max: float
            limits for the values to plot
        colormap: string
            color map to use for the plot (if it is a 2D plot)
        linewidth: float or list of floats
            line width
        label: string of list of strings
            annotation string
        alpha: float or list of floats
            transparency value
        """
        self._plots.append(f)
        self._kwargs.append(kwargs)

    def output(self, **kwargs):
        """Plot the accumulated list of figures.

        Parameters
        ----------
        title: string
            title of the full plot
        nx, ny: integer (default: square root of the numer of plots, rounded up)
            number of subplots to use in x- and y-direction
        xsize, ysize: float (default: 6)
            dimensions of the full plot in inches
        name: string (default: "")
            if left empty, the plot will be shown on the screen,
            otherwise it will be written to a file with the given name.
            Supported extensions: .png and .pdf
        """
        import matplotlib.pyplot as plt
        nplot = len(self._plots)
        fig = plt.figure()
        if "title" in kwargs:
            plt.suptitle(kwargs.pop("title"))
        nx = kwargs.pop("nx", int(np.ceil(np.sqrt(nplot))))
        ny = kwargs.pop("ny", int(np.ceil(np.sqrt(nplot))))
        if nx*ny < nplot:
            raise ValueError(
                'Figure dimensions not sufficient for number of plots. '
                'Available plot slots: {}, number of plots: {}'
                .format(nx*ny, nplot))
        xsize = kwargs.pop("xsize", 6)
        ysize = kwargs.pop("ysize", 6)
        fig.set_size_inches(xsize, ysize)
        for i in range(nplot):
            ax = fig.add_subplot(ny, nx, i+1)
            _plot(self._plots[i], ax, **self._kwargs[i])
        fig.tight_layout()
        _makeplot(kwargs.pop("name", None))