plot_utils.py 50.8 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
merged    
Chris Smith committed
7
from __future__ import division # int/int = float
8
from warnings import warn
9
import os
Chris Smith's avatar
merged    
Chris Smith committed
10
import h5py
11
import scipy
12
import matplotlib.pyplot as plt
13
from matplotlib.colors import LinearSegmentedColormap
14
import numpy as np
15
from ..analysis.utils.be_loop import loopFitFunction
16
from ..io.hdf_utils import reshape_to_Ndims, get_formatted_labels
17
18


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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)

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
77
78
79
def cmap_jet_white_center():
    """
    Generates the jet colormap with a white center

    Returns
    -------
    white_jet : matplotlib.colors.LinearSegmentedColormap object
        color map object that can be used in place of plt.cm.jet
    """
    # 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)
80

Chris Smith's avatar
Chris Smith committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def cmap_hot_desaturated():
    hot_desaturated = [(1, (255, 76, 76, 255)),
                       (0.857, (107, 0, 0, 255)),
                       (0.714, (255, 96, 0, 255)),
                       (0.571, (255, 255, 0, 255)),
                       (0.429, (0, 127, 0, 255)),
                       (0.285, (0, 255, 255, 255)),
                       (0.143, (0, 0, 91, 255)),
                       (0, (71, 71, 219, 255))]

    cdict = {'red': tuple([(dist, colors[0]/255.0, colors[0]/255.0) for (dist, colors) in hot_desaturated][::-1]),
             'green': tuple([(dist, colors[1]/255.0, colors[1]/255.0) for (dist, colors) in hot_desaturated][::-1]),
             'blue': tuple([(dist, colors[2]/255.0, colors[2]/255.0) for (dist, colors) in hot_desaturated][::-1])}

    return LinearSegmentedColormap('hot_desaturated', cdict)



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def discrete_cmap(num_bins, base_cmap=plt.cm.jet):
    """
    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
    -------
    new_cmap : matplotlib.colors.LinearSegmentedColormap object
        Discretized color map

    Credits
    -------
    Jake VanderPlas
    License: BSD-style
    """

    base = plt.cm.get_cmap(base_cmap)
    color_list = base(np.linspace(0, 1, num_bins))
    cmap_name = base.name + str(num_bins)
    return base.from_list(cmap_name, color_list, num_bins)

126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def plotLoopFitNGuess(Vdc, ds_proj_loops, ds_guess, ds_fit, title=''):
    '''
    Plots the loop guess, fit, source projected loops for a single cycle

    Parameters
    ----------
    Vdc - 1D float numpy array
        DC offset vector (unshifted)
    ds_proj_loops - 2D numpy array
        Projected loops arranged as [position, Vdc]
    ds_guess - 1D compound numpy array
        Loop guesses arranged as [position]
    ds_fit - 1D compound numpy array
        Loop fits arranged as [position]
    title - (Optional) String / unicode
        Title for the figure

    Returns
    ----------
    fig - matplotlib.pyplot.figure object
        Figure handle
    axes - 2D array of matplotlib.pyplot.axis handles
        handles to axes in the 2d figure
    '''
    shift_ind = int(-1 * len(Vdc) / 4)
    Vdc_shifted = np.roll(Vdc, shift_ind)

    num_plots = np.min([5, int(np.sqrt(ds_proj_loops.shape[0]))])
    fig, axes = plt.subplots(nrows=num_plots, ncols=num_plots, figsize=(18, 18))
    positions = np.linspace(0, ds_proj_loops.shape[0] - 1, num_plots ** 2, dtype=np.int)
    for ax, pos in zip(axes.flat, positions):
        ax.plot(Vdc, ds_proj_loops[pos, :], 'k', label='Raw')
        ax.plot(Vdc_shifted, loopFitFunction(Vdc_shifted, np.array(list(ds_guess[pos]))), 'g', label='guess')
        ax.plot(Vdc_shifted, loopFitFunction(Vdc_shifted, np.array(list(ds_fit[pos]))), 'r--', label='Fit')
        ax.set_xlabel('V_DC (V)')
        ax.set_ylabel('PR (a.u.)')
        ax.set_title('Loop ' + str(pos))
    ax.legend()
    fig.suptitle(title)
    fig.tight_layout()

    return fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
