plot_utils.py 56.9 KB
Newer Older
Somnath, Suhas's avatar
Somnath, Suhas committed
1
2
3
4
5
6
# -*- coding: utf-8 -*-
"""
Created on Thu May 05 13:29:12 2016

@author: Suhas Somnath
"""
Chris Smith's avatar
Chris Smith committed
7
# TODO: All general plotting functions should support data with 1, 2, or 3 spatial dimensions.
Chris Smith's avatar
Chris Smith committed
8

9
from __future__ import division, print_function, absolute_import, unicode_literals
10
11

import inspect
Unknown's avatar
Unknown committed
12
import os
13
import sys
14
15
from warnings import warn

Chris Smith's avatar
merged    
Chris Smith committed
16
import h5py
17
import ipywidgets as widgets
18
import matplotlib as mpl
19
import matplotlib.pyplot as plt
20
21
import numpy as np
import scipy
22
from matplotlib.colors import LinearSegmentedColormap
23
from mpl_toolkits.axes_grid1 import ImageGrid
24
25
from scipy.signal import blackman

26
from ..io.hdf_utils import reshape_to_Ndims, get_formatted_labels, get_data_descriptor
27

28
29
30
31
32
33
34
35
36
37
38
# mpl.rcParams.keys()  # gets all allowable keys
mpl.rc('figure', figsize=(5,5))
mpl.rc('lines', linewidth=2)
mpl.rc('axes', labelsize=16, titlesize=16)
mpl.rc('figure', titlesize=20)
mpl.rc('font', size=14) # global font size
mpl.rc('legend', fontsize=16, fancybox=True)
mpl.rc('xtick.major', size=6)
mpl.rc('xtick.minor', size=4)
# mpl.rcParams['xtick.major.size'] = 6

39
40
if sys.version_info.major == 3:
    unicode = str
Somnath, Suhas's avatar
Somnath, Suhas committed
41

Somnath, Suhas's avatar
Somnath, Suhas committed
42
default_cmap = plt.cm.viridis
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
def set_tick_font_size(axes, font_size):
    """
    Sets the font size of the ticks in the provided axes

    Parameters
    ----------
    axes : matplotlib.pyplot.axis object or list of axis objects
        axes to set font sizes
    font_size : unigned int
        Font size
    """

    def __set_axis_tick(axis):
        """
        Sets the font sizes to the x and y axis in the given axis object

        Parameters
        ----------
        axis : matplotlib.pyplot.axis object
            axis to set font sizes
        """
        for tick in axis.xaxis.get_major_ticks():
            tick.label.set_fontsize(font_size)
        for tick in axis.yaxis.get_major_ticks():
            tick.label.set_fontsize(font_size)

    if hasattr(axes, '__iter__'):
        for axis in axes:
            __set_axis_tick(axis)
    else:
        __set_axis_tick(axes)

Somnath, Suhas's avatar
Somnath, Suhas committed
77

78
def make_scalar_mappable(vmin, vmax, cmap=None):
79
    """
80
    Creates a scalar mappable object that can be used to create a colorbar for non-image (e.g. - line) plots
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

    Parameters
    ----------
    vmin : float
        Minimum value for colorbar
    vmax : float
        Maximum value for colorbar
    cmap : colormap object
        Colormap object to use

    Returns
    -------
    sm : matplotlib.pyplot.cm.ScalarMappable object
        The object that can used to create a colorbar via plt.colorbar(sm)
    """
    if cmap is None:
        cmap = default_cmap

    sm = plt.cm.ScalarMappable(cmap=cmap,
                               norm=plt.Normalize(vmin=vmin, vmax=vmax))
    # fake up the array of the scalar mappable
    sm._A = []
    return sm


106
107
108
109
110
111
112
113
114
115
116
117
118
119
def cbar_for_line_plot(axis, num_steps, discrete_ticks=True, **kwargs):
    """
    Adds a colorbar next to a line plot axis

    Parameters
    ----------
    axis : axis handle
        Axis with multiple line objects
    num_steps : uint
        Number of steps in the colorbar
    discrete_ticks : (optional) bool
        Whether or not to have the ticks match the number of number of steps. Default = True
    """
    cmap = get_cmap_object(kwargs.pop('cmap', None))
120
    cmap = discrete_cmap(num_steps, cmap=cmap.name)
121
122
123
124
125
126
127
128
129
130
131

    sm = make_scalar_mappable(0, num_steps - 1, cmap=cmap, **kwargs)

    if discrete_ticks:
        kwargs.update({'ticks': np.arange(num_steps)})

    cbar = plt.colorbar(sm, ax=axis, orientation='vertical',
                        pad=0.04, use_gridspec=True, **kwargs)
    return cbar


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def get_cmap_object(cmap):
    """
    Get the matplotlib.colors.LinearSegmentedColormap object regardless of the input

    Parameters
    ----------
    cmap : String, or matplotlib.colors.LinearSegmentedColormap object (Optional)
        Requested color map
    Returns
    -------
    cmap : matplotlib.colors.LinearSegmentedColormap object
        Requested / Default colormap object
    """
    if cmap is None:
        return default_cmap
    elif isinstance(cmap, str):
        return plt.get_cmap(cmap)
    return cmap


152
153
154
155
156
157
158
def cmap_jet_white_center():
    """
    Generates the jet colormap with a white center

    Returns
    -------
    white_jet : matplotlib.colors.LinearSegmentedColormap object
159
        color map object that can be used in place of the default colormap
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
    """
    # For red - central column is like brightness
    # For blue - last column is like brightness
    cdict = {'red': ((0.00, 0.0, 0.0),
                     (0.30, 0.0, 0.0),
                     (0.50, 1.0, 1.0),
                     (0.90, 1.0, 1.0),
                     (1.00, 0.5, 1.0)),
             'green': ((0.00, 0.0, 0.0),
                       (0.10, 0.0, 0.0),
                       (0.42, 1.0, 1.0),
                       (0.58, 1.0, 1.0),
                       (0.90, 0.0, 0.0),
                       (1.00, 0.0, 0.0)),
             'blue': ((0.00, 0.0, 0.5),
                      (0.10, 1.0, 1.0),
                      (0.50, 1.0, 1.0),
                      (0.70, 0.0, 0.0),
                      (1.00, 0.0, 0.0))
             }
    return LinearSegmentedColormap('white_jet', cdict)
