data_table.py 24.9 KB
Newer Older
1
2
3
4
# -*- coding: utf-8 -*-
"""Data_table class which is the base for the other data types like data_line,
data_complex and data_IQ. The idea is adapted from holoviews (holoviews.org)
and builds on pandas as excellent data processing tool.
5
6
7

Author: Christian Schneider <c.schneider@uibk.ac.at>
Date: 16.03.2018
8
9
10
"""
from .base import data_module_base
import pandas as pd
11
from .plot_style import color_scheme, cc, check_color, color_labels
12
import holoviews as hv
User expired's avatar
User expired committed
13
import holoviews.operation.datashader as hd
14
import numpy as np
15
16
17
18
try:
    import matplotlib.pyplot as plt
except NotImplementedError:
    pass
19
import bokeh.plotting as bp
20
from bokeh.models import HoverTool
21
22
23
24
import scipy.optimize as sp_opt
import scipy.signal as sp_sig
import scipy.interpolate as sp_intp
from collections import OrderedDict
25

26

Gerhard Kirchmair's avatar
Gerhard Kirchmair committed
27
hv.extension('bokeh', logo=False)
28

29
30
31
32
33
34
35
36
37
38

class data_table(data_module_base):
    """Class for table like data with one or more independent variables and
    one or more dependent variables

    Parameters
    -----------
    data_arrays : list, array, np.array
        Data to save. Format should be
        [array_x, array_y, array_z, ...]
39
40
41
    data_names : list, array, np.array
        Labels for the data. Format should be
        ['Label first axis', 'Label second axis', ...]
42
43
    """

44
    def __init__(self, data_arrays=None, data_names=None):
45
        super().__init__()
46
47
48
        # Create default data and names
        if data_arrays is None:
            data_arrays = [[np.nan], [np.nan]]
49
        df_names = ['x', 'y', 'z'][:len(data_arrays)]
50
51
        df_names += ['x{}'.format(i) for i in range(3, len(data_arrays))]

52
53
54
55
        # Replace default names by the names given
        if data_names:
            for idx in range(len(data_names)):
                if data_names[idx]:
56
                    df_names[idx] = data_names[idx]
57

58
        # Create dictionary for pandas dataframe
59
60
        tmp_dict = {}
        for idx, d in enumerate(data_arrays):
61
62
            tmp_dict[df_names[idx]] = data_arrays[idx]

63
        # Create dataframe
64
65
        self.df = pd.DataFrame(data=tmp_dict)

66
67
68
69
70
71
72
73
        # Create easy access variables
        self.name_x = df_names[0]
        self.name_y = df_names[1]

        # Create further variables
        self._fit_executed = False
        self._fit_labeles = None

74
75
76
        # Order dataframe
        self.df = self.df[df_names]

77
78
79
80
81
    def _repr_html_(self):
        """Show pandas dataframe as default representation"""
        return '<h3>data_table</h3>' + self.df.head().to_html()

    def return_x(self):
Christian Schneider's avatar
Christian Schneider committed
82
        return np.array(self.df[self.name_x][self.idx_min:self.idx_max])
83
84
85
86
87

    def return_y(self):
        if '{}_smoothed'.format(self.name_y) in self.df.keys():
            # Return smoothed data
            name = '{}_smoothed'.format(self.name_y)
Christian Schneider's avatar
Christian Schneider committed
88
            return np.array(self.df[name][self.idx_min:self.idx_max])
89
        else:
Christian Schneider's avatar
Christian Schneider committed
90
            return np.array(self.df[self.name_y][self.idx_min:self.idx_max])
91
92
93
94
95
96
97

    @property
    def x(self):
        return self.return_x()

    @x.setter
    def x(self, value):
98
        if len(value) != len(self.x):
99
            self.df = self.df.reindex(range(len(value)))
Christian Schneider's avatar
Christian Schneider committed
100
        self.df[self.name_x][self.idx_min:self.idx_max] = value
101
102
103
104
105
106
107

    @property
    def y(self):
        return self.return_y()

    @y.setter
    def y(self, value):
Christian Schneider's avatar
Christian Schneider committed
108
        self.df[self.name_y][self.idx_min:self.idx_max] = value
109
110
111
112
113
114
115
116
117
118
119

    def rename_x(self, new_name):
        """Rename x variable"""
        self.df = self.df.rename(columns={self.name_x: new_name})
        self.name_x = new_name

    def rename_y(self, new_name):
        """Rename y variable"""
        self.df = self.df.rename(columns={self.name_y: new_name})
        self.name_y = new_name