168
169
170

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

171
172

def rainbowPlot(ax, ao_vec, ai_vec, num_steps=32, cmap=plt.cm.jet, **kwargs):
Somnath, Suhas's avatar
Somnath, Suhas committed
173
174
175
176
    """
    Plots the input against the output waveform (typically loops).
    The color of the curve changes as a function of time using the jet colorscheme

177
178
    Parameters
    ----------
Somnath, Suhas's avatar
Somnath, Suhas committed
179
180
181
182
183
184
185
186
    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
187
188
    cmap : matplotlib.colors.LinearSegmentedColormap object
        Colormap to be used
Somnath, Suhas's avatar
Somnath, Suhas committed
189
190
191
192
193
    """
    pts_per_step = int(len(ai_vec) / num_steps)
    for step in xrange(num_steps - 1):
        ax.plot(ao_vec[step * pts_per_step:(step + 1) * pts_per_step],
                ai_vec[step * pts_per_step:(step + 1) * pts_per_step],
194
                color=cmap(255 * step / num_steps), **kwargs)
Somnath, Suhas's avatar
Somnath, Suhas committed
195
196
197
    # plot the remainder:
    ax.plot(ao_vec[(num_steps - 1) * pts_per_step:],
            ai_vec[(num_steps - 1) * pts_per_step:],
198
            color=cmap(255 * num_steps / num_steps), **kwargs)
Somnath, Suhas's avatar
Somnath, Suhas committed
199
200
201
202
203
    """
    CS3=plt.contourf([[0,0],[0,0]], range(0,310),cmap=plt.cm.jet)
    fig.colorbar(CS3)"""


204
205
206
207
208
209
210
211
212
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
def plot_line_family(ax, x_axis, line_family, line_names=None, label_prefix='Line', label_suffix='', cmap=plt.cm.jet, **kwargs):
    """
    Plots a family of lines with a sequence of colors

    Parameters
    ----------
    ax : axis handle
        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
    """
    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)]

    for line_ind in xrange(num_lines):
        ax.plot(x_axis, line_family[line_ind],
                label=line_names[line_ind],
                color=cmap(int(255 * line_ind / (num_lines - 1))), **kwargs)



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def plot_map(axis, data, stdevs=2, show_colorbar=False, **kwargs):
    """
    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
    stdevs : unsigned int (Optional. Default = 2)
        Number of standard deviations to consider for plotting
    show_colorbar : Boolean (Optional. Default = True)
        Whether or not to show the color bar
    Returns
    -------
    """
    data_mean = np.mean(data)
    data_std = np.std(data)
    if show_colorbar:
        pcol0 = axis.pcolor(data,
                            vmin=data_mean - stdevs * data_std, vmax=data_mean + stdevs * data_std, **kwargs)
        axis.figure.colorbar(pcol0, ax=axis)
        axis.axis('tight')
    else:
        axis.imshow(data, interpolation='none',
                    vmin=data_mean - stdevs * data_std, vmax=data_mean + stdevs * data_std, **kwargs)
    axis.set_aspect('auto')


Somnath, Suhas's avatar
Somnath, Suhas 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
###############################################################################

def plotLoops(excit_wfm, h5_loops, h5_pos=None, central_resp_size=None,
              evenly_spaced=True, plots_on_side=5, rainbow_plot=True,
              x_label='', y_label='', subtitles='Eigenvector', title=None):
    """
    Plots loops from up to 25 evenly spaced positions

    Parameters
    -----------
    excit_wfm : 1D numpy float array
        Excitation waveform in the time domain
    h5_loops : float HDF5 dataset reference or 2D numpy array
        Dataset containing data arranged as (pixel, time)
    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
    rainbow_plot : (optional) Boolean
        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
    """

    plots_on_side = min(abs(plots_on_side), 5)
    num_pos = h5_loops.shape[0]
    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)

    fig, axes = plt.subplots(nrows=sq_num_plots, ncols=sq_num_plots, figsize=(12, 12))
    axes_lin = axes.flat

    cent_ind = int(0.5 * h5_loops.shape[1])
    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
        r_resp_ind = h5_loops.shape[1]

    for count, posn in enumerate(chosen_pos):
        if rainbow_plot:
            rainbowPlot(axes_lin[count], excit_wfm[l_resp_ind:r_resp_ind], h5_loops[posn, l_resp_ind:r_resp_ind])
        else:
            axes_lin[count].plot(excit_wfm[l_resp_ind:r_resp_ind], h5_loops[posn, l_resp_ind:r_resp_ind])

        if type(h5_pos) != type(None):
            # print 'Row ' + str(h5_pos[posn,1]) + ' Col ' + str(h5_pos[posn,0])
            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))
    if title:
        fig.suptitle(title, fontsize=14)
    plt.tight_layout()
    return fig, axes
