plot_utils.py 58.4 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
12
from warnings import warn
Unknown's avatar
Unknown committed
13
import os
14
import sys
Chris Smith's avatar
merged    
Chris Smith committed
15
import h5py
16
import matplotlib as mpl
17
import matplotlib.pyplot as plt
18
19
import numpy as np
import scipy
20
from scipy.signal import blackman
Unknown's avatar
Unknown committed
21
import ipywidgets as widgets
22
from matplotlib.colors import LinearSegmentedColormap
23
from mpl_toolkits.axes_grid1 import ImageGrid
24
from ..io.hdf_utils import reshape_to_Ndims, get_formatted_labels, get_data_descriptor
25

26
27
28
29
30
31
32
33
34
35
36
# 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

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

Somnath, Suhas's avatar
Somnath, Suhas committed
40
default_cmap = plt.cm.viridis
41

42
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
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
74

75
def make_scalar_mappable(vmin, vmax, cmap=None):
76
    """
77
    Creates a scalar mappable object that can be used to create a colorbar for non-image (e.g. - line) plots
78
79
80
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

    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


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


123
124
125
126
127
128
129
def cmap_jet_white_center():
    """
    Generates the jet colormap with a white center

    Returns
    -------
    white_jet : matplotlib.colors.LinearSegmentedColormap object
130
        color map object that can be used in place of the default colormap
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
    """
    # 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)
152

Chris Smith's avatar
Chris Smith committed
153

Somnath, Suhas's avatar
Somnath, Suhas committed
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
184
                             for (dist, colors) in interp_vals][::-1])}
Somnath, Suhas's avatar
Somnath, Suhas committed
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
212
213
214

    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
215
216


Somnath, Suhas's avatar
Somnath, Suhas committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
236
237


238
def discrete_cmap(num_bins, base_cmap=default_cmap):
239
240
241
242
243
244
245
246
247
248
249
250
    """
    Create an N-bin discrete colormap from the specified input map

    Parameters
    ----------
    num_bins : unsigned int
        Number of discrete bins
    base_cmap : matplotlib.colors.LinearSegmentedColormap object
        Base color map to discretize

    Returns
    -------
251
    new_cmap : String or matplotlib.colors.LinearSegmentedColormap object
252
253
        Discretized color map

Chris Smith's avatar
Chris Smith committed
254
255
256
257
258
    Notes
    -----
    Jake VanderPlas License: BSD-style
    https://gist.github.com/jakevdp/91077b0cae40f8f8244a

259
    """
260
    if base_cmap is None:
261
        base_cmap = default_cmap.name
262

263
    elif isinstance(base_cmap, type(default_cmap)):
264
        base_cmap = base_cmap.name
265

266
267
268
269
    if type(base_cmap) == str:
        return plt.get_cmap(base_cmap, num_bins)

    return base_cmap
270

271

Chris Smith's avatar
Chris Smith committed
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def _add_loop_parameters(axes, switching_coef_vec):
    """
    Add the loop parameters for the given loop to a list of axes

    Parameters
    ----------
    axes : list of matplotlib.pyplo.axes
        Plot axes to add the coeffients to
    switching_coef_vec : 1D numpy.ndarray
        Array of loop parameters arranged by position

    Returns
    -------
    axes : list of matplotlib.pyplo.axes
    """
    positions = np.linspace(0, switching_coef_vec.shape[0] - 1, len(axes.flat), dtype=np.int)

    for ax, pos in zip(axes.flat, positions):
        ax.axvline(switching_coef_vec[pos]['V+'], c='k', label='V+')
        ax.axvline(switching_coef_vec[pos]['V-'], c='r', label='V-')
        ax.axvline(switching_coef_vec[pos]['Nucleation Bias 1'], c='k', ls=':', label='Nucleation Bias 1')
        ax.axvline(switching_coef_vec[pos]['Nucleation Bias 2'], c='r', ls=':', label='Nucleation Bias 2')
        ax.axhline(switching_coef_vec[pos]['R+'], c='k', ls='-.', label='R+')
        ax.axhline(switching_coef_vec[pos]['R-'], c='r', ls='-.', label='R-')

    return axes
298

299
300

def rainbow_plot(ax, ao_vec, ai_vec, num_steps=32, cmap=default_cmap, **kwargs):
Somnath, Suhas's avatar
Somnath, Suhas committed
301
302
303
304
    """
    Plots the input against the output waveform (typically loops).
    The color of the curve changes as a function of time using the jet colorscheme

305
306
    Parameters
    ----------
Somnath, Suhas's avatar
Somnath, Suhas committed
307
308
309
310
311
312
313
314
    ax : axis handle
        Axis to plot the curve
    ao_vec : 1D float numpy array
        vector that forms the X axis
    ai_vec : 1D float numpy array
        vector that forms the Y axis
    num_steps : unsigned int (Optional)
        Number of discrete color steps
315
316
    cmap : matplotlib.colors.LinearSegmentedColormap object
        Colormap to be used
