plot.py 13.9 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/>.
#
14
# Copyright(C) 2013-2019 Max-Planck-Society
15
#
16
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik.
17

Martin Reinecke's avatar
Martin Reinecke committed
18 19
import os

20 21
import numpy as np

Martin Reinecke's avatar
fix  
Martin Reinecke committed
22 23 24
from . import dobj
from .domains.gl_space import GLSpace
from .domains.hp_space import HPSpace
Philipp Arras's avatar
Philipp Arras committed
25
from .domains.log_rg_space import LogRGSpace
Martin Reinecke's avatar
fix  
Martin Reinecke committed
26 27 28
from .domains.power_space import PowerSpace
from .domains.rg_space import RGSpace
from .field import Field
29

Martin Reinecke's avatar
Martin Reinecke committed
30 31 32 33 34 35 36 37
# 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
38
# - labels
Martin Reinecke's avatar
Martin Reinecke committed
39

Martin Reinecke's avatar
PEP8  
Martin Reinecke committed
40

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

    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
57

Martin Reinecke's avatar
Martin Reinecke committed
58 59
def _find_closest(A, target):
    # A must be sorted
Martin Reinecke's avatar
Martin Reinecke committed
60 61
    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
62 63
    return idx

Martin Reinecke's avatar
PEP8  
Martin Reinecke committed
64

Martin Reinecke's avatar
Martin Reinecke committed
65
def _makeplot(name):
66
    import matplotlib.pyplot as plt
Martin Reinecke's avatar
Martin Reinecke committed
67
    if dobj.rank != 0:
68
        plt.close()
Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
69
        return
Martin Reinecke's avatar
Martin Reinecke committed
70 71
    if name is None:
        plt.show()
72
        plt.close()
Martin Reinecke's avatar
Martin Reinecke committed
73 74
        return
    extension = os.path.splitext(name)[1]
75
    if extension in (".pdf", ".png", ".svg"):
Martin Reinecke's avatar
Martin Reinecke committed
76 77 78 79 80
        plt.savefig(name)
        plt.close()
    else:
        raise ValueError("file format not understood")

Martin Reinecke's avatar
PEP8  
Martin Reinecke committed
81

Martin Reinecke's avatar
Martin Reinecke committed
82
def _limit_xy(**kwargs):
Martin Reinecke's avatar
Martin Reinecke committed
83
    import matplotlib.pyplot as plt
Martin Reinecke's avatar
PEP8  
Martin Reinecke committed
84
    x1, x2, y1, y2 = plt.axis()
clienhar's avatar
clienhar committed
85 86 87 88
    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
89 90
    plt.axis((x1, x2, y1, y2))

Martin Reinecke's avatar
Martin Reinecke committed
91

Martin Reinecke's avatar
Martin Reinecke committed
92 93 94 95 96 97 98 99 100
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
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
    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