Chris Smith's avatar
merged    
Chris Smith committed
353
354
355


def plotSHOMaps(sho_maps, map_names, stdevs=2, title='', save_path=None): 
Somnath, Suhas's avatar
Somnath, Suhas committed
356
    """
Chris Smith's avatar
merged    
Chris Smith committed
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
    Plots the SHO quantity maps for a single UDVS step
    
    Parameters
    ------------
    sho_maps : List of 2D numpy arrays
        Each SHO map is structured as [row, col]
    map_names: List of strings
        Titles for each of the SHO maps
    stdevs : (Optional) Unsigned int
        Number of standard deviations from the mean to be used to clip the color axis
    title : (Optional) String
        Title for the entire figure. Group name is most appropriate here
    save_path : (Optional) String
        Absolute path to write the figure to
        
    Returns
    ----------
    None
Somnath, Suhas's avatar
Somnath, Suhas committed
375
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
376
    fig, axes = plt.subplots(ncols=3, nrows=2, sharex=True, figsize=(15, 10))
Chris Smith's avatar
merged    
Chris Smith committed
377
378
    
    for index, ax_hand, data_mat, qty_name in zip(range(len(map_names)), axes.flat, sho_maps, map_names):
Somnath, Suhas's avatar
Somnath, Suhas committed
379
        plot_map(ax_hand, data_mat, stdevs=stdevs)
Chris Smith's avatar
merged    
Chris Smith committed
380
381
        ax_hand.set_title(qty_name) 
         
Somnath, Suhas's avatar
Somnath, Suhas committed
382
383
    plt.setp([ax.get_xticklabels() for ax in axes[0, :]], visible=True)
    axes[1, 2].axis('off')
Chris Smith's avatar
merged    
Chris Smith committed
384
385
386
387
388
389
390
    
    plt.tight_layout()   
    if save_path:
        fig.savefig(save_path, format='png', dpi=300)


def plotVSsnapshots(resp_mat, title='', stdevs=2, save_path=None):
Somnath, Suhas's avatar
Somnath, Suhas committed
391
    """
Chris Smith's avatar
merged    
Chris Smith committed
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
    Plots the spatial distribution of the response at evenly spaced UDVS steps
    
    Parameters
    -------------
    resp_mat : 3D numpy array
        SHO responses arranged as [udvs_step, rows, cols]
    title : (Optional) String
        Super title for the plots - Preferably the group name
    stdevs : (Optional) string
        Number of standard deviations from the mean to be used to clip the color axis
    save_path : (Optional) String
        Absolute path to write the figure to
        
    Returns
    ----------
    None