Somnath, Suhas's avatar
Somnath, Suhas committed
317
    """
318
319
    cmap = get_cmap_object(cmap)

Somnath, Suhas's avatar
Somnath, Suhas committed
320
    pts_per_step = int(len(ai_vec) / num_steps)
321
    for step in range(num_steps - 1):
Somnath, Suhas's avatar
Somnath, Suhas committed
322
323
        ax.plot(ao_vec[step * pts_per_step:(step + 1) * pts_per_step],
                ai_vec[step * pts_per_step:(step + 1) * pts_per_step],
324
                color=cmap(255 * step / num_steps), **kwargs)
Somnath, Suhas's avatar
Somnath, Suhas committed
325
326
327
    # plot the remainder:
    ax.plot(ao_vec[(num_steps - 1) * pts_per_step:],
            ai_vec[(num_steps - 1) * pts_per_step:],
328
            color=cmap(255 * num_steps / num_steps), **kwargs)
Somnath, Suhas's avatar
Somnath, Suhas committed
329
    """
330
    CS3=plt.contourf([[0,0],[0,0]], range(0,310),cmap=plt.cm.viridis)
Somnath, Suhas's avatar
Somnath, Suhas committed
331
332
333
    fig.colorbar(CS3)"""


334
def plot_line_family(axis, x_axis, line_family, line_names=None, label_prefix='Line', label_suffix='',
335
                     cmap=default_cmap, y_offset=0, **kwargs):
336
337
338
339
340
    """
    Plots a family of lines with a sequence of colors

    Parameters
    ----------
341
    axis : axis handle
342
343
344
345
346
347
348
349
350
351
352
353
354
        Axis to plot the curve
    x_axis : array-like
        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)
    cmap : matplotlib.colors.LinearSegmentedColormap object
        Colormap to be used
355
356
    y_offset : (optional) number
        quantity by which the lines are offset from each other vertically (useful for spectra)
357
    """
358
359
    cmap = get_cmap_object(cmap)

360
361
362
363
364
365
366
367
368
    num_lines = line_family.shape[0]

    if line_names is None:
        line_names = ['{} {} {}'.format(label_prefix, line_ind, label_suffix) for line_ind in range(num_lines)]
    else:
        if len(line_names) != num_lines:
            warn('Line names of different length compared to provided dataset')
            line_names = ['{} {} {}'.format(label_prefix, line_ind, label_suffix) for line_ind in range(num_lines)]

369
    for line_ind in range(num_lines):
Unknown's avatar
Unknown committed
370
        axis.plot(x_axis, line_family[line_ind] + line_ind * y_offset,
371
372
                  label=line_names[line_ind],
                  color=cmap(int(255 * line_ind / (num_lines - 1))), **kwargs)
373
374


Unknown's avatar
Unknown committed
375
def plot_map(axis, data, stdevs=None, origin='lower', **kwargs):
376
377
378
379
380
381
382
383
384
385
    """
    Plots a 2d map with a tight z axis, with or without color bars.
    Note that the direction of the y axis is flipped if the color bar is required

    Parameters
    ----------
    axis : matplotlib.pyplot.axis object
        Axis to plot this map onto
    data : 2D real numpy array
        Data to be plotted
Unknown's avatar
Unknown committed
386
387
    stdevs : unsigned int (Optional. Default = None)
        Number of standard deviations to consider for plotting.  If None, full range is plotted.
Chris Smith's avatar
Chris Smith committed
388
389
390
391
    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'
392

393
394
395
    Returns
    -------
    """
Unknown's avatar
Unknown committed
396
397
398
399
400
401
402
403
404
    if stdevs is not None:
        data_mean = np.mean(data)
        data_std = np.std(data)
        plt_min = data_mean - stdevs * data_std
        plt_max = data_mean + stdevs * data_std
    else:
        plt_min = np.min(data)
        plt_max = np.max(data)

405
    im = axis.imshow(data, interpolation='none',
Unknown's avatar
Unknown committed
406
407
                     vmin=plt_min,
                     vmax=plt_max,
408
                     origin=origin,
409
                     **kwargs)
410

411
    return im
412

413

Unknown's avatar
Unknown committed
414
415
def single_img_cbar_plot(axis, img, show_xy_ticks=None, show_cbar=True, x_size=1, y_size=1, num_ticks=4,
                         cbar_label=None, tick_font_size=14, **kwargs):
416
417
418
419
420
421
422
423
424
425
    """
    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