147 148 149

    plt.register_cmap(cmap=LinearSegmentedColormap("Planck-like", planckcmap))
    plt.register_cmap(cmap=LinearSegmentedColormap("High Energy", he_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
150
    plt.register_cmap(cmap=LinearSegmentedColormap("Faraday Map", fd_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
151 152
    plt.register_cmap(cmap=LinearSegmentedColormap("Faraday Uncertainty",
                                                   fdu_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
153
    plt.register_cmap(cmap=LinearSegmentedColormap("Plus Minus", pm_cmap))
Martin Reinecke's avatar
Martin Reinecke committed
154

Martin Reinecke's avatar
Martin Reinecke committed
155

156
def _plot1D(f, ax, **kwargs):
157
    import matplotlib.pyplot as plt
158

159 160 161 162 163
    for i, fld in enumerate(f):
        if not isinstance(fld, Field):
            raise TypeError("incorrect data type")
        if i == 0:
            dom = fld.domain
164 165
            if (len(dom) != 1):
                raise ValueError("input field must have exactly one domain")
166 167 168
        else:
            if fld.domain != dom:
                raise ValueError("domain mismatch")
169
    dom = dom[0]
Martin Reinecke's avatar
Martin Reinecke committed
170

clienhar's avatar
clienhar committed
171
    label = kwargs.pop("label", None)
172
    if not isinstance(label, list):
Martin Reinecke's avatar
Martin Reinecke committed
173
        label = [label] * len(f)
Martin Reinecke's avatar
Martin Reinecke committed
174

Martin Reinecke's avatar
Martin Reinecke committed
175
    linewidth = kwargs.pop("linewidth", 1.)
Philipp Arras's avatar
Philipp Arras committed
176
    if not isinstance(linewidth, list):
Martin Reinecke's avatar
Martin Reinecke committed
177
        linewidth = [linewidth] * len(f)
Philipp Arras's avatar
Philipp Arras committed
178

clienhar's avatar
clienhar committed
179
    alpha = kwargs.pop("alpha", None)
Philipp Arras's avatar
Philipp Arras committed
180
    if not isinstance(alpha, list):
Martin Reinecke's avatar
Martin Reinecke committed
181
        alpha = [alpha] * len(f)
Philipp Arras's avatar
Philipp Arras committed
182

clienhar's avatar
clienhar committed
183 184 185
    ax.set_title(kwargs.pop("title", ""))
    ax.set_xlabel(kwargs.pop("xlabel", ""))
    ax.set_ylabel(kwargs.pop("ylabel", ""))
186

Martin Reinecke's avatar
Martin Reinecke committed
187
    if isinstance(dom, RGSpace):
188
        plt.yscale(kwargs.pop("yscale", "linear"))
189 190 191 192 193 194 195 196 197 198 199
        npoints = dom.shape[0]
        dist = dom.distances[0]
        xcoord = np.arange(npoints, dtype=np.float64)*dist
        for i, fld in enumerate(f):
            ycoord = fld.to_global_data()
            plt.plot(xcoord, ycoord, label=label[i],
                     linewidth=linewidth[i], alpha=alpha[i])
        _limit_xy(**kwargs)
        if label != ([None]*len(f)):
            plt.legend()
        return
200
    elif isinstance(dom, LogRGSpace):
Martin Reinecke's avatar
fixes  
Martin Reinecke committed
201
        plt.yscale(kwargs.pop("yscale", "log"))
202 203 204 205 206 207 208 209 210 211
        npoints = dom.shape[0]
        xcoord = dom.t_0 + np.arange(npoints-1)*dom.bindistances[0]
        for i, fld in enumerate(f):
            ycoord = fld.to_global_data()[1:]
            plt.plot(xcoord, ycoord, label=label[i],
                     linewidth=linewidth[i], alpha=alpha[i])
        _limit_xy(**kwargs)
        if label != ([None]*len(f)):
            plt.legend()
        return
Martin Reinecke's avatar
Martin Reinecke committed
212
    elif isinstance(dom, PowerSpace):
213 214
        plt.xscale(kwargs.pop("xscale", "log"))
        plt.yscale(kwargs.pop("yscale", "log"))
Philipp Arras's avatar
Philipp Arras committed
215
        xcoord = dom.k_lengths
Martin Reinecke's avatar
Martin Reinecke committed
216
        for i, fld in enumerate(f):
Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
217
            ycoord = fld.to_global_data()
Martin Reinecke's avatar
Martin Reinecke committed
218 219
            plt.plot(xcoord, ycoord, label=label[i],
                     linewidth=linewidth[i], alpha=alpha[i])
Martin Reinecke's avatar
Martin Reinecke committed
220
        _limit_xy(**kwargs)
221 222
        if label != ([None]*len(f)):
            plt.legend()
Martin Reinecke's avatar
Martin Reinecke committed
223
        return
224 225 226 227 228 229 230 231
    raise ValueError("Field type not(yet) supported")


def _plot2D(f, ax, **kwargs):
    import matplotlib.pyplot as plt

    dom = f.domain

232 233
    if len(dom) > 1:
        raise ValueError("DomainTuple must have exactly one entry.")
234 235 236 237 238

    label = kwargs.pop("label", None)

    foo = kwargs.pop("norm", None)
    norm = {} if foo is None else {'norm': foo}
239 240
    aspect = kwargs.pop("aspect", None)
    aspect = {} if foo is None else {'aspect': foo}
241 242 243 244 245

    ax.set_title(kwargs.pop("title", ""))
    ax.set_xlabel(kwargs.pop("xlabel", ""))
    ax.set_ylabel(kwargs.pop("ylabel", ""))
    dom = dom[0]
246
    cmap = kwargs.pop("colormap", plt.rcParams['image.cmap'])
247 248 249 250

    if isinstance(dom, RGSpace):
        nx, ny = dom.shape
        dx, dy = dom.distances
251 252 253
        im = ax.imshow(
            f.to_global_data().T, extent=[0, nx*dx, 0, ny*dy],
            vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
254
            cmap=cmap, origin="lower", **norm, **aspect)
255
        plt.colorbar(im)
256 257
        _limit_xy(**kwargs)
        return
Martin Reinecke's avatar
Martin Reinecke committed
258
    elif isinstance(dom, (HPSpace, GLSpace)):
Martin Reinecke's avatar
Martin Reinecke committed
259 260 261
        import pyHealpix
        xsize = 800
        res, mask, theta, phi = _mollweide_helper(xsize)
Martin Reinecke's avatar
Martin Reinecke committed
262 263 264 265
        if isinstance(dom, HPSpace):
            ptg = np.empty((phi.size, 2), dtype=np.float64)
            ptg[:, 0] = theta
            ptg[:, 1] = phi
266
            base = pyHealpix.Healpix_Base(int(np.sqrt(dom.size//12)), "RING")
267
            res[mask] = f.to_global_data()[base.ang2pix(ptg)]
Martin Reinecke's avatar
Martin Reinecke committed
268 269 270 271 272 273
        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)
274
            res[mask] = f.to_global_data()[ilat*dom.nlon + ilon]
Martin Reinecke's avatar
Martin Reinecke committed
275
        plt.axis('off')
276 277
        plt.imshow(res, vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
                   cmap=cmap, origin="lower")
278
        plt.colorbar(orientation="horizontal")
279 280 281 282 283 284 285 286 287 288 289 290 291 292
        return
    raise ValueError("Field type not(yet) supported")


def _plot(f, ax, **kwargs):
    _register_cmaps()
    if isinstance(f, Field):
        f = [f]
    f = list(f)
    if len(f) == 0:
        raise ValueError("need something to plot")
    if not isinstance(f[0], Field):
            raise TypeError("incorrect data type")
    dom1 = f[0].domain
Martin Reinecke's avatar
Martin Reinecke committed
293 294
    if (len(dom1) == 1 and
        (isinstance(dom1[0], PowerSpace) or
295 296
            (isinstance(dom1[0], (RGSpace, LogRGSpace)) and
             len(dom1[0].shape) == 1))):
297 298 299 300 301 302
        _plot1D(f, ax, **kwargs)
        return
    else:
        if len(f) != 1:
            raise ValueError("need exactly one Field for 2D plot")
        _plot2D(f[0], ax, **kwargs)
Martin Reinecke's avatar
Martin Reinecke committed
303 304
        return
    raise ValueError("Field type not(yet) supported")
Martin Reinecke's avatar
Martin Reinecke committed
305

Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
306

307 308 309 310 311 312 313 314 315 316
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
        -----
Philipp Arras's avatar
Docs  
Philipp Arras committed
317 318
        After doing one or more calls `add()`, one needs to call `output()` to
        show or save the plot.
319 320 321

        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
322
        f: Field or list of Field
Philipp Arras's avatar
Philipp Arras committed
323
            If `f` is a single Field, it must be defined on a single `RGSpace`,
Martin Reinecke's avatar
typo  
Martin Reinecke committed
324
            `PowerSpace`, `HPSpace`, `GLSpace`.
Philipp Arras's avatar
Philipp Arras committed
325
            If it is a list, all list members must be Fields defined over the
326 327
            same one-dimensional `RGSpace` or `PowerSpace`.
        title: string
Philipp Arras's avatar
Docs  
Philipp Arras committed
328
            Title of the plot.
329
        xlabel: string
Philipp Arras's avatar
Philipp Arras committed
330
            Label for the x axis.
331
        ylabel: string
Philipp Arras's avatar
Philipp Arras committed
332
            Label for the y axis.
333
        [xyz]min, [xyz]max: float
Philipp Arras's avatar
Philipp Arras committed
334
            Limits for the values to plot.
335
        colormap: string
Philipp Arras's avatar
Philipp Arras committed
336
            Color map to use for the plot (if it is a 2D plot).
337
        linewidth: float or list of floats
Philipp Arras's avatar
Philipp Arras committed
338
            Line width.
339
        label: string of list of strings
Philipp Arras's avatar
Philipp Arras committed
340
            Annotation string.
341
        alpha: float or list of floats
Philipp Arras's avatar
Docs  
Philipp Arras committed
342
            Transparency value.
343 344 345 346 347 348 349 350 351 352
        """
        self._plots.append(f)
        self._kwargs.append(kwargs)

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

        Parameters
        ----------
        title: string
Philipp Arras's avatar
Philipp Arras committed
353 354 355 356 357 358 359 360
            Title of the full plot.
        nx, ny: int
            Number of subplots to use in x- and y-direction.
            Default: square root of the numer of plots, rounded up.
        xsize, ysize: float
            Dimensions of the full plot in inches. Default: 6.
        name: string
            If left empty, the plot will be shown on the screen,
361
            otherwise it will be written to a file with the given name.
Philipp Arras's avatar
Philipp Arras committed
362
            Supported extensions: .png and .pdf. Default: None.
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
        """
        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))