181

Somnath, Suhas's avatar
Somnath, Suhas committed
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
def cmap_from_rgba(name, interp_vals, normalization_val):
    """
    Generates a colormap given a matlab-style interpolation table

    Parameters
    ----------
    name : String / Unicode
        Name of the desired colormap
    interp_vals : List of tuples
        Interpolation table that describes the desired color map. Each entry in the table should be described as:
        (position in the colorbar, (red, green, blue, alpha))
        The position in the color bar, red, green, blue, and alpha vary from 0 to the normalization value
    normalization_val : number
        The common maximum value for the position in the color bar, red, green, blue, and alpha

    Returns
    -------
    new_cmap : matplotlib.colors.LinearSegmentedColormap object
        desired color map
    """

    normalization_val = np.round(1.0 * normalization_val)

    cdict = {'red': tuple([(dist / normalization_val, colors[0] / normalization_val, colors[0] / normalization_val)
                           for (dist, colors) in interp_vals][::-1]),
             'green': tuple([(dist / normalization_val, colors[1] / normalization_val, colors[1] / normalization_val)
                             for (dist, colors) in interp_vals][::-1]),
             'blue': tuple([(dist / normalization_val, colors[2] / normalization_val, colors[2] / normalization_val)
                            for (dist, colors) in interp_vals][::-1]),
             'alpha': tuple([(dist / normalization_val, colors[3] / normalization_val, colors[3] / normalization_val)
Unknown's avatar
Unknown committed
212
                             for (dist, colors) in interp_vals][::-1])}
Somnath, Suhas's avatar
Somnath, Suhas committed
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

    return LinearSegmentedColormap(name, cdict)


def make_linear_alpha_cmap(name, solid_color, normalization_val, min_alpha=0, max_alpha=1):
    """
    Generates a transparent to opaque color map based on a single solid color

    Parameters
    ----------
    name : String / Unicode
        Name of the desired colormap
    solid_color : List of numbers
        red, green, blue, and alpha values for a specific color
    normalization_val : number
        The common maximum value for the red, green, blue, and alpha values. This is 1 in matplotlib
    min_alpha : float (optional. Default = 0 : ie- transparent)
        Lowest alpha value for the bottom of the color bar
    max_alpha : float (optional. Default = 1 : ie- opaque)
        Highest alpha value for the top of the color bar

    Returns
    -------
    new_cmap : matplotlib.colors.LinearSegmentedColormap object
        transparent to opaque color map based on the provided color
    """
    solid_color = np.array(solid_color) / normalization_val * 1.0
    interp_table = [(1.0, (solid_color[0], solid_color[1], solid_color[2], max_alpha)),
                    (0, (solid_color[0], solid_color[1], solid_color[2], min_alpha))]
    return cmap_from_rgba(name, interp_table, 1)
Chris Smith's avatar
Chris Smith committed
243
244


Somnath, Suhas's avatar
Somnath, Suhas committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
def cmap_hot_desaturated():
    """
    Returns a desaturated color map based on the hot colormap

    Returns
    -------
    new_cmap : matplotlib.colors.LinearSegmentedColormap object
        Desaturated version of the hot color map
    """
    hot_desaturated = [(255.0, (255, 76, 76, 255)),
                       (218.5, (107, 0, 0, 255)),
                       (182.1, (255, 96, 0, 255)),
                       (145.6, (255, 255, 0, 255)),
                       (109.4, (0, 127, 0, 255)),
                       (72.675, (0, 255, 255, 255)),
                       (36.5, (0, 0, 91, 255)),
                       (0, (71, 71, 219, 255))]

    return cmap_from_rgba('hot_desaturated', hot_desaturated, 255)
Chris Smith's avatar
Chris Smith committed
264
265


266
def discrete_cmap(num_bins, cmap=None):
267
    """
268
    Create an N-bin discrete colormap from the specified input map specified
269
270
271
272
273

    Parameters
    ----------
    num_bins : unsigned int
        Number of discrete bins
274
    cmap : matplotlib.colors.Colormap object
275
276
277
278
        Base color map to discretize

    Returns
    -------
279
    new_cmap : matplotlib.colors.LinearSegmentedColormap object
280
281
        Discretized color map

Chris Smith's avatar
Chris Smith committed
282
283
284
285
286
    Notes
    -----
    Jake VanderPlas License: BSD-style
    https://gist.github.com/jakevdp/91077b0cae40f8f8244a

287
    """
288
289
    if cmap is None:
        cmap = default_cmap.name
290

291
292
293
    elif not isinstance(cmap, str):
        # could not figure out a better type check
        cmap = cmap.name
294

295
296
    if type(cmap) == str:
        return plt.get_cmap(cmap, num_bins)
297

298
    return cmap
299

300

syz's avatar
syz committed
301
def rainbow_plot(axis, x_vec, y_vec, num_steps=32, **kwargs):
Somnath, Suhas's avatar
Somnath, Suhas committed
302
303
    """
    Plots the input against the output waveform (typically loops).
syz's avatar
syz committed
304
    The color of the curve changes as a function of time
Somnath, Suhas's avatar
Somnath, Suhas committed
305

306
307
    Parameters
    ----------
syz's avatar
syz committed
308
    axis : axis handle
Somnath, Suhas's avatar
Somnath, Suhas committed
309
        Axis to plot the curve
syz's avatar
syz committed
310
    x_vec : 1D float numpy array
Somnath, Suhas's avatar
Somnath, Suhas committed
311
        vector that forms the X axis
syz's avatar
syz committed
312
    y_vec : 1D float numpy array
Somnath, Suhas's avatar
Somnath, Suhas committed
313
314
315
316
        vector that forms the Y axis
    num_steps : unsigned int (Optional)
        Number of discrete color steps
    """