426
    show_xy_ticks : bool, Optional, default = None, shown unedited
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
        Whether or not to show X, Y ticks
    show_cbar : bool, optional, default = True
        Whether or not to show the colorbar
    x_size : float, optional, default = 1
        Extent of tick marks in the X axis. This could be something like 1.5 for 1.5 microns
    y_size : float, optional, default = 1
        Extent of tick marks in y axis
    num_ticks : unsigned int, optional, default = 4
        Number of tick marks on the X and Y axes
    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
    kwargs : dictionary
        Anything else that will be passed on to plot_map or imshow

    Returns
    -------
    im_handle : handle to image plot
        handle to image plot
    cbar : handle to color bar
        handle to color bar
    """
    if 'clim' not in kwargs:
Unknown's avatar
Unknown committed
451
        im_handle = plot_map(axis, img, **kwargs)
452
453
454
    else:
        im_handle = axis.imshow(img, origin='lower', **kwargs)

Unknown's avatar
Unknown committed
455
    if show_xy_ticks is True:
456
457
458
459
460
461
462
        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)
Unknown's avatar
Unknown committed
463
    elif show_xy_ticks is False:
464
465
        axis.set_xticks([])
        axis.set_yticks([])
Unknown's avatar
Unknown committed
466
467
    else:
        set_tick_font_size(axis, tick_font_size)
468

469
    cbar = None
470
    if show_cbar:
Unknown's avatar
Unknown committed
471
472
473
474
475
476
        # cbar = fig.colorbar(im_handle, ax=axis)
        # divider = make_axes_locatable(axis)
        # cax = divider.append_axes('right', size='5%', pad=0.05)
        # cbar = plt.colorbar(im_handle, cax=cax)
        cbar = plt.colorbar(im_handle, ax=axis, orientation='vertical',
                            fraction=0.046, pad=0.04, use_gridspec=True)
477
478
479
480
481
482
483
484
485
486
        if cbar_label is not None:
            cbar.set_label(cbar_label, fontsize=tick_font_size)
        """
        z_lims = cbar.get_clim()
        cbar.set_ticks(np.linspace(z_lims[0],z_lims[1], num_ticks))
        """
        cbar.ax.tick_params(labelsize=tick_font_size)
    return im_handle, cbar


Unknown's avatar
Unknown committed
487
488
489
def plot_loops(excit_wfm, datasets, line_colors=[], dataset_names=[], evenly_spaced=True,
               plots_on_side=5, x_label='', y_label='', subtitles='Position', title='',
               central_resp_size=None, use_rainbow_plots=False, h5_pos=None):
490
    # TODO: Allow multiple excitation waveforms
Somnath, Suhas's avatar
Somnath, Suhas committed
491
    """
492
    Plots loops from multiple datasets from up to 25 evenly spaced positions
Somnath, Suhas's avatar
Somnath, Suhas committed
493
494
495
496
497

    Parameters
    -----------
    excit_wfm : 1D numpy float array
        Excitation waveform in the time domain
498
499
500
501
502
503
    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
504
505
506
507
508
509
510
511
    h5_pos : HDF5 dataset reference or 2D numpy array
        Dataset containing position indices
    central_resp_size : (optional) unsigned integer
        Number of responce sample points from the center of the waveform to show in plots. Useful for SPORC
    evenly_spaced : boolean
        Evenly spaced positions or first N positions
    plots_on_side : unsigned int
        Number of plots on each side
512
    use_rainbow_plots : (optional) Boolean
Somnath, Suhas's avatar
Somnath, Suhas committed
513
514
515
516
517
518
519
520
521
522
523
524
525
526
        Plot the lines as a function of spectral index (eg. time)
    x_label : (optional) String
        X Label for all plots
    y_label : (optional) String
        Y label for all plots
    subtitles : (optional) String
        prefix for title over each plot
    title : (optional) String
        Main plot title

    Returns
    ---------
    fig, axes
    """
527
    if type(datasets) in [h5py.Dataset, np.ndarray]:
528
529
530
        # can be numpy array or h5py.dataset
        num_pos = datasets.shape[0]
        num_points = datasets.shape[1]
Somnath, Suhas's avatar
Somnath, Suhas committed
531
        datasets = [datasets]
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
        line_colors = ['b']
        dataset_names = ['Default']
    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)
        if np.unique(num_pos_es).size > 1 or np.unique(num_points_es).size > 1:
            warn('Datasets of incompatible sizes')
            return
        num_pos = np.unique(num_pos_es)[0]
        num_points = np.unique(num_points_es)[0]

        # 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):
            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:
                warn('Insufficient number of line colors provided')
                return

    if excit_wfm.size != num_points:
        warn('Length of excitation waveform not compatible with second axis of datasets')
        return
Somnath, Suhas's avatar
Somnath, Suhas committed
568
569

    plots_on_side = min(abs(plots_on_side), 5)
570

Somnath, Suhas's avatar
Somnath, Suhas committed
571
572
573
574
575
576
    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)

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

580
    cent_ind = int(0.5 * excit_wfm.size)
Somnath, Suhas's avatar
Somnath, Suhas committed
581
582
583
584
585
586
    if central_resp_size:
        sz = int(0.5 * central_resp_size)
        l_resp_ind = cent_ind - sz
        r_resp_ind = cent_ind + sz
    else:
        l_resp_ind = 0
587
        r_resp_ind = excit_wfm.size
Somnath, Suhas's avatar
Somnath, Suhas committed
588
589

    for count, posn in enumerate(chosen_pos):
590
591
        if use_rainbow_plots and len(datasets) == 1:
            rainbow_plot(axes_lin[count], excit_wfm[l_resp_ind:r_resp_ind], datasets[0][posn, l_resp_ind:r_resp_ind])
Somnath, Suhas's avatar
Somnath, Suhas committed
592
        else:
593
            for dataset, col_val in zip(datasets, line_colors):
Unknown's avatar
Unknown committed
594
595
                axes_lin[count].plot(excit_wfm[l_resp_ind:r_resp_ind], dataset[posn, l_resp_ind:r_resp_ind],
                                     color=col_val)
596
        if h5_pos is not None:
597
            # print('Row ' + str(h5_pos[posn,1]) + ' Col ' + str(h5_pos[posn,0]))
Somnath, Suhas's avatar
Somnath, Suhas committed
598
599
600
601
602
603
604
605
606
607
608
            axes_lin[count].set_title('Row ' + str(h5_pos[posn, 1]) + ' Col ' + str(h5_pos[posn, 0]), fontsize=12)
        else:
            axes_lin[count].set_title(subtitles + ' ' + str(posn), fontsize=12)

        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))
609
610
    if len(datasets) > 1:
        axes_lin[count].legend(dataset_names, loc='best')
Somnath, Suhas's avatar
Somnath, Suhas committed
611
    if title:
612
        fig.suptitle(title, fontsize=14, y=1.05)
Somnath, Suhas's avatar
Somnath, Suhas committed
613
614
    plt.tight_layout()
    return fig, axes
Chris Smith's avatar
merged    
Chris Smith committed
615

Unknown's avatar
Unknown committed
616

Somnath, Suhas's avatar
Somnath, Suhas committed
617
618
###############################################################################

619

620
621
def plot_complex_map_stack(map_stack, num_comps=4, title='Eigenvectors', xlabel='UDVS Step', stdevs=2,
                           cmap=default_cmap):
Somnath, Suhas's avatar
Somnath, Suhas committed
622
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
623
624
    Plots the provided spectrograms from SVD V vector

Chris Smith's avatar
Chris Smith committed
625
    Parameters
Somnath, Suhas's avatar
Somnath, Suhas committed
626
    -------------
627
    map_stack : 3D numpy complex matrices
Somnath, Suhas's avatar
Somnath, Suhas committed
628
629
630
631
632
633
634
635
636
        Eigenvectors rearranged as - [row, col, component]
    num_comps : int
        Number of components to plot
    title : String
        Title to plot above everything else
    xlabel : String
        Label for x axis
    stdevs : int
        Number of standard deviations to consider for plotting
637
638
    cmap : String, or matplotlib.colors.LinearSegmentedColormap object (Optional)
        Requested color map
Somnath, Suhas's avatar
Somnath, Suhas committed
639

Chris Smith's avatar
Chris Smith committed
640
    Returns
Somnath, Suhas's avatar
Somnath, Suhas committed
641
642
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
643
    """