Somnath, Suhas's avatar
Somnath, Suhas committed
408
    """
Chris Smith's avatar
merged    
Chris Smith committed
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
    
    num_udvs = resp_mat.shape[2]
    if num_udvs >= 9:
        tot_plots = 9
    elif num_udvs >= 4:
        tot_plots = 4
    else:
        tot_plots = 1
    delta_pos = int(np.ceil(num_udvs/tot_plots)) 
    
    fig, axes = plt.subplots(nrows=int(tot_plots**0.5),ncols=int(tot_plots**0.5),
                             sharex=True, sharey=True, figsize=(12, 12)) 
    if tot_plots > 1:    
        axes_lin = axes.reshape(tot_plots)
    else:
        axes_lin = axes
    
    for count, posn in enumerate(xrange(0,num_udvs, delta_pos)):
        
        snapshot = np.squeeze(resp_mat[:,:,posn])
429
430
        amp_mean = np.mean(snapshot) 
        amp_std = np.std(snapshot)
Chris Smith's avatar
merged    
Chris Smith committed
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
        ndims = len(snapshot.shape)
        if ndims == 2:
            axes_lin[count].imshow(snapshot, vmin=amp_mean-stdevs*amp_std, vmax=amp_mean+stdevs*amp_std)
        elif ndims == 1:
            np.clip(snapshot,amp_mean-stdevs*amp_std,amp_mean+stdevs*amp_std,snapshot)
            axes_lin[count].plot(snapshot)
        axes_lin[count].axis('tight')
        axes_lin[count].set_aspect('auto')
        axes_lin[count].set_title('UDVS Step #' + str(posn))
    
    fig.suptitle(title)
    plt.tight_layout()
    if save_path:
        fig.savefig(save_path, format='png', dpi=300)

Somnath, Suhas's avatar
Somnath, Suhas committed
446
447
448

def plotSpectrograms(eigenvectors, num_comps=4, title='Eigenvectors', xlabel='Step', stdevs=2,
                     show_colorbar=True):
Somnath, Suhas's avatar
Somnath, Suhas committed
449
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
    Plots the provided spectrograms from SVD V vector

    Parameters:
    -------------
    eigenvectors : 3D numpy complex matrices
        Eigenvectors rearranged as - [row, col, component]


    xaxis : 1D real numpy array
        The vector to plot against
    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

    Returns:
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
472
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
473
474
475
476
477
478
479
480
481
482
483
    import matplotlib.pyplot as plt
    fig_h, fig_w = (4, 4 + show_colorbar * 1.00)
    p_rows = int(np.ceil(np.sqrt(num_comps)))
    p_cols = int(np.floor(num_comps / p_rows))
    fig201, axes201 = plt.subplots(p_rows, p_cols, figsize=(p_cols * fig_w, p_rows * fig_h))
    fig201.subplots_adjust(hspace=0.4, wspace=0.4)
    fig201.canvas.set_window_title(title)

    for index in xrange(num_comps):
        cur_map = np.transpose(eigenvectors[index, :, :])
        ax = axes201.flat[index]
484
485
        mean = np.mean(cur_map)
        std = np.std(cur_map)
Somnath, Suhas's avatar
Somnath, Suhas committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
        ax.imshow(cur_map, cmap='jet',
                  vmin=mean - stdevs * std,
                  vmax=mean + stdevs * std)
        ax.set_title('Eigenvector: %d' % (index + 1))
        ax.set_aspect('auto')
        ax.set_xlabel(xlabel)
        ax.axis('tight')

    return fig201, axes201


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

def plotBEspectrograms(eigenvectors, num_comps=4, title='Eigenvectors', xlabel='UDVS Step', stdevs=2):
Somnath, Suhas's avatar
Somnath, Suhas committed
500
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
    Plots the provided spectrograms from SVD V vector

    Parameters:
    -------------
    eigenvectors : 3D numpy complex matrices
        Eigenvectors rearranged as - [row, col, component]


    xaxis : 1D real numpy array
        The vector to plot against
    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

    Returns:
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
523
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
524
525
526
527
528
529
530
531
532
533
    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)

    for index in xrange(num_comps):
        cur_map = np.transpose(eigenvectors[index, :, :])
        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):
534
535
            amp_mean = np.mean(func(cur_map))
            amp_std = np.std(func(cur_map))
Somnath, Suhas's avatar
Somnath, Suhas committed
536
537
538
539
540
541
542
543
544
545
546
547
548
            ax.imshow(func(cur_map), cmap='inferno',
                      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


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

def plotBEeigenvectors(eigenvectors, num_comps=4, xlabel=''):
Somnath, Suhas's avatar
Somnath, Suhas committed
549
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
    Plots the provided spectrograms from SVD V vector

    Parameters:
    -------------
    eigenvectors : 3D numpy complex matrices
        Eigenvectors rearranged as - [row, col, component]


    xaxis : 1D real numpy array
        The vector to plot against
    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

    Returns:
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
572
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
    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)
    fig201.canvas.set_window_title("Eigenvectors")

    for index in xrange(num_comps):
        cur_map = eigenvectors[index, :]
        #         axes = [axes201.flat[index], axes201.flat[index+num_comps], axes201.flat[index+2*num_comps], axes201.flat[index+3*num_comps]]
        axes = [axes201.flat[index], axes201.flat[index + num_comps]]
        for func, lab, ax in zip(funcs, labels, axes):
            ax.plot(func(cur_map))
            ax.set_title('Eigenvector: %d - %s' % (index + 1, lab))
        ax.set_xlabel(xlabel)
    fig201.tight_layout()

    return fig201, axes201


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

def plotBELoops(xaxis, xlabel, amp_mat, phase_mat, num_comps, title=None):
Somnath, Suhas's avatar
Somnath, Suhas committed
596
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
    Plots the provided loops from the SHO. Replace / merge with function in BESHOUtils

    Parameters:
    -------------
    xaxis : 1D real numpy array
        The vector to plot against
    xlabel : string
        Label for x axis
    amp_mat : 2D real numpy array
        Amplitude matrix arranged as [points, component]
    phase_mat : 2D real numpy array
        Phase matrix arranged as [points, component]
    num_comps : int
        Number of components to plot
    title : String
        Title to plot above everything else

    Returns:
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
617
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
    fig201, axes201 = plt.subplots(2, num_comps, figsize=(4 * num_comps, 6))
    fig201.subplots_adjust(hspace=0.4, wspace=0.4)
    fig201.canvas.set_window_title(title)

    for index in xrange(num_comps):
        axes = [axes201.flat[index], axes201.flat[index + num_comps]]
        resp_vecs = [amp_mat[index, :], phase_mat[index, :]]
        resp_titles = ['Amplitude', 'Phase']

        for ax, resp, titl in zip(axes, resp_vecs, resp_titles):
            ax.plot(xaxis, resp)
            ax.set_title('%s %d' % (titl, index + 1))
            ax.set_aspect('auto')
            ax.set_xlabel(xlabel)

    fig201.tight_layout()
    return fig201, axes201


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

def plotScree(S, title='Scree'):
Somnath, Suhas's avatar
Somnath, Suhas committed
640
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
641
642
643
644
645
646
647
648
649
650
    Plots the S or scree

    Parameters:
    -------------
    S : 1D real numpy array
        The S vector from SVD

    Returns:
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
651
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
    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)
    axes203.loglog(np.arange(len(S)) + 1, S, 'b', marker='*')
    axes203.set_xlabel('Principal Component')
    axes203.set_ylabel('Variance')
    axes203.set_title(title)
    axes203.set_xlim(left=1, right=len(S))
    axes203.set_ylim(bottom=np.min(S), top=np.max(S))
    fig203.canvas.set_window_title("Scree")

    return fig203, axes203


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

Somnath, Suhas's avatar
Somnath, Suhas committed
667
668
def plot_map_stack(map_stack, num_comps=4, stdevs=2, show_colorbar=True,
                   title='Component', heading='Map Stack', **kwargs):
Somnath, Suhas's avatar
Somnath, Suhas committed
669
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
670
    Plots the provided stack of maps
Somnath, Suhas's avatar
Somnath, Suhas committed
671
672
673

    Parameters:
    -------------
Somnath, Suhas's avatar
Somnath, Suhas committed
674
    map_stack : 3D real numpy array
Somnath, Suhas's avatar
Somnath, Suhas committed
675
676
677
678
679
680
681
682
683
684
685
686
687
        structured as [rows, cols, component]
    num_comps : int
        Number of components to plot
    stdevs : int
        Number of standard deviations to consider for plotting
    colormap : string or object from matplotlib.colors (Optional. Default = jet or rainbow)
        Colormap for the plots
    show_colorbar : Boolean (Optional. Default = True)
        Whether or not to show the color bar

    Returns:
    ---------
    fig, axes
Somnath, Suhas's avatar
Somnath, Suhas committed
688
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
689
690
691
692
693
    fig_h, fig_w = (4, 4 + show_colorbar * 1.00)
    p_rows = int(np.ceil(np.sqrt(num_comps)))
    p_cols = int(np.floor(num_comps / p_rows))
    fig202, axes202 = plt.subplots(p_cols, p_rows, figsize=(p_cols * fig_w, p_rows * fig_h))
    fig202.subplots_adjust(hspace=0.4, wspace=0.4)
Somnath, Suhas's avatar
Somnath, Suhas committed
694
695
    fig202.canvas.set_window_title(heading)
    fig202.suptitle(heading, fontsize=16)
Somnath, Suhas's avatar
Somnath, Suhas committed
696
697

    for index in xrange(num_comps):
Somnath, Suhas's avatar
Somnath, Suhas committed
698
699
        plot_map(axes202.flat[index], map_stack[:, :, index], stdevs=stdevs, show_colorbar=show_colorbar, **kwargs)
        axes202.flat[index].set_title('{} {}'.format(title, index))
Somnath, Suhas's avatar
Somnath, Suhas committed
700
701
702
703
    fig202.tight_layout()

    return fig202, axes202

704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# TODO: The label and units for the main dataset itself are missing in most cases! - ie. I don't know that the data is 'Current' and 'nA'


def plot_cluster_results(h5_group, y_spec_label):
    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)

    pos_ticks = [h5_pos_vals[:pos_dims[0], 0], h5_pos_vals[slice(0,None,pos_dims[0]), 1]]
    # 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)

    plotClusterResults(label_mat, mean_response, spec_val=np.squeeze(h5_spec_vals[0]),
                       spec_label=x_spec_label, resp_label=y_spec_label,
                       pos_labels=pos_labels, pos_ticks=pos_ticks)
Somnath, Suhas's avatar
Somnath, Suhas committed
745
746

###############################################################################
747
748


Chris Smith's avatar
Chris Smith committed
749
def plotClusterResults(label_mat, mean_response, spec_val=None, cmap=plt.cm.jet,
750
751
                       spec_label='Spectroscopic Value', resp_label='Response',
                       pos_labels=('X', 'Y'), pos_ticks=None):
Somnath, Suhas's avatar
Somnath, Suhas committed
752
    """