120
121
122
    def rename(self, column_name, new_column_name):
        self.df = self.df.rename(column={column_name: new_column_name})

123
124
125
126
127
128
129
130
131
132
133
134
135
    def add_column(self, column, name):
        """Add a new column to the dataframe. New Column has to be equal or
        shorter then first column (independent variable)
        
        Parameters
        -----------
        column : list, array
            New column to add
        name : str
            Name for column
        """
        self.df[name] = pd.Series(column)

136
    def import_data(self, data_arrays, data_names=None):
137
138
        """Import data from new array. Naming highly recommended!
        Assumes first given array is the array of the independent variable.
139
140
141
142
        Parameters
        -----------
        data_arrays : list, array, np.array
            List of data arrays. Structure
143
            [[x, x, x, x, ....], [y, y, y,....], [z, z, z, z, ...]
Christian Schneider's avatar
Christian Schneider committed
144
        data_names : list, array, np.array, None
145
            List of names for arrays:
146
            ['x', 'y', 'Resistances', ... ]
147
148
        """
        if data_names:
149
            order_names = data_names
150
        else:
151
            order_names = self.df.columns
152

153
        # Check if column/dependent variable already exists, if not --> create
154
155
        for idx, d_name in zip(range(1, len(order_names) + 1),
                               order_names[1:]):
156
157
            if d_name not in self.df.keys():
                if (self.df[order_names[0]] == data_arrays[0]).all():
Christian Schneider's avatar
Christian Schneider committed
158
159
                    # Quick check: If independent variable is the same as
                    # already given, just add new column
160
161
162
163
164
165
166
167
168
169
170
171
                    self.df[d_name] = data_arrays[idx]
                else:
                    # Fill existing array with np.nan
                    self.df[d_name] = [np.nan for i in
                                       range(len(self.df[order_names[0]]))]

        # Add values if not already added
        for idx, d in zip(range(len(data_arrays[0])), data_arrays[0]):
            # Check if value for independent variable already exists
            df_idxs = self.df.index[self.df[order_names[0]] == d]
            if not df_idxs.empty:
                df_idx = df_idxs[0]  # take first element
172
                for i in range(1, len(data_arrays)):
173
174
175
                    if np.isfinite(self.df[order_names[i]][df_idx]):
                        # TODO Is running double if added above --> change
                        # Check if entry is np.nan, if not use mean
176
                        self.df[order_names[i]][df_idx] += data_arrays[i][idx]
177
178
179
                        self.df[order_names[i]][df_idx] /= 2
                    else:
                        # Else just take new value
180
                        self.df[order_names[i]][df_idx] = data_arrays[i][idx]
181
            else:
182
                self.df = self.df.append({key: value[idx] for key, value
183
                                          in zip(order_names, data_arrays)},
184
                                         ignore_index=True)
185
                pass
186

User expired's avatar
User expired committed
187
    
188
    def plot_hv(self, x=None, y=None, height=400, width=800,
189
                title='', color=None):
190
        '''Plot table with Holoviews
191
192
193
194
195
196
197
198
199
200
201

        Parameters
        -----------
        x : None, str, list
            Column name(s) used for x axis
        y : None, str, list
            Column name(s) used for y axis
        height : int
            Height of plot in pixels
        width : int
            Width of plot in pixels
202
203
204
205
        title : str
            Title of plot
        color : str
            Color for plot
206
        '''
207
        if x is None:
208
            x_val = self.name_x
209
        else:
210
            x_val = x
211
212

        if y is None:
213
            y_val = self.name_y
214
        else:
215
            y_val = y
216

217
218
219
220
        if color is None:
            color = color_scheme[0]
        elif color in cc.keys():
            color = cc[color]
221

222
        # Plot
223
224
        s = hv.Scatter(self.df[self.idx_min:self.idx_max],
                       x_val, y_val, label=title)
225
        scatter_plots = hd.dynspread(hd.datashade(hv.Curve(s), cmap=[color]))
226
227
228

        return scatter_plots.opts(plot=dict(height=height, width=width,
                                            show_grid=True))
User expired's avatar
User expired committed
229
    
230
    # Plotting #################################################################