644
645
    cmap = get_cmap_object(cmap)

Somnath, Suhas's avatar
Somnath, Suhas committed
646
647
648
649
    fig201, axes201 = plt.subplots(2, num_comps, figsize=(4 * num_comps, 8))
    fig201.subplots_adjust(hspace=0.4, wspace=0.4)
    fig201.canvas.set_window_title(title)

650
    for index in range(num_comps):
651
        cur_map = np.transpose(map_stack[index, :, :])
Somnath, Suhas's avatar
Somnath, Suhas committed
652
653
654
655
        axes = [axes201.flat[index], axes201.flat[index + num_comps]]
        funcs = [np.abs, np.angle]
        labels = ['Amplitude', 'Phase']
        for func, lab, ax in zip(funcs, labels, axes):
656
657
            amp_mean = np.mean(func(cur_map))
            amp_std = np.std(func(cur_map))
658
            ax.imshow(func(cur_map), cmap=cmap,
Somnath, Suhas's avatar
Somnath, Suhas committed
659
660
661
662
663
664
665
666
667
668
669
                      vmin=amp_mean - stdevs * amp_std,
                      vmax=amp_mean + stdevs * amp_std)
            ax.set_title('Eigenvector: %d - %s' % (index + 1, lab))
            ax.set_aspect('auto')
        ax.set_xlabel(xlabel)

    return fig201, axes201


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

670
def plot_complex_loop_stack(loop_stack, x_axis, heading='BE Loops', subtitle='Eigenvector', num_comps=4, x_label=''):
Somnath, Suhas's avatar
Somnath, Suhas committed
671
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
672
673
    Plots the provided spectrograms from SVD V vector

Chris Smith's avatar
Chris Smith committed
674
    Parameters
Somnath, Suhas's avatar
Somnath, Suhas committed
675
    -------------
676
677
678
    loop_stack : 3D numpy complex matrices
        Loops rearranged as - [component, points]
    x_axis : 1D real numpy array
Somnath, Suhas's avatar
Somnath, Suhas committed
679
        The vector to plot against
Unknown's avatar
Unknown committed
680
681
682
683
    heading : str
        Title to plot above everything else
    subtitle : str
        Subtile to of Figure
Somnath, Suhas's avatar
Somnath, Suhas committed
684
685
    num_comps : int
        Number of components to plot
Unknown's avatar
Unknown committed
686
    x_label : str
Somnath, Suhas's avatar
Somnath, Suhas committed
687
688
        Label for x axis

Chris Smith's avatar
Chris Smith committed
689
    Returns