Chris Smith's avatar
Chris Smith committed
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
    Plot the cluster labels and mean response for each cluster

    Parameters
    ----------
    label_mat : 2D ndarray or h5py.Dataset of ints
        Spatial map of cluster labels structured as [rows, cols]
    mean_response : 2D ndarray or h5py.Dataset
        Mean value of each cluster over all samples 
        arranged as [cluster number, features]
    spec_val :  1D ndarray or h5py.Dataset of floats, optional
        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
775
776
777
778
    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
779
780
781
782
783
784
785

    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
786
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
787
788

    def __plotCentroids(centroids, ax, spec_val, spec_label, y_label, cmap, title=None):
789
        plot_line_family(ax, spec_val, centroids, label_prefix='Cluster', cmap=cmap)
Somnath, Suhas's avatar
Somnath, Suhas committed
790
        ax.set_ylabel(y_label)
Chris Smith's avatar
Chris Smith committed
791
        # ax.legend(loc='best')
Somnath, Suhas's avatar
Somnath, Suhas committed
792
793
794
795
796
        if title:
            ax.set_title(title)
            ax.set_xlabel(spec_label)

    if type(spec_val) == type(None):
Chris Smith's avatar
Chris Smith committed
797
        spec_val = np.arange(mean_response.shape[1])