Christian Schneider's avatar
Christian Schneider committed
231
232
    def plot(self, style='-o', x_col=None, y_col=None, color=None, xscale=1,
             yscale=1,
233
             plot_fit=True, linewidth=1.5, markersize=3,
234
235
             fit_linewidth=1, plot_errors=True, legend=None,
             legend_pos=0, engine=None, title='', show=True, fig=None,
236
             fitcolor='r', fit_on_top=False,
237
             logy=False, logx=False, **kwargs):
238
239
240
241
242
243
244
245
246
        """Plot data and optionally the fit.

        Choose between two plot-engines: 'bokeh' and 'pyplot'

        Parameters
        ----------
        style : str
            Specify plot style in matplotlib language. E.g. 'b-o' for
            blue dots connected with a line.
Christian Schneider's avatar
Christian Schneider committed
247
248
249
250
251
252
        x_col : str, None
            Name of column for plot on x axis. If none is given, first column is
            taken
        y_col : str, None
            Name of column for plot on y axis. If none is given, second column
            is taken
253
254
        color : str
            Color shortcut (eg. 'b') or specific color like '#123456'.
Christian Schneider's avatar
Christian Schneider committed
255
            Type cc to see available colors.
256
257
258
259
260
261
262
263
264
265
266
267
        xscale : float
            X scaling
        yscale : float
            Y scaling
        plot_fit : bool
            Plot the fit if available
        linewidth : int
            Thickness of lines
        markersize : int
            Size of markers
        fit_linewidth : int
            Thickness of fit line
268
        plot_errors : bool
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
            Plot error bars
        legend : list
            Custom legend for plot ['Label 1', 'Label 2']]
        legend_pos : int, str
            Location of legend
        engine : str
            Plot engine. Choose between 'bokeh' and 'pyplot'
        title : str
            Title of the plot
        show : bool
            Directly show plot. Useful if one wants to add labels etc.
            and show plot afterwards.
        fig : object
            Figure to plot into (bokeh/matplotlib figure object)
        fitcolor : str
            Color shortcut (like 'b') or specific color (like #123456) for
            fit
        fit_on_top : bool
            Data over fit or fit over data
288
289
290
291
        logy : bool
            Logarithmic y scale
        logx : bool
            Logarithmic x scale
292
293
294
295
296
297
298
299

        Returns
        --------
        object
            Returns a fit object for bokeh or matplotlib. This is useful, if
            you want to add for example another points, lines, labels, etc
            afterwards.
        """
300
        # Get default data or specified columns
Christian Schneider's avatar
Christian Schneider committed
301
302
303
        if x_col is None:
            x_col = self.name_x
        if y_col is None:
Christian Schneider's avatar
Christian Schneider committed
304
305
306
307
            if '{}_smoothed'.format(self.name_y) in self.df.keys():
                y_col = '{}_smoothed'.format(self.name_y)
            else:
                y_col = self.name_y
Christian Schneider's avatar
Christian Schneider committed
308

309
310
        x = np.array(self.df[x_col])[self.idx_min:self.idx_max]
        y = np.array(self.df[y_col])[self.idx_min:self.idx_max]
311
312
313
314
315
316
317

        # Check for default plot engine
        if engine is None:
            if len(x) > 5000:
                engine = 'h'  # Use holoviews for large data
            else:
                engine = 'b'  # Use bokeh for small data
318
319
320
321
322
323
324
325
326
327
328
329
330
331

        # Don't show plot if figure is given (normally one does not need this)
        if fig:
            show = False
        # Get fit function
        if plot_fit and self._fit_executed:
            exec(self._fit_function_code)
            possibles = globals().copy()
            possibles.update(locals())
            fitfunc = possibles.get(self._fit_function)
            if not fitfunc:
                raise Exception('Method %s not implemented' %
                                self._fit_function)

332
333
334
335
336
337
338
339
340
        # Check for color specified in style
        if color is None:
            color = check_color(style)

        if color in color_labels:
            c = cc[color]
        else:
            c = color

341
342
        # Bokeh
        if engine in ['bokeh', 'b']:
343
344
345
346
            # Create Figure if no figure is given
            if fig is None:
                tools = ['box_zoom', 'pan', 'wheel_zoom', 'reset',
                         'save', 'hover']
347
348
349
350
351
                kws = {}
                if logx:
                    kws['x_axis_type'] = 'log'
                if logy:
                    kws['y_axis_type'] = 'log'