Somnath, Suhas's avatar
Somnath, Suhas committed
690
691
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
692
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
693
694
695
696
697
    funcs = [np.abs, np.angle]
    labels = ['Amplitude', 'Phase']

    fig201, axes201 = plt.subplots(len(funcs), num_comps, figsize=(num_comps * 4, 4 * len(funcs)))
    fig201.subplots_adjust(hspace=0.4, wspace=0.4)
698
    fig201.canvas.set_window_title(heading)
Somnath, Suhas's avatar
Somnath, Suhas committed
699

700
    for index in range(num_comps):
701
        cur_map = loop_stack[index, :]
Somnath, Suhas's avatar
Somnath, Suhas committed
702
703
        axes = [axes201.flat[index], axes201.flat[index + num_comps]]
        for func, lab, ax in zip(funcs, labels, axes):
704
705
706
            ax.plot(x_axis, func(cur_map))
            ax.set_title('%s: %d - %s' % (subtitle, index + 1, lab))
        ax.set_xlabel(x_label)
Somnath, Suhas's avatar
Somnath, Suhas committed
707
708
709
710
    fig201.tight_layout()

    return fig201, axes201

Unknown's avatar
Unknown committed
711

Somnath, Suhas's avatar
Somnath, Suhas committed
712
713
714
###############################################################################


715
def plotScree(scree, title='Scree'):
Somnath, Suhas's avatar
Somnath, Suhas committed
716
    """
717
    Plots the scree or scree
Somnath, Suhas's avatar
Somnath, Suhas committed
718

Chris Smith's avatar
Chris Smith committed
719
    Parameters
Somnath, Suhas's avatar
Somnath, Suhas committed
720
    -------------
721
722
    scree : 1D real numpy array
        The scree vector from SVD
Unknown's avatar
Unknown committed
723
724
    title : str
        Figure title.  Default Scree
Somnath, Suhas's avatar
Somnath, Suhas committed
725

Chris Smith's avatar
Chris Smith committed
726
    Returns
Somnath, Suhas's avatar
Somnath, Suhas committed
727
728
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
729
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
730
731
    fig203 = plt.figure(figsize=(6.5, 6))
    axes203 = fig203.add_axes([0.1, 0.1, .8, .8])  # left, bottom, width, height (range 0 to 1)
732
    axes203.loglog(np.arange(len(scree)) + 1, scree, 'b', marker='*')
Somnath, Suhas's avatar
Somnath, Suhas committed
733
734
735
    axes203.set_xlabel('Principal Component')
    axes203.set_ylabel('Variance')
    axes203.set_title(title)
736
737
    axes203.set_xlim(left=1, right=len(scree))
    axes203.set_ylim(bottom=np.min(scree), top=np.max(scree))
Somnath, Suhas's avatar
Somnath, Suhas committed
738
739
740
741
742
    fig203.canvas.set_window_title("Scree")

    return fig203, axes203


743
744
745
# ###############################################################################


746
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
747
748
                   title='Component', heading='Map Stack', colorbar_label='', fig_mult=(5, 5), pad_mult=(0.1, 0.07),
                   **kwargs):
Somnath, Suhas's avatar
Somnath, Suhas committed
749
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
750
    Plots the provided stack of maps
Somnath, Suhas's avatar
Somnath, Suhas committed
751

Chris Smith's avatar
Chris Smith committed
752
    Parameters
Somnath, Suhas's avatar
Somnath, Suhas committed
753
    -------------
Somnath, Suhas's avatar
Somnath, Suhas committed
754
    map_stack : 3D real numpy array
755
        structured as [component, rows, cols]
756
    num_comps : unsigned int
Somnath, Suhas's avatar
Somnath, Suhas committed
757
758
759
        Number of components to plot
    stdevs : int
        Number of standard deviations to consider for plotting
760
    color_bar_mode : String, Optional
761
        Options are None, single or each. Default None
Unknown's avatar
Unknown committed
762
763
764
765
    evenly_spaced : bool
        Default False
    reverse_dims : Boolean (Optional)
        Set this to False to accept data structured as [component, rows, cols]
766
767
768
769
    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.
770
771
    heading : String
        ###Insert description here### Default 'Map Stack'
772
773
    colorbar_label : String
        label for colorbar. Default is an empty string.
774
775
776
    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
777
778
779
780
781
782
783
    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)
    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
784

Chris Smith's avatar
Chris Smith committed
785
    Returns
Somnath, Suhas's avatar
Somnath, Suhas committed
786
787
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
788
    """
789
790
791
    if reverse_dims:
        map_stack = np.transpose(map_stack, (2, 0, 1))

792
    num_comps = abs(num_comps)
793
    num_comps = min(num_comps, map_stack.shape[0])
794
795

    if evenly_spaced:
796
        chosen_pos = np.linspace(0, map_stack.shape[0] - 1, num_comps, dtype=int)
797
798
799
    else:
        chosen_pos = np.arange(num_comps, dtype=int)

800
801
802
803
804
805
    if isinstance(title, list):
        if len(title) > num_comps:
            # remove additional titles
            title = title[:num_comps]
        elif len(title) < num_comps:
            # add titles
806
            title += ['Component' + ' ' + str(x) for x in range(len(title), num_comps)]