Somnath, Suhas's avatar
Somnath, Suhas committed
798

Chris Smith's avatar
Chris Smith committed
799
    if mean_response.dtype in [np.complex64, np.complex128, np.complex]:
Somnath, Suhas's avatar
Somnath, Suhas committed
800
        fig = plt.figure(figsize=(12, 8))
Chris Smith's avatar
Chris Smith committed
801
802
803
        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
804
805
        axes = [ax_map, ax_amp, ax_phase]

Chris Smith's avatar
Chris Smith committed
806
807
808
        __plotCentroids(np.abs(mean_response), ax_amp, spec_val, spec_label,
                        resp_label + ' - Amplitude', cmap, 'Mean Response')
        __plotCentroids(np.angle(mean_response), ax_phase, spec_val, spec_label,
Somnath, Suhas's avatar
Somnath, Suhas committed
809
                        resp_label + ' - Phase', cmap)
Chris Smith's avatar
Chris Smith committed
810
811
        plot_handles, plot_labels = ax_amp.get_legend_handles_labels()

Somnath, Suhas's avatar
Somnath, Suhas committed
812
    else:
Chris Smith's avatar
Chris Smith committed
813
814
815
816
817
818
819
820
821
822
823
        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]
        __plotCentroids(mean_response, ax_resp, spec_val, spec_label,
                        resp_label, cmap, 'Mean Response')
        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