352
                fig = bp.figure(plot_width=800, plot_height=400, tools=tools,
353
354
                                toolbar_location='above', title=title,
                                **kws)
355
356
357
358
359
360

            # Empty legend if no legend is given
            if legend is None:
                legend = ""

            # Plot Data
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
            if ("{} Errors".format(self.name_y) in self.df.keys() and
                    plot_errors):
                # Just plot dots if error bars given
                fig.circle(x, y, fill_color=c, line_color=c,
                           size=markersize, legend=legend, **kwargs)

                err_xs = []
                err_ys = []
                errs = self.df[self.name_y + ' Errors'][
                       self.idx_min:self.idx_max]
                for xs, ys, yerr in zip(x, y, errs):
                    err_xs.append((xs, xs))
                    err_ys.append((ys - yerr, ys + yerr))
                fig.multi_line(err_xs, err_ys, color=c)
            else:
                for kw in style:
                    if kw == '-':
                        fig.line(x * xscale, y * yscale, line_color=c,
                                 line_width=linewidth, legend=legend, **kwargs)
                    elif kw == 'o':
                        fig.circle(x, y, fill_color=c, line_color=c,
                                   size=markersize, legend=legend, **kwargs)
383

384
            # Plot Fit
385
            if plot_fit and self._fit_executed:
Christian Schneider's avatar
Christian Schneider committed
386
387
388
389
390
391
                # Get color
                if fitcolor in color_labels:
                    fc = cc[fitcolor]
                else:
                    fc = fitcolor
                # Plot fit
392
                fig.line(x * xscale, fitfunc(x, *self._fit_parameters) * yscale,
Christian Schneider's avatar
Christian Schneider committed
393
                         line_color=fc, line_width=fit_linewidth)
394
395

            # Format nicer HoverTool
Christian Schneider's avatar
Christian Schneider committed
396
            tooltips = [(x_col, "$x"), (y_col, "$y")]
397
398
399
            fig.select(dict(type=HoverTool)).tooltips = OrderedDict(tooltips)

            # Add labels
Christian Schneider's avatar
Christian Schneider committed
400
401
            fig.xaxis.axis_label = x_col
            fig.yaxis.axis_label = y_col
402
403
404
405
406
407
408

            if show:
                bp.show(fig)
            return fig

        # Matplotlib
        elif engine in ['pyplot', 'p']:
Christian Schneider's avatar
Christian Schneider committed
409
410
411
412
413
            if not fig:
                try:
                    fig = plt.gcf()
                except:
                    fig = plt.figure()
414

Christian Schneider's avatar
Christian Schneider committed
415
            plt.title(title)
416
            # Plot errors
Christian Schneider's avatar
Christian Schneider committed
417
            # Data
418
            if (plot_errors and "{} Errors".format(self.name_y) in
419
                    self.df.keys()):
420
                yerrs = np.array(self.df[self.name_y + ' Errors'][
421
422
                                 self.idx_min:self.idx_max]) * yscale
                plt.errorbar(x * xscale, y * yscale, fmt=style, color=c,
Christian Schneider's avatar
Christian Schneider committed
423
                             yerr=yerrs, markersize=markersize, **kwargs)
424

Christian Schneider's avatar
Christian Schneider committed
425
            else:
426
                plt.plot(x * xscale, y * yscale, style, color=c,
Christian Schneider's avatar
Christian Schneider committed
427
428
                         linewidth=linewidth, markersize=markersize,
                         **kwargs)
429

Christian Schneider's avatar
Christian Schneider committed
430
            # Fit
431
432
            if plot_fit and self._fit_executed:
                if not fit_on_top:
433
                    fit_zorder = 0
434
                else:
435
436
                    fit_zorder = 99
                plt.plot(x * xscale, fitfunc(x, *self._fit_parameters) * yscale,
437
438
439
                         '-', color=fitcolor, linewidth=fit_linewidth,
                         zorder=fit_zorder)

440
441
442
443
444
445
446
                if logx and logy:
                    plt.loglog()
                elif logx:
                    plt.semilogx()
                elif logy:
                    plt.semilogy()

447
            # Labels
Christian Schneider's avatar
Christian Schneider committed
448
449
            plt.xlabel(x_col)
            plt.ylabel(y_col)
450
451
            # Styling
            plt.grid()
452
            plt.xlim([x[0] * xscale, x[-1] * xscale])
453