807
808
809
    else:
        if not isinstance(title, str):
            title = 'Component'
810
        title = [title + ' ' + str(x) for x in chosen_pos]
811

812
    fig_h, fig_w = fig_mult
813
814
    p_rows = int(np.floor(np.sqrt(num_comps)))
    p_cols = int(np.ceil(num_comps / p_rows))
815
    if p_rows * p_cols < num_comps:
816
        p_cols += 1
Chris Smith's avatar
Chris Smith committed
817
818
819
820
821
822
823

    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()
824
825
826
827

    if sys.version_info.major == 3:
        inspec_func = inspect.getfullargspec
    else:
Unknown's avatar
Unknown committed
828
        inspec_func = inspect.signature
829
830

    for key in inspec_func(plt.figure).args:
Chris Smith's avatar
Chris Smith committed
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
        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
847
    for key in igkwargs.keys():
Chris Smith's avatar
Chris Smith committed
848
849
850
        if key in kwargs:
            igkwargs.update({key: kwargs.pop(key)})

851
852
    axes202 = ImageGrid(fig202, 111, nrows_ncols=(p_rows, p_cols),
                        cbar_mode=color_bar_mode,
853
                        axes_pad=(pad_w * fig_w, pad_h * fig_h),
Chris Smith's avatar
Chris Smith committed
854
                        **igkwargs)
Somnath, Suhas's avatar
Somnath, Suhas committed
855
    fig202.canvas.set_window_title(heading)
856
    fig202.suptitle(heading, fontsize=16+(p_rows+ p_cols), y=0.9)
Somnath, Suhas's avatar
Somnath, Suhas committed
857

858
859
    for count, index, subtitle in zip(range(chosen_pos.size), chosen_pos, title):
        im = plot_map(axes202[count],
860
                      map_stack[index],
861
862
                      stdevs=stdevs, **kwargs)
        axes202[count].set_title(subtitle)
863
        if color_bar_mode is 'each':
864
865
            cb = axes202.cbar_axes[count].colorbar(im)
            cb.set_label_text(colorbar_label)
866
    if color_bar_mode is 'single':
867
868
        cb = axes202.cbar_axes[0].colorbar(im)
        cb.set_label_text(colorbar_label)
Somnath, Suhas's avatar
Somnath, Suhas committed
869
870
    return fig202, axes202

871

872
def plot_cluster_h5_group(h5_group, centroids_together=True, cmap=default_cmap):
873
    """
Chris Smith's avatar
Chris Smith committed
874
    Plots the cluster labels and mean response for each cluster
875

Chris Smith's avatar
Chris Smith committed
876
877
878
879
880
881
    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
882
883
    cmap : plt.cm object or str, optional
        Colormap to use for the labels map and the centroid.
Chris Smith's avatar
Chris Smith committed
884
885
886
887
888
889
890
891

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

893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
    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
913
    pos_ticks = [h5_pos_vals[:pos_dims[0], 0], h5_pos_vals[slice(0, None, pos_dims[0]), 1]]
914
915
916
917
918
919
920
921
922
923
924
925
    # 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)
926
927

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

930
931
932
    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,
933
                                             pos_labels=pos_labels, pos_ticks=pos_ticks, cmap=cmap)
934
935
    else:
        return plot_cluster_results_separate(label_mat, mean_response, max_centroids=4, x_label=x_spec_label,
936
                                             spec_val=np.squeeze(h5_spec_vals[0]), y_label=y_spec_label, cmap=cmap)
Somnath, Suhas's avatar
Somnath, Suhas committed
937

Unknown's avatar
Unknown committed
938

Somnath, Suhas's avatar
Somnath, Suhas committed
939
###############################################################################
940
941


942
def plot_cluster_results_together(label_mat, mean_response, spec_val=None, cmap=default_cmap,
943
944
                                  spec_label='Spectroscopic Value', resp_label='Response',
                                  pos_labels=('X', 'Y'), pos_ticks=None):
Somnath, Suhas's avatar
Somnath, Suhas committed
945
    """
946
    Plot the cluster labels and mean response for each cluster in separate plots
Chris Smith's avatar
Chris Smith committed
947
948
949
950
951

    Parameters
    ----------
    label_mat : 2D ndarray or h5py.Dataset of ints
        Spatial map of cluster labels structured as [rows, cols]
952
    mean_response : 2D array or h5py.Dataset
Chris Smith's avatar
Chris Smith committed
953
954
        Mean value of each cluster over all samples 
        arranged as [cluster number, features]
955
    spec_val :  1D array or h5py.Dataset of floats, optional
Chris Smith's avatar
Chris Smith committed
956
957
958
959
960
961
962
963
964
965
966
967
        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.
        Default = matplotlib.pyplot.cm.jet
    spec_label : str, optional
        Label to use for X axis on cluster centroid plot
        Default = 'Spectroscopic Value'
    resp_label : str, optional
        Label to use for Y axis on cluster centroid plot
         Default = 'Response'
Chris Smith's avatar
Chris Smith committed
968
969
970
971
    pos_labels : array_like of str, optional
        Labels to use for the X and Y axes on the Label map
        Default = ('X', 'Y')
    pos_ticks : array_like of int