824
825

    if isinstance(label_mat, h5py.Dataset):
Somnath, Suhas's avatar
Somnath, Suhas committed
826
        """
Somnath, Suhas's avatar
Somnath, Suhas committed
827
        Reshape label_mat based on linked positions
Somnath, Suhas's avatar
Somnath, Suhas committed
828
        """
Somnath, Suhas's avatar
Somnath, Suhas committed
829
830
831
832
        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)
833

Chris Smith's avatar
Chris Smith committed
834
    # im = ax_map.imshow(label_mat, interpolation='none')
835
836
837
838
839
840
841
842
843
844
845
    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])

846
    """divider = make_axes_locatable(ax_map)
Somnath, Suhas's avatar
Somnath, Suhas committed
847
    cax = divider.append_axes("right", size="5%", pad=0.05)  # space for colorbar
848
849
850
851
852
    fig.colorbar(im, cax=cax, ticks=np.arange(num_clusters),
                 cmap=discrete_cmap(num_clusters, base_cmap=plt.cm.jet))
    ax_map.axis('tight')"""
    pcol0 = ax_map.pcolor(label_mat, cmap=discrete_cmap(num_clusters, base_cmap=plt.cm.jet))
    fig.colorbar(pcol0, ax=ax_map, ticks=np.arange(num_clusters))
Somnath, Suhas's avatar
Somnath, Suhas committed
853
    ax_map.axis('tight')
854
    ax_map.set_aspect('auto')
Somnath, Suhas's avatar
Somnath, Suhas committed
855
856
857
    ax_map.set_title('Cluster Label Map')

    fig.tight_layout()
Chris Smith's avatar
Chris Smith committed
858
    fig.canvas.set_window_title('Cluster results')
Somnath, Suhas's avatar
Somnath, Suhas committed
859
860
861
862
863

    return fig, axes

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

864
865
866

def plotKMeansClusters(label_mat, cluster_centroids, max_centroids=4,
                       spec_val=None, x_label='Excitation (a.u.)', y_label='Response (a.u.)'):
Somnath, Suhas's avatar
Somnath, Suhas committed
867
    """
868
    Plots the provided labels mat and centroids from clustering
Somnath, Suhas's avatar
Somnath, Suhas committed
869

870
871
    Parameters
    ----------
Somnath, Suhas's avatar
Somnath, Suhas committed
872
873
874
875
    label_mat : 2D int numpy array
                structured as [rows, cols]
    cluster_centroids: 2D real numpy array
                       structured as [cluster,features]
876
877
    max_centroids : unsigned int
                    Number of centroids to plot
878
879
880
    spec_val :  array-like
        X axis to plot the centroids against
        If no value is specified, the data is plotted against the index
881
882
883
884
    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
885

886
887
    Returns
    -------
Somnath, Suhas's avatar
Somnath, Suhas committed
888
    fig
Somnath, Suhas's avatar
Somnath, Suhas committed
889
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
890

891
    if max_centroids < 5:
Somnath, Suhas's avatar
Somnath, Suhas committed
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919

        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]

920
    # First plot the labels map:
921
922
    pcol0 = fax1.pcolor(label_mat, cmap=discrete_cmap(cluster_centroids.shape[0],
                                                      base_cmap=plt.cm.jet))
923
    fig501.colorbar(pcol0, ax=fax1, ticks=np.arange(cluster_centroids.shape[0]))
924
925
    fax1.axis('tight')
    fax1.set_aspect('auto')
926
    fax1.set_title('Cluster Label Map')
927
    """im = fax1.imshow(label_mat, interpolation='none')