Christian Schneider's avatar
Christian Schneider committed
454
        elif engine in ['holoviews', 'h', 'hv']:
455
456
            return self.plot_hv(color=color, **kwargs)

457
    def plot_all(self, colormap=None):
458
459
460
461
462
463
464
465
466
467
468
        """Fast plot of the whole data in holoviews"""

        # Get default colormap
        if colormap is None:
            colormap = color_scheme

        # Get columns
        cols = self.df.columns[1:]

        # Create dots of the first point for legend (bug in holoviews)
        color_points = hv.NdOverlay({cols[i]:
469
470
471
472
                                         hv.Points([[self.x[0],
                                                     self.df[cols[i]][0]]],
                                                   label=str(cols[i]))
                                    .opts(style=dict(color=colormap[i]))
473
474
475
476
477
                                     for i in range(len(cols))})
        plot = color_points
        for col, c in zip(cols, colormap):
            plot *= self.plot_hv(y=col, color=c)
        return plot
478

Christian Schneider's avatar
Christian Schneider committed
479
480
    def fit(self, fitfunc, fit_p_init, boundaries = None,plot=True,
            plot_init=False, plot_params=True, labels=None, **kwargs):
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
        """Fit `fitfunc` to data with initial fit parameters `fit_p_init`

        Note
        -----
            After the fit, the data module will contain the fit, however it
            should be saved again. Don't forget this.

            The fit will be performed on the stored data, not the plotted
            one. If you use xscale or yscale different than the one you
            plot, you should take it into account

        Parameters
        -----------
        fitfunc : func
            Function to fit to. There exist already some functions in the
            DataModule library (DataModule/fit_functions)
        fit_p_init : list
            Initial (guessed) parameters
        plot : bool
            Plot fit after result
        plot_init : bool
            Plot initial guess.
503
504
        plot_params : bool
            Print paramaters for fit
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
        labels : list
            Label for fitparameters. E.g. ['offset', 'amplitude', 'fr']
        **kwargs : keywords
            Keywords for fitfunction like maxfev=10000, epsfcn=1e-10,
            factor=0.1, xtol=1e-9, ftol=1e-9...

        At the end of the fit the data module will contain the function
        used to fit and some fit-related functions will be enabled.
        The fit parameters are stored in
        self._fit_parameters, self._fit_par_errors
        and the average error (sigma) in self._fit_data_error.

        Returns
        list, list, float

        """
521
        xsel, ysel = self.return_x(), self.return_y()
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
        try:
            fit_p_fit, err = sp_opt.curve_fit(fitfunc, xsel, ysel, fit_p_init,
                                              **kwargs)
        except RuntimeError:
            print('At least one fit did not converge', end=' ', flush=True)
            fit_p_fit = np.array([np.nan for i in fit_p_init])
            err = np.array([[np.nan for i in fit_p_init] for j in fit_p_init])
            raise Exception(RuntimeError)

        if plot:
            # Just use bokeh since we don't want to publish this plot
            fig = bp.figure(title='Fit', plot_width=800, plot_height=400)
            if plot_init:
                # Plot initial parameter guess, fit and data
                fig.line(xsel, fitfunc(xsel, *fit_p_init), color=cc['g'],
                         legend='Init guess')

            fig.circle(xsel, ysel, color=cc['b'], legend='Data')
            fig.line(xsel, fitfunc(xsel, *fit_p_fit), color=cc['r'],
                     legend='Fit')
            bp.show(fig)

        # Save fitfunction as string
        import inspect
        self._fit_executed = True
        code = inspect.getsourcelines(fitfunc)[0]
        self._fit_function = fitfunc.__name__
        self._fit_function_code = ''.join(code)
        self._fit_parameters = fit_p_fit
        self._fit_par_errors = np.sqrt(np.diag(err))
        # Chi squared