Chris Smith's avatar
Chris Smith committed
972
973
974
975
976
977
978

    Returns
    -------
    fig : Figure
        Figure containing the plots
    axes : 1D array_like of axes objects
        Axes of the individual plots within `fig`
Somnath, Suhas's avatar
Somnath, Suhas committed
979
    """
980
    cmap = get_cmap_object(cmap)
981
982
983

    if isinstance(cmap, str):
        cmap = plt.get_cmap(cmap)
Somnath, Suhas's avatar
Somnath, Suhas committed
984

985
    def __plot_centroids(centroids, ax, spec_val, spec_label, y_label, cmap, title=None):
986
        plot_line_family(ax, spec_val, centroids, label_prefix='Cluster', cmap=cmap)
Somnath, Suhas's avatar
Somnath, Suhas committed
987
        ax.set_ylabel(y_label)
Chris Smith's avatar
Chris Smith committed
988
        # ax.legend(loc='best')
Somnath, Suhas's avatar
Somnath, Suhas committed
989
990
991
992
        if title:
            ax.set_title(title)
            ax.set_xlabel(spec_label)

Unknown's avatar
Unknown committed
993
    if spec_val is None:
Chris Smith's avatar
Chris Smith committed
994
        spec_val = np.arange(mean_response.shape[1])
Somnath, Suhas's avatar
Somnath, Suhas committed
995

Chris Smith's avatar
Chris Smith committed
996
    if mean_response.dtype in [np.complex64, np.complex128, np.complex]:
Somnath, Suhas's avatar
Somnath, Suhas committed
997
        fig = plt.figure(figsize=(12, 8))
Chris Smith's avatar
Chris Smith committed
998
999
1000
        ax_map = plt.subplot2grid((2, 12), (0, 0), colspan=6, rowspan=2)
        ax_amp = plt.subplot2grid((2, 12), (0, 6), colspan=4)
        ax_phase = plt.subplot2grid((2, 12), (1, 6), colspan=4)
Somnath, Suhas's avatar
Somnath, Suhas committed
1001
1002
        axes = [ax_map, ax_amp, ax_phase]

1003
        __plot_centroids(np.abs(mean_response), ax_amp, spec_val, spec_label,
1004
                         resp_label + ' - Amplitude', cmap, 'Mean Response')
1005
        __plot_centroids(np.angle(mean_response), ax_phase, spec_val, spec_label,
1006
                         resp_label + ' - Phase', cmap)
Chris Smith's avatar
Chris Smith committed
1007
1008
        plot_handles, plot_labels = ax_amp.get_legend_handles_labels()

Somnath, Suhas's avatar
Somnath, Suhas committed
1009
    else:
Chris Smith's avatar
Chris Smith committed
1010
1011
1012
1013
        fig = plt.figure(figsize=(12, 8))
        ax_map = plt.subplot2grid((1, 12), (0, 0), colspan=6)
        ax_resp = plt.subplot2grid((1, 12), (0, 6), colspan=4)
        axes = [ax_map, ax_resp]
1014
        __plot_centroids(mean_response, ax_resp, spec_val, spec_label,
1015
                         resp_label, cmap, 'Mean Response')
Chris Smith's avatar
Chris Smith committed
1016
1017
1018
1019
1020
        plot_handles, plot_labels = ax_resp.get_legend_handles_labels()

    fleg = plt.figlegend(plot_handles, plot_labels, loc='center right',
                         borderaxespad=0.0)
    num_clusters = mean_response.shape[0]
Somnath, Suhas's avatar
Somnath, Suhas committed
1021
1022

    if isinstance(label_mat, h5py.Dataset):
Somnath, Suhas's avatar
Somnath, Suhas committed
1023
        """
Somnath, Suhas's avatar
Somnath, Suhas committed
1024
        Reshape label_mat based on linked positions
Somnath, Suhas's avatar
Somnath, Suhas committed
1025
        """
Somnath, Suhas's avatar
Somnath, Suhas committed
1026
1027
1028
1029
        pos = label_mat.file[label_mat.attrs['Position_Indices']]
        nx = len(np.unique(pos[:, 0]))
        ny = len(np.unique(pos[:, 1]))
        label_mat = label_mat[()].reshape(nx, ny)
1030

Chris Smith's avatar
Chris Smith committed
1031
    # im = ax_map.imshow(label_mat, interpolation='none')
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
    ax_map.set_xlabel(pos_labels[0])
    ax_map.set_ylabel(pos_labels[1])

    if pos_ticks is not None:
        x_ticks = np.linspace(0, label_mat.shape[1] - 1, 5, dtype=np.uint16)
        y_ticks = np.linspace(0, label_mat.shape[0] - 1, 5, dtype=np.uint16)
        ax_map.set_xticks(x_ticks)
        ax_map.set_yticks(y_ticks)
        ax_map.set_xticklabels(pos_ticks[0][x_ticks])
        ax_map.set_yticklabels(pos_ticks[1][y_ticks])

1043
    """divider = make_axes_locatable(ax_map)
Somnath, Suhas's avatar
Somnath, Suhas committed
1044
    cax = divider.append_axes("right", size="5%", pad=0.05)  # space for colorbar