928
929
    divider = make_axes_locatable(fax1)
    cax = divider.append_axes("right", size="5%", pad=0.05)  # space for colorbar
930
931
932
933
    plt.colorbar(im, cax=cax)"""

    if spec_val is None and cluster_centroids.ndim == 2:
        spec_val = np.arange(cluster_centroids.shape[1])
934
935

    # Plot results
936
937
938
939
940
941
942
943
    for ax, index in zip(axes_handles[1: max_centroids + 1], np.arange(max_centroids)):
        if cluster_centroids.ndim == 2:
            ax.plot(spec_val, cluster_centroids[index, :],
                    color=plt.cm.jet(int(255 * index / (cluster_centroids.shape[0] - 1))))
            ax.set_xlabel(x_label)
            ax.set_ylabel(y_label)
        elif cluster_centroids.ndim == 3:
            plot_map(ax, cluster_centroids[index], show_colorbar=True)
944
        ax.set_title('Centroid: %d' % index)
Somnath, Suhas's avatar
Somnath, Suhas committed
945
946

    fig501.subplots_adjust(hspace=0.60, wspace=0.60)
947
    fig501.tight_layout()
Somnath, Suhas's avatar
Somnath, Suhas committed
948
949
950
951
952
953
954
955

    return fig501


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

def plotClusterDendrograms(label_mat, e_vals, num_comp, num_cluster, mode='Full', last=None,
                           sort_type='distance', sort_mode=True):
Somnath, Suhas's avatar
Somnath, Suhas committed
956
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
957
958
959
960
961
962
    Creates and plots the dendrograms for the given label_mat and
    eigenvalues

    Parameters
    -------------
    label_mat : 2D real numpy array
963
        structured as [rows, cols], from KMeans clustering
Somnath, Suhas's avatar
Somnath, Suhas committed
964
    e_vals: 3D real numpy array of eigenvalues
965
        structured as [component, rows, cols]
Somnath, Suhas's avatar
Somnath, Suhas committed
966
    num_comps : int
967
968
969
        Number of components used to make eigenvalues
    num_cluster : int
        Number of cluster used to make the label_mat
Somnath, Suhas's avatar
Somnath, Suhas committed
970
    mode: str, optional
971
972
973
        How should the dendrograms be created.
        "Full" -- use all clusters when creating the dendrograms
        "Truncated" -- stop showing clusters after 'last'
Somnath, Suhas's avatar
Somnath, Suhas committed
974
    last: int, optional - should be provided when using "Truncated"
975
976
977
978
979
980
981
982
983
984
985
986
987
988
        How many merged clusters should be shown when using
        "Truncated" mode
    sort_type: {'count', 'distance'}, optional
        What type of sorting should be used when plotting the
        dendrograms.  Options are:
        count - Uses the count_sort from scipy.cluster.hierachy.dendrogram
        distance - Uses the distance_sort from scipy.cluster.hierachy.dendrogram
    sort_mode: {False, True, 'ascending', 'descending'}, optional
        For the chosen sort_type, which mode should be used.
        False - Does no sorting
        'ascending' or True - The child with the minimum of the chosen sort
        parameter is plotted first
        'descending' - The child with the maximum of the chosen sort parameter is
        plotted first
Somnath, Suhas's avatar
Somnath, Suhas committed
989
990
991

    Returns
    ---------
992
993
    fig : matplotlib.pyplot Figure object
        Figure containing the dendrogram
Somnath, Suhas's avatar
Somnath, Suhas committed
994
    """
Somnath, Suhas's avatar
Somnath, Suhas committed
995
996
997
998
999
1000
    if mode == 'Truncated' and not last:
        warn('Warning: Truncated dendrograms requested, but no last cluster given.  Reverting to full dendrograms.')
        mode = 'Full'

    if mode == 'Full':
        print 'Creating full dendrogram from clusters'