553
554
555
        self._fit_data_error = (
                np.sum((fitfunc(xsel, *fit_p_fit) - ysel) ** 2) /
                (len(xsel) - 2))
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
        self._fit_labels = labels

        if plot_params:
            print(self.fit_pars())

        return fit_p_fit, self._fit_par_errors, self._fit_data_error

    def fit_func(self, x=None):
        """Calculates values of fit function for an x-array/values.

        Parameters
        -----------
        x : None, float, list, np.array
            X values. None means same x data as datamodule.

        ToDo
        -----
        Would like to rename the function to calc_fitfunc(self, x=None)
        """
        if not self._fit_executed:
            print('No fit was executed on this data')
            return

        exec(self._fit_function_code)
        possibles = globals().copy()
        possibles.update(locals())
        fitfunc = possibles.get(self._fit_function)
        if not fitfunc:
            raise Exception('Method %s not implemented' % self._fit_function)

        if x is None:
            return fitfunc(self.x, *self._fit_parameters)
        else:
            return fitfunc(x, *self._fit_parameters)

    def localmin(self, min_threshold=None, npoints=1, mode='clip'):
        """Obtain all the local minimas

        Parameters
        -----------
        min_threshold : float
            Only consider minima below this value
        npoints : int
            How many points on each side to use for the comparison.
        mode : str
            'clip' (def) or 'wrap'. If wrap is used, the data will considered
            periodic-like

        Returns
        --------
        np.array
            x and y values of local minima
        """
        xsel = self.x
        ysel = self.y

        if min_threshold is not None:
            msk = ysel <= min_threshold
            xsel = xsel[msk]
            ysel = ysel[msk]

        min_idx = sp_sig.argrelextrema(ysel, np.less, order=npoints, mode=mode)
        return np.vstack((xsel[min_idx], ysel[min_idx]))

    def localmax(self, max_threshold=None, npoints=1, mode='clip'):
        """Obtain all the local maxima

        Parameters
        -----------
        min_threshold : float
            Only consider maxima above this value
        npoints : int
            How many points on each side to use for the comparison.
        mode : str
            'clip' (def) or 'wrap'. If wrap is used, the data will considered
            periodic-like

        Returns
        --------
        np.array
            x and y values of local maxima
        """
        xsel = self.x
        ysel = self.y

        if max_threshold is not None:
            msk = ysel >= max_threshold
            xsel = xsel[msk]
            ysel = ysel[msk]

        min_idx = sp_sig.argrelextrema(ysel, np.greater, order=npoints,
                                       mode=mode)
        return np.vstack((xsel[min_idx], ysel[min_idx]))

    def smooth(self, nnb=21, polyorder=2):
        """Smooth data using the Savitzky-Golay filter.

        Information
            https://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter

        This has the advantage over moving_average, that the bias of smaller
        local minima/maxima is removed.

        Note
        -----
        Saves the smoothed data as dm.y values. To unsmooth the data run
        `unsmooth()`

        Parameters
        -----------
        nnb : int
            Window length of filter
        polyorder : int
            Polynomial order for the fit
        """
        y_filtered = sp_sig.savgol_filter(self.df[self.name_y], nnb, polyorder)
        self.import_data([self.x, y_filtered],
                         [self.name_x, '{}_smoothed'.format(self.df.keys()[1])])

    def unsmooth(self):
        """Recover unsmoothened y data."""
        try:
            del self.df['{}_smoothed'.format(self.name_y)]
        except KeyError:
            pass

    def interp(self, xnew, kind='cubic'):
        """Interpolates data to new x values.

        Parameters
        -----------
        xnew : list, np.array
            New x array
        kind : str
            Kind of interpolation.
            Choose between 'linear', 'nearest', 'zero', 'slinear', 'quadratic',
            'cubic'

        Returns
        --------
        DataModule
            Returns a new datamodule.

        Example
        --------
            >>> d1 = dm.load_datamodule('foo.dm')
            >>> xnew = np.linspace(d1.x.min(), d1.x.max(), 100)
            >>> d2 = d1.interp(xnew)
        """
        f = sp_intp.interp1d(self.x, self.y, kind=kind)
Christian Schneider's avatar
Christian Schneider committed
706
        return data_table([xnew, f(xnew)], [self.name_x, self.name_y])
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

    def fit_pars(self):
        """Returns the fit parameters as pandas DataFrame."""

        if not self._fit_executed:
            print('No Fit found. Please run a fit first.')
            return

        df = pd.DataFrame([list(self._fit_parameters),
                           list(self._fit_par_errors)])
        df.index = ['Value', 'Error']
        if self._fit_labels is not None:
            df.columns = self._fit_labels

        return df.T

    def y_value(self, x):
        """ Returns y value for given x array or value using linear
        interpolation.

        Parameters
        ----------
        x : list, np.array, float
            x value(s)

        Returns
        --------
        list, np.array, float
            Interpolated y value for given x value(s)
        """
        return np.interp(x, self.x, self.y)