1045
    fig.colorbar(im, cax=cax, ticks=np.arange(num_clusters),
1046
                 cmap=discrete_cmap(num_clusters, base_cmap=plt.cm.viridis))
1047
    ax_map.axis('tight')"""
1048
    pcol0 = ax_map.pcolor(label_mat, cmap=discrete_cmap(num_clusters, base_cmap=cmap))
1049
    fig.colorbar(pcol0, ax=ax_map, ticks=np.arange(num_clusters))
Somnath, Suhas's avatar
Somnath, Suhas committed
1050
    ax_map.axis('tight')
1051
    ax_map.set_aspect('auto')
Somnath, Suhas's avatar
Somnath, Suhas committed
1052
1053
1054
    ax_map.set_title('Cluster Label Map')

    fig.tight_layout()
Chris Smith's avatar
Chris Smith committed
1055
    fig.canvas.set_window_title('Cluster results')
Somnath, Suhas's avatar
Somnath, Suhas committed
1056
1057
1058

    return fig, axes

Unknown's avatar
Unknown committed
1059

Somnath, Suhas's avatar
Somnath, Suhas committed
1060
1061
###############################################################################

1062

1063
def plot_cluster_results_separate(label_mat, cluster_centroids, max_centroids=4, cmap=default_cmap,
1064
                                  spec_val=None, x_label='Excitation (a.u.)', y_label='Response (a.u.)'):
Somnath, Suhas's avatar
Somnath, Suhas committed
1065
    """
1066
    Plots the provided labels mat and centroids from clustering
Somnath, Suhas's avatar
Somnath, Suhas committed
1067

1068
1069
    Parameters
    ----------
Somnath, Suhas's avatar
Somnath, Suhas committed
1070
1071
1072
1073
    label_mat : 2D int numpy array
                structured as [rows, cols]
    cluster_centroids: 2D real numpy array
                       structured as [cluster,features]
1074
1075
    max_centroids : unsigned int
                    Number of centroids to plot
1076
1077
    cmap : plt.cm object or str, optional
        Colormap to use for the labels map and the centroids
1078
1079
1080
    spec_val :  array-like
        X axis to plot the centroids against
        If no value is specified, the data is plotted against the index
1081
1082
1083
1084
    x_label : String / unicode
              X label for centroid plots
    y_label : String / unicode
              Y label for centroid plots
Somnath, Suhas's avatar
Somnath, Suhas committed
1085

1086
1087
    Returns
    -------
Somnath, Suhas's avatar
Somnath, Suhas committed
1088
    fig
Somnath, Suhas's avatar
Somnath, Suhas committed
1089
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
1090

1091
    cmap = get_cmap_object(cmap)
1092

1093
    if max_centroids < 5:
Somnath, Suhas's avatar
Somnath, Suhas committed
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121

        fig501 = plt.figure(figsize=(20, 10))
        fax1 = plt.subplot2grid((2, 4), (0, 0), colspan=2, rowspan=2)
        fax2 = plt.subplot2grid((2, 4), (0, 2))
        fax3 = plt.subplot2grid((2, 4), (0, 3))
        fax4 = plt.subplot2grid((2, 4), (1, 2))
        fax5 = plt.subplot2grid((2, 4), (1, 3))
        fig501.tight_layout()
        axes_handles = [fax1, fax2, fax3, fax4, fax5]

    else:
        fig501 = plt.figure(figsize=(20, 10))
        # make subplot for cluster map
        fax1 = plt.subplot2grid((3, 6), (0, 0), colspan=3, rowspan=3)  # For cluster map
        fax1.set_xmargin(0.50)
        # make subplot for cluster centers
        fax2 = plt.subplot2grid((3, 6), (0, 3))
        fax3 = plt.subplot2grid((3, 6), (0, 4))
        fax4 = plt.subplot2grid((3, 6), (0, 5))
        fax5 = plt.subplot2grid((3, 6), (1, 3))
        fax6 = plt.subplot2grid((3, 6), (1, 4))
        fax7 = plt.subplot2grid((3, 6), (1, 5))
        fax8 = plt.subplot2grid((3, 6), (2, 3))
        fax9 = plt.subplot2grid((3, 6), (2, 4))
        fax10 = plt.subplot2grid((3, 6), (2, 5))
        fig501.tight_layout()
        axes_handles = [fax1, fax2, fax3, fax4, fax5, fax6, fax7, fax8, fax9, fax10]

1122
    # First plot the labels map:
1123
    pcol0 = fax1.pcolor(label_mat, cmap=discrete_cmap(cluster_centroids.shape[0], base_cmap=cmap))
1124
    fig501.colorbar(pcol0, ax=fax1, ticks=np.arange(cluster_centroids.shape[0]))
1125
1126
    fax1.axis('tight')
    fax1.set_aspect('auto')
1127
    fax1.set_title('Cluster Label Map')
1128
    """im = fax1.imshow(label_mat, interpolation='none')
1129
1130
    divider = make_axes_locatable(fax1)
    cax = divider.append_axes("right", size="5%", pad=0.05)  # space for colorbar