syz's avatar
syz committed
317
    cmap = kwargs.pop('cmap', default_cmap)
318
319
    cmap = get_cmap_object(cmap)

320
321
322
    # Remove any color flag
    _ = kwargs.pop('color', None)

syz's avatar
syz committed
323
324
    pts_per_step = len(y_vec) // num_steps

325
    for step in range(num_steps - 1):
syz's avatar
syz committed
326
327
328
        axis.plot(x_vec[step * pts_per_step:(step + 1) * pts_per_step],
                  y_vec[step * pts_per_step:(step + 1) * pts_per_step],
                  color=cmap(255 * step // num_steps), **kwargs)
Somnath, Suhas's avatar
Somnath, Suhas committed
329
    # plot the remainder:
syz's avatar
syz committed
330
331
332
    axis.plot(x_vec[(num_steps - 1) * pts_per_step:],
              y_vec[(num_steps - 1) * pts_per_step:],
              color=cmap(255 * num_steps / num_steps), **kwargs)
Somnath, Suhas's avatar
Somnath, Suhas committed
333
334


335
336
def plot_line_family(axis, x_vec, line_family, line_names=None, label_prefix='', label_suffix='',
                     y_offset=0, show_cbar=False, **kwargs):
337
338
339
340
341
    """
    Plots a family of lines with a sequence of colors

    Parameters
    ----------
342
    axis : axis handle
343
        Axis to plot the curve
344
    x_vec : array-like
345
346
347
348
349
350
351
352
353
        Values to plot against
    line_family : 2D numpy array
        family of curves arranged as [curve_index, features]
    line_names : array-like
        array of string or numbers that represent the identity of each curve in the family
    label_prefix : string / unicode
        prefix for the legend (before the index of the curve)
    label_suffix : string / unicode
        suffix for the legend (after the index of the curve)
354
355
    y_offset : (optional) number
        quantity by which the lines are offset from each other vertically (useful for spectra)
356
357
    show_cbar : (optional) bool
        Whether or not to show a colorbar (instead of a legend)
358
    """
359
360
361
    cmap = get_cmap_object(kwargs.pop('cmap', None))

    num_lines = len(line_family)
362

363
    default_names = False
364
365

    if line_names is None:
366
367
368
369
370
371
372
373
374
375
        label_prefix = 'Line '
        default_names = True
    elif len(line_names) != num_lines:
        warn('Line names of different length compared to provided dataset')
        default_names = True

    if default_names:
        line_names = [str(line_ind) for line_ind in range(num_lines)]

    line_names = ['{} {} {}'.format(label_prefix, cur_name, label_suffix) for cur_name in line_names]
376

377
    for line_ind in range(num_lines):
378
        axis.plot(x_vec, line_family[line_ind] + line_ind * y_offset,
379
380
                  label=line_names[line_ind],
                  color=cmap(int(255 * line_ind / (num_lines - 1))), **kwargs)
381

382
383
384
    if show_cbar:
        # put back the cmap parameter:
        kwargs.update({'cmap': cmap})
385
        _ = cbar_for_line_plot(axis, num_lines, **kwargs)
386

387

388
389
def plot_map(axis, img, show_xy_ticks=True, show_cbar=True, x_size=None, y_size=None, num_ticks=4,
             stdevs=None, cbar_label=None, tick_font_size=14, origin='lower', **kwargs):
390
391
392
393
394
395
396
397
398
    """
    Plots an image within the given axis with a color bar + label and appropriate X, Y tick labels.
    This is particularly useful to get readily interpretable plots for papers
    Parameters
    ----------
    axis : matplotlib.axis object
        Axis to plot this image onto
    img : 2D numpy array with real values
        Data for the image plot
Unknown's avatar
Unknown committed
399
    show_xy_ticks : bool, Optional, default = None, shown unedited
400
401
402
        Whether or not to show X, Y ticks
    show_cbar : bool, optional, default = True
        Whether or not to show the colorbar
403
    x_size : float, optional, default = number of pixels in x direction
404
        Extent of tick marks in the X axis. This could be something like 1.5 for 1.5 microns
405
    y_size : float, optional, default = number of pixels in y direction
406
407
408
        Extent of tick marks in y axis
    num_ticks : unsigned int, optional, default = 4
        Number of tick marks on the X and Y axes
409
410
    stdevs : unsigned int (Optional. Default = None)
        Number of standard deviations to consider for plotting.  If None, full range is plotted.
411
412
413
414
    cbar_label : str, optional, default = None
        Labels for the colorbar. Use this for something like quantity (units)
    tick_font_size : unsigned int, optional, default = 14
        Font size to apply to x, y, colorbar ticks and colorbar label
415
416
417
418
    origin : str
        Where should the origin of the image data be located.  'lower' sets the origin to the
        bottom left, 'upper' sets it to the upper left.
        Default 'lower'
419
    kwargs : dictionary
420
        Anything else that will be passed on to imshow
421
422
423
424
425
426
427
    Returns
    -------
    im_handle : handle to image plot
        handle to image plot
    cbar : handle to color bar
        handle to color bar
    """
428
429
430
431
432
433
434
435
436
    if stdevs is not None:
        data_mean = np.mean(img)
        data_std = np.std(img)
        kwargs.update({'clim': [data_mean - stdevs * data_std,
                                data_mean + stdevs * data_std]})

    kwargs.update({'origin': origin})

    im_handle = axis.imshow(img, **kwargs)
437

Unknown's avatar
Unknown committed
438
    if show_xy_ticks is True:
439
440
441
442
443
444
445
446
447
        if x_size is not None and y_size is not None:
            x_ticks = np.linspace(0, img.shape[1] - 1, num_ticks, dtype=int)
            y_ticks = np.linspace(0, img.shape[0] - 1, num_ticks, dtype=int)
            axis.set_xticks(x_ticks)
            axis.set_yticks(y_ticks)
            axis.set_xticklabels([str(np.round(ind * x_size / (img.shape[1] - 1), 2)) for ind in x_ticks])
            axis.set_yticklabels([str(np.round(ind * y_size / (img.shape[0] - 1), 2)) for ind in y_ticks])
            set_tick_font_size(axis, tick_font_size)
    else:
448
449
450
        axis.set_xticks([])
        axis.set_yticks([])

451
    cbar = None
452
    if show_cbar:
Unknown's avatar
Unknown committed
453
454
        cbar = plt.colorbar(im_handle, ax=axis, orientation='vertical',
                            fraction=0.046, pad=0.04, use_gridspec=True)
455
456
457
458
459
460
        if cbar_label is not None:
            cbar.set_label(cbar_label, fontsize=tick_font_size)
        cbar.ax.tick_params(labelsize=tick_font_size)
    return im_handle, cbar


461
462
def plot_loops(excit_wfms, datasets, line_colors=[], dataset_names=[], evenly_spaced=True,
               plots_on_side=5, x_label='', y_label='', subtitle_prefix='Position', title='',
463
               use_rainbow_plots=False, fig_title_yoffset=1.05, h5_pos=None, **kwargs):
Somnath, Suhas's avatar
Somnath, Suhas committed
464
    """
465
    Plots loops from multiple datasets from up to 25 evenly spaced positions
Somnath, Suhas's avatar
Somnath, Suhas committed
466
467
    Parameters
    -----------
468
    excit_wfms : 1D numpy float array or list of same
Somnath, Suhas's avatar
Somnath, Suhas committed
469
        Excitation waveform in the time domain
470
471
472
473
474
475
    datasets : list of 2D numpy arrays or 2D hyp5.Dataset objects
        Datasets containing data arranged as (pixel, time)
    line_colors : list of strings
        Colors to be used for each of the datasets
    dataset_names : (Optional) list of strings
        Names of the different datasets to be compared
Somnath, Suhas's avatar
Somnath, Suhas committed
476
477
478
479
480
481
482
483
    evenly_spaced : boolean
        Evenly spaced positions or first N positions
    plots_on_side : unsigned int
        Number of plots on each side
    x_label : (optional) String
        X Label for all plots
    y_label : (optional) String
        Y label for all plots
484
    subtitle_prefix : (optional) String
Somnath, Suhas's avatar
Somnath, Suhas committed
485
486
487
        prefix for title over each plot
    title : (optional) String
        Main plot title
488
489
490
491
492
493
    use_rainbow_plots : (optional) Boolean
        Plot the lines as a function of spectral index (eg. time)
    fig_title_yoffset : (optional) float
        Y offset for the figure title. Value should be around 1
    h5_pos : HDF5 dataset reference or 2D numpy array
        Dataset containing position indices
Somnath, Suhas's avatar
Somnath, Suhas committed
494
495
496
497
    Returns
    ---------
    fig, axes
    """
498
499
500
501
    mode = 0
    # 0 = one excitation waveform and one dataset
    # 1 = one excitation waveform but many datasets
    # 2 = one excitation waveform for each of many dataset
502
    if type(datasets) in [h5py.Dataset, np.ndarray]:
503
504
505
        # can be numpy array or h5py.dataset
        num_pos = datasets.shape[0]
        num_points = datasets.shape[1]
Somnath, Suhas's avatar
Somnath, Suhas committed
506
        datasets = [datasets]
507
        excit_wfms = [excit_wfms]
508
509
        line_colors = ['b']
        dataset_names = ['Default']
510
        mode = 0
511
512
513
514
515
516
517
518
519
    else:
        # First check if the datasets are correctly shaped:
        num_pos_es = list()
        num_points_es = list()
        for dataset in datasets:
            num_pos_es.append(dataset.shape[0])
            num_points_es.append(dataset.shape[1])
        num_pos_es = np.array(num_pos_es)
        num_points_es = np.array(num_points_es)
520
521
        if np.unique(num_pos_es).size > 1:  # or np.unique(num_points_es).size > 1:
            raise ValueError('The first dimension of the datasets are not matching: ' + str(num_pos_es))
522
        num_pos = np.unique(num_pos_es)[0]
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537

        if len(excit_wfms) == len(datasets):
            # one excitation waveform per dataset but now verify each size
            if not np.all([len(cur_ex) == cur_dset.shape[1] for cur_ex, cur_dset in zip(excit_wfms, datasets)]):
                raise ValueError('Number of points in the datasets do not match with the excitation waveforms')
            mode = 2
        else:
            # one excitation waveform for all datasets
            if np.unique(num_points_es).size > 1:
                raise ValueError('Datasets don not contain the same number of points: ' + str(num_points_es))
            # datasets of the same size but does this match with the size of excitation waveforms:
            if len(excit_wfms) != np.unique(num_points_es)[0]:
                raise ValueError('Number of points in dataset not matching with shape of excitation waveform')
            excit_wfms = [excit_wfms]
            mode = 1
538
539
540
541
542
543
544
545
546

        # Next the identification of datasets:
        if len(dataset_names) > len(datasets):
            # remove additional titles
            dataset_names = dataset_names[:len(datasets)]
        elif len(dataset_names) < len(datasets):
            # add titles
            dataset_names = dataset_names + ['Dataset' + ' ' + str(x) for x in range(len(dataset_names), len(datasets))]
        if len(line_colors) != len(datasets):
547
            # TODO: Generate colors from a user-specified colormap
548
549
550
551
552
            color_list = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'pink', 'brown', 'orange']
            if len(datasets) < len(color_list):
                remaining_colors = [x for x in color_list if x not in line_colors]
                line_colors += remaining_colors[:len(datasets) - len(color_list)]
            else:
553
                raise ValueError('Insufficient number of line colors provided')
554

555
556
557
558
559
560
    # cannot support rainbows with multiple datasets!
    use_rainbow_plots = use_rainbow_plots and len(datasets) == 1

    if mode != 2:
        # convert it to something like mode 2
        excit_wfms = [excit_wfms[0] for _ in range(len(datasets))]
Somnath, Suhas's avatar
Somnath, Suhas committed
561

562
563
564
565
    if mode != 0:
        # users are not allowed to specify colors
        _ = kwargs.pop('color', None)

Somnath, Suhas's avatar
Somnath, Suhas committed
566
    plots_on_side = min(abs(plots_on_side), 5)
567

Somnath, Suhas's avatar
Somnath, Suhas committed
568
569
570
571
572
573
    sq_num_plots = min(plots_on_side, int(round(num_pos ** 0.5)))
    if evenly_spaced:
        chosen_pos = np.linspace(0, num_pos - 1, sq_num_plots ** 2, dtype=int)
    else:
        chosen_pos = np.arange(sq_num_plots ** 2, dtype=int)

574
    fig, axes = plt.subplots(nrows=sq_num_plots, ncols=sq_num_plots, sharex=True, figsize=(12, 12))
575
    axes_lin = axes.flatten()
Somnath, Suhas's avatar
Somnath, Suhas committed
576
577

    for count, posn in enumerate(chosen_pos):
578
        if use_rainbow_plots:
579
            rainbow_plot(axes_lin[count], excit_wfms[0], datasets[0][posn], **kwargs)
Somnath, Suhas's avatar
Somnath, Suhas committed
580
        else:
581
            for dataset, ex_wfm, col_val in zip(datasets, excit_wfms, line_colors):
582
                axes_lin[count].plot(ex_wfm, dataset[posn], color=col_val, **kwargs)
583
        if h5_pos is not None:
584
            # print('Row ' + str(h5_pos[posn,1]) + ' Col ' + str(h5_pos[posn,0]))
Somnath, Suhas's avatar
Somnath, Suhas committed
585
586
            axes_lin[count].set_title('Row ' + str(h5_pos[posn, 1]) + ' Col ' + str(h5_pos[posn, 0]), fontsize=12)
        else:
587
            axes_lin[count].set_title(subtitle_prefix + ' ' + str(posn), fontsize=12)
Somnath, Suhas's avatar
Somnath, Suhas committed
588
589
590
591
592
593
594
595

        if count % sq_num_plots == 0:
            axes_lin[count].set_ylabel(y_label, fontsize=12)
        if count >= (sq_num_plots - 1) * sq_num_plots:
            axes_lin[count].set_xlabel(x_label, fontsize=12)
        axes_lin[count].axis('tight')
        axes_lin[count].set_aspect('auto')
        axes_lin[count].ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
596
597
    if len(datasets) > 1:
        axes_lin[count].legend(dataset_names, loc='best')
Somnath, Suhas's avatar
Somnath, Suhas committed
598
    if title:
599
        fig.suptitle(title, fontsize=14, y=fig_title_yoffset)
Somnath, Suhas's avatar
Somnath, Suhas committed
600
601
    plt.tight_layout()
    return fig, axes
Chris Smith's avatar
merged    
Chris Smith committed
602

Unknown's avatar
Unknown committed
603

Somnath, Suhas's avatar
Somnath, Suhas committed
604
605
###############################################################################

606

607
def plot_complex_map_stack(map_stack, num_comps=4, title=None, x_label='', y_label='',
608
                           subtitle_prefix='Component', amp_units=None, stdevs=2, **kwargs):
Somnath, Suhas's avatar
Somnath, Suhas committed
609
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
610
611
    Plots the provided spectrograms from SVD V vector

Chris Smith's avatar
Chris Smith committed
612
    Parameters
Somnath, Suhas's avatar
Somnath, Suhas committed
613
    -------------
614
    map_stack : 3D numpy complex matrices
615
        Eigenvectors rearranged as - [component, row, col]
Somnath, Suhas's avatar
Somnath, Suhas committed
616
617
    num_comps : int
        Number of components to plot
618
    title : str, optional
Somnath, Suhas's avatar
Somnath, Suhas committed
619
        Title to plot above everything else
620
    x_label : str, optional
Somnath, Suhas's avatar
Somnath, Suhas committed
621
        Label for x axis
622
623
624
625
    y_label : str, optional
        Label for y axis
    subtitle_prefix : str, optional
        Prefix for the title over each image
626
627
    amp_units : str, optional
        Units for amplitude
Somnath, Suhas's avatar
Somnath, Suhas committed
628
629
630
    stdevs : int
        Number of standard deviations to consider for plotting

Chris Smith's avatar
Chris Smith committed
631
    Returns
Somnath, Suhas's avatar
Somnath, Suhas committed
632
633
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
634
    """
635
636
    if amp_units is None:
        amp_units = 'a.u.'
637
638
639

    figsize = kwargs.pop('figsize', (4, 4))
    figsize = (figsize[0] * num_comps, 8)
640

641
642
    num_comps = min(num_comps, map_stack.shape[0])

643
644
645
646
647
    fig, axes = plt.subplots(2, num_comps, figsize=figsize)
    fig.subplots_adjust(hspace=0.1, wspace=0.4)
    if title is not None:
        fig.canvas.set_window_title(title)
        fig.suptitle(title, y=1.025)
Somnath, Suhas's avatar
Somnath, Suhas committed
648

649
650
    title_prefix = ''

651
    for index in range(num_comps):
652
        cur_axes = [axes.flat[index], axes.flat[index + num_comps]]
Somnath, Suhas's avatar
Somnath, Suhas committed
653
        funcs = [np.abs, np.angle]
654
        labels = ['Amplitude (' + amp_units + ')', 'Phase (rad)']
655
        for func, comp_name, axis, std_val in zip(funcs, labels, cur_axes, [stdevs, None]):
656
            kwargs['stdevs'] = std_val
657
            _ = plot_map(axis, func(map_stack[index]), **kwargs)
658
659
660
661
662

            if num_comps > 1:
                title_prefix = '%s %d - ' % (subtitle_prefix, index)
            axis.set_title('%s%s' % (title_prefix, comp_name))

663
664
665
666
667
668
669
670
            axis.set_aspect('auto')
            if index == 0:
                axis.set_ylabel(y_label)
        axis.set_xlabel(x_label)

    fig.tight_layout()

    return fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
671
672
673
674


###############################################################################

675
676
def plot_complex_loop_stack(loop_stack, x_vec, title=None, subtitle_prefix='Component', num_comps=4, x_label='',
                            amp_units=None, **kwargs):
Somnath, Suhas's avatar
Somnath, Suhas committed
677
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
678
679
    Plots the provided spectrograms from SVD V vector

Chris Smith's avatar
Chris Smith committed
680
    Parameters
Somnath, Suhas's avatar
Somnath, Suhas committed
681
    -------------
682
    loop_stack : 2D numpy complex matrix
683
        Loops rearranged as - [component, points]
684
    x_vec : 1D real numpy array
Somnath, Suhas's avatar
Somnath, Suhas committed
685
        The vector to plot against
686
    title : str
Unknown's avatar
Unknown committed
687
        Title to plot above everything else
688
    subtitle_prefix : str
Unknown's avatar
Unknown committed
689
        Subtile to of Figure
Somnath, Suhas's avatar
Somnath, Suhas committed
690
691
    num_comps : int
        Number of components to plot
Unknown's avatar
Unknown committed
692
    x_label : str
Somnath, Suhas's avatar
Somnath, Suhas committed
693
        Label for x axis
694
695
    amp_units : str, optional
        Units for amplitude
Somnath, Suhas's avatar
Somnath, Suhas committed
696

Chris Smith's avatar
Chris Smith committed
697
    Returns
Somnath, Suhas's avatar
Somnath, Suhas committed
698
699
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
700
    """
701
702
703
704
705
706
    if amp_units is None:
        amp_units = 'a.u.'

    if min(num_comps, loop_stack.shape[0]) == 1:
        subtitle_prefix = None

707
708
    num_comps = min(num_comps, loop_stack.shape[0])

Somnath, Suhas's avatar
Somnath, Suhas committed
709
    funcs = [np.abs, np.angle]
710
    comp_labs = ['Amplitude (' + amp_units + ')', 'Phase (rad)']
Somnath, Suhas's avatar
Somnath, Suhas committed
711

712
713
714
715
716
717
718
719
    figsize = kwargs.pop('figsize', (4, 4))
    figsize = (figsize[0] * num_comps, figsize[1] * len(funcs))

    fig, axes = plt.subplots(len(funcs), num_comps, figsize=figsize)
    fig.subplots_adjust(hspace=0.4, wspace=0.4)
    if title is not None:
        fig.canvas.set_window_title(title)
        fig.suptitle(title, y=1.025)
Somnath, Suhas's avatar
Somnath, Suhas committed
720

721
    for index in range(num_comps):
722
723
        cur_loop = loop_stack[index, :]
        cur_axes = [axes.flat[index], axes.flat[index + num_comps]]
724
        for func, y_label, axis in zip(funcs, comp_labs, cur_axes):
725
            axis.plot(x_vec, func(cur_loop), **kwargs)
726
727
728
729
            if subtitle_prefix is not None:
                axis.set_title('%s: %d' % (subtitle_prefix, index))
            if index == 0:
                axis.set_ylabel(y_label)
730
        axis.set_xlabel(x_label)
731

732
    fig.tight_layout()
Somnath, Suhas's avatar
Somnath, Suhas committed
733

734
    return fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
735

Unknown's avatar
Unknown committed
736

Somnath, Suhas's avatar
Somnath, Suhas committed
737
738
739
###############################################################################


syz's avatar
syz committed
740
def plot_scree(scree, title='Scree', **kwargs):
Somnath, Suhas's avatar
Somnath, Suhas committed
741
    """
742
    Plots the scree or scree
Somnath, Suhas's avatar
Somnath, Suhas committed
743

Chris Smith's avatar
Chris Smith committed
744
    Parameters
Somnath, Suhas's avatar
Somnath, Suhas committed
745
    -------------
746
747
    scree : 1D real numpy array
        The scree vector from SVD
Unknown's avatar
Unknown committed
748
749
    title : str
        Figure title.  Default Scree
Somnath, Suhas's avatar
Somnath, Suhas committed
750

Chris Smith's avatar
Chris Smith committed
751
    Returns
Somnath, Suhas's avatar
Somnath, Suhas committed
752
753
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
754
    """
755
    fig = plt.figure(figsize=kwargs.pop('figsize', (6.5, 6)))
syz's avatar
syz committed
756
757
758
759
760
761
762
763
764
765
766
767
    axis = fig.add_axes([0.1, 0.1, .8, .8])  # left, bottom, width, height (range 0 to 1)
    kwargs.update({'color': kwargs.pop('color', 'b')})
    kwargs.update({'marker': kwargs.pop('marker', '*')})
    axis.loglog(np.arange(len(scree)) + 1, scree, **kwargs)
    axis.set_xlabel('Component')
    axis.set_ylabel('Variance')
    axis.set_title(title)
    axis.set_xlim(left=1, right=len(scree))
    axis.set_ylim(bottom=np.min(scree), top=np.max(scree))
    fig.canvas.set_window_title("Scree")

    return fig, axis
Somnath, Suhas's avatar
Somnath, Suhas committed
768
769


770
771
772
# ###############################################################################


773
def plot_map_stack(map_stack, num_comps=9, stdevs=2, color_bar_mode=None, evenly_spaced=False, reverse_dims=True,
Unknown's avatar
Unknown committed
774
                   title='Component', heading='Map Stack', colorbar_label='', fig_mult=(5, 5), pad_mult=(0.1, 0.07),
775
                   fig_title_yoffset=None, fig_title_size=None, **kwargs):
Somnath, Suhas's avatar
Somnath, Suhas committed
776
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
777
    Plots the provided stack of maps
Somnath, Suhas's avatar
Somnath, Suhas committed
778

Chris Smith's avatar
Chris Smith committed
779
    Parameters
Somnath, Suhas's avatar
Somnath, Suhas committed
780
    -------------
Somnath, Suhas's avatar
Somnath, Suhas committed
781
    map_stack : 3D real numpy array
782
        structured as [component, rows, cols]
783
    num_comps : unsigned int
Somnath, Suhas's avatar
Somnath, Suhas committed
784
785
786
        Number of components to plot
    stdevs : int
        Number of standard deviations to consider for plotting
787
    color_bar_mode : String, Optional
788
        Options are None, single or each. Default None
Unknown's avatar
Unknown committed
789
790
791
792
    evenly_spaced : bool
        Default False
    reverse_dims : Boolean (Optional)
        Set this to False to accept data structured as [component, rows, cols]
793
794
795
796
    title : String or list of strings
        The titles for each of the plots.
        If a single string is provided, the plot titles become ['title 01', title 02', ...].
        if a list of strings (equal to the number of components) are provided, these are used instead.
797
798
    heading : String
        ###Insert description here### Default 'Map Stack'
799
800
    colorbar_label : String
        label for colorbar. Default is an empty string.
801
802
803
    fig_mult : length 2 array_like of uints
        Size multipliers for the figure.  Figure size is calculated as (num_rows*`fig_mult[0]`, num_cols*`fig_mult[1]`).
        Default (4, 4)
Chris Smith's avatar
Chris Smith committed
804
805
806
807
    pad_mult : length 2 array_like of floats
        Multipliers for the axis padding between plots in the stack.  Padding is calculated as
        (pad_mult[0]*fig_mult[1], pad_mult[1]*fig_mult[0]) for the width and height padding respectively.
        Default (0.1, 0.07)
808
809
810
811
    fig_title_yoffset : float
        Offset to move the figure title vertically in the figure
    fig_title_size : float
        Size of figure title
Chris Smith's avatar
Chris Smith committed
812
813
814
    kwargs : dictionary
        Keyword arguments to be passed to either matplotlib.pyplot.figure, mpl_toolkits.axes_grid1.ImageGrid, or
        pycroscopy.vis.plot_utils.plot_map.  See specific function documentation for the relavent options.
Somnath, Suhas's avatar
Somnath, Suhas committed
815

Chris Smith's avatar
Chris Smith committed
816
    Returns
Somnath, Suhas's avatar
Somnath, Suhas committed
817
818
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
819
    """
820
821
822
    if reverse_dims:
        map_stack = np.transpose(map_stack, (2, 0, 1))

823
    num_comps = abs(num_comps)
824
    num_comps = min(num_comps, map_stack.shape[0])
825
826

    if evenly_spaced:
827
        chosen_pos = np.linspace(0, map_stack.shape[0] - 1, num_comps, dtype=int)
828
829
830
    else:
        chosen_pos = np.arange(num_comps, dtype=int)

831
832
833
834
835
836
    if isinstance(title, list):
        if len(title) > num_comps:
            # remove additional titles
            title = title[:num_comps]
        elif len(title) < num_comps:
            # add titles
837
            title += ['Component' + ' ' + str(x) for x in range(len(title), num_comps)]
838
839
840
    else:
        if not isinstance(title, str):
            title = 'Component'
841
        title = [title + ' ' + str(x) for x in chosen_pos]
842

843
    fig_h, fig_w = fig_mult
844
845
    p_rows = int(np.floor(np.sqrt(num_comps)))
    p_cols = int(np.ceil(num_comps / p_rows))
846
    if p_rows * p_cols < num_comps:
847
        p_cols += 1
Chris Smith's avatar
Chris Smith committed
848
849
850
851
852
853
854

    pad_w, pad_h = pad_mult

    '''
    Set defaults for kwargs to the figure creation and extract any non-default values from current kwargs
    '''
    figkwargs = dict()
855
856
857
858

    if sys.version_info.major == 3:
        inspec_func = inspect.getfullargspec
    else:
Unknown's avatar
Unknown committed
859
        inspec_func = inspect.signature
860
861

    for key in inspec_func(plt.figure).args:
Chris Smith's avatar
Chris Smith committed
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
        if key in kwargs:
            figkwargs.update({key: kwargs.pop(key)})

    fig202 = plt.figure(figsize=(p_cols * fig_w, p_rows * fig_h), **figkwargs)

    '''
    Set defaults for kwargs to the ImageGrid and extract any non-default values from current kwargs
    '''
    igkwargs = {'cbar_pad': '1%',
                'cbar_size': '5%',
                'cbar_location': 'right',
                'direction': 'row',
                'add_all': True,
                'share_all': False,
                'aspect': True,
                'label_mode': 'L'}
Somnath, Suhas's avatar
Somnath, Suhas committed
878
    for key in igkwargs.keys():
Chris Smith's avatar
Chris Smith committed
879
880
881
        if key in kwargs:
            igkwargs.update({key: kwargs.pop(key)})

882
883
    axes202 = ImageGrid(fig202, 111, nrows_ncols=(p_rows, p_cols),
                        cbar_mode=color_bar_mode,
884
                        axes_pad=(pad_w * fig_w, pad_h * fig_h),
Chris Smith's avatar
Chris Smith committed
885
                        **igkwargs)
886

Somnath, Suhas's avatar
Somnath, Suhas committed
887
    fig202.canvas.set_window_title(heading)
888
889
890
891
892
893
    # These parameters have not been easy to fix:
    if fig_title_yoffset is None:
        fig_title_yoffset = 0.9
    if fig_title_size is None:
        fig_title_size = 16+(p_rows+ p_cols)
    fig202.suptitle(heading, fontsize=fig_title_size, y=fig_title_yoffset)
Somnath, Suhas's avatar
Somnath, Suhas committed
894

895
    for count, index, subtitle in zip(range(chosen_pos.size), chosen_pos, title):
896
897
        im, im_cbar = plot_map(axes202[count],
                               map_stack[index],
Unknown's avatar
Unknown committed
898
                               stdevs=stdevs, show_cbar=False, **kwargs)
899
        axes202[count].set_title(subtitle)
900

901
        if color_bar_mode is 'each':
902
903
            cb = axes202.cbar_axes[count].colorbar(im)
            cb.set_label_text(colorbar_label)
904

905
    if color_bar_mode is 'single':
906
907
        cb = axes202.cbar_axes[0].colorbar(im)
        cb.set_label_text(colorbar_label)
908

Somnath, Suhas's avatar
Somnath, Suhas committed
909
910
    return fig202, axes202

911

912
def plot_cluster_h5_group(h5_group, centroids_together=True, cmap=default_cmap):
913
    """
Chris Smith's avatar
Chris Smith committed
914
    Plots the cluster labels and mean response for each cluster
915

Chris Smith's avatar
Chris Smith committed
916
917
918
919
920
921
    Parameters
    ----------
    h5_group : h5py.Datagroup object
        H5 group containing the labels and mean response
    centroids_together : Boolean, optional - default = True
        Whether or nor to plot all centroids together on the same plot
922
923
    cmap : plt.cm object or str, optional
        Colormap to use for the labels map and the centroid.
Chris Smith's avatar
Chris Smith committed
924
925
926
927
928
929
930
931

    Returns
    -------
    fig : Figure
        Figure containing the plots
    axes : 1D array_like of axes objects
        Axes of the individual plots within `fig`
    """
932

933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
    h5_labels = h5_group['Labels']
    try:
        h5_mean_resp = h5_group['Mean_Response']
    except KeyError:
        # old PySPM format:
        h5_mean_resp = h5_group['Centroids']

    # Reshape the mean response to N dimensions
    mean_response, success = reshape_to_Ndims(h5_mean_resp)

    # unfortunately, we cannot use the above function for the labels
    # However, we will assume that the position values are linked to the labels:
    h5_pos_vals = h5_labels.file[h5_labels.attrs['Position_Values']]
    h5_pos_inds = h5_labels.file[h5_labels.attrs['Position_Indices']]

    # Reshape the labels correctly:
    pos_dims = []
    for col in range(h5_pos_inds.shape[1]):
        pos_dims.append(np.unique(h5_pos_inds[:, col]).size)

Unknown's avatar
Unknown committed
953
    pos_ticks = [h5_pos_vals[:pos_dims[0], 0], h5_pos_vals[slice(0, None, pos_dims[0]), 1]]
954
955
956
957
958
959
960
961
962
963
964
965
    # prepare the axes ticks for the map

    pos_dims.reverse()  # go from slowest to fastest
    pos_dims = tuple(pos_dims)
    label_mat = np.reshape(h5_labels.value, pos_dims)

    # Figure out the correct units and labels for mean response:
    h5_spec_vals = h5_mean_resp.file[h5_mean_resp.attrs['Spectroscopic_Values']]
    x_spec_label = get_formatted_labels(h5_spec_vals)[0]

    # Figure out the correct axes labels for label map:
    pos_labels = get_formatted_labels(h5_pos_vals)
966
967

    y_spec_label = get_data_descriptor(h5_mean_resp)
968
    # TODO: cleaner x and y axes labels instead of 0.0000125 etc.
969

970
971
972
    if centroids_together:
        return plot_cluster_results_together(label_mat, mean_response, spec_val=np.squeeze(h5_spec_vals[0]),
                                             spec_label=x_spec_label, resp_label=y_spec_label,
973
                                             pos_labels=pos_labels, pos_ticks=pos_ticks, cmap=cmap)
974
975
    else:
        return plot_cluster_results_separate(label_mat, mean_response, max_centroids=4, x_label=x_spec_label,
976
                                             spec_val=np.squeeze(h5_spec_vals[0]), y_label=y_spec_label, cmap=cmap)
Somnath, Suhas's avatar
Somnath, Suhas committed
977

Unknown's avatar
Unknown committed
978

Somnath, Suhas's avatar
Somnath, Suhas committed
979
###############################################################################
980
981


982
def plot_cluster_results_together(label_mat, mean_response, spec_val=None, cmap=default_cmap,
983
984
                                  spec_label='Spectroscopic Value', resp_label='Response',
                                  pos_labels=('X', 'Y'), pos_ticks=None):
Somnath, Suhas's avatar
Somnath, Suhas committed
985
    """
986
    Plot the cluster labels and mean response for each cluster in separate plots
Chris Smith's avatar
Chris Smith committed
987
988
989
990
991

    Parameters
    ----------
    label_mat : 2D ndarray or h5py.Dataset of ints
        Spatial map of cluster labels structured as [rows, cols]
992
    mean_response : 2D array or h5py.Dataset
Chris Smith's avatar
Chris Smith committed
993
994
        Mean value of each cluster over all samples 
        arranged as [cluster number, features]
995
    spec_val :  1D array or h5py.Dataset of floats, optional
Chris Smith's avatar
Chris Smith committed
996
997
998
999
1000
        X axis to plot the centroids against
        If no value is specified, the data is plotted against the index
    cmap : plt.cm object or str, optional
        Colormap to use for the labels map and the centroid.
        Advised to pick a map where the centroid plots show clearly.
For faster browsing, not all history is shown. View entire blame