data_table.py 24.1 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
13
import holoviews as hv
import holoviews.operation.datashader as hd
14
15
16
import numpy as np
import matplotlib.pyplot as plt
import bokeh.plotting as bp
17
from bokeh.models import HoverTool
18
19
20
21
import scipy.optimize as sp_opt
import scipy.signal as sp_sig
import scipy.interpolate as sp_intp
from collections import OrderedDict
22

23
24
hv.extension('bokeh')

25
26
27
28
29
30
31
32
33
34

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, ...]
35
36
37
    data_names : list, array, np.array
        Labels for the data. Format should be
        ['Label first axis', 'Label second axis', ...]
38
39
    """

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

48
49
50
51
        # Replace default names by the names given
        if data_names:
            for idx in range(len(data_names)):
                if data_names[idx]:
52
                    df_names[idx] = data_names[idx]
53

54
        # Create dictionary for pandas dataframe
55
56
        tmp_dict = {}
        for idx, d in enumerate(data_arrays):
57
58
            tmp_dict[df_names[idx]] = data_arrays[idx]

59
        # Create dataframe
60
61
        self.df = pd.DataFrame(data=tmp_dict)

62
63
64
65
66
67
68
69
        # 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

70
71
72
        # Order dataframe
        self.df = self.df[df_names]

73
74
75
76
77
    def _repr_html_(self):
        """Show pandas dataframe as default representation"""
        return '<h3>data_table</h3>' + self.df.head().to_html()

    def return_x(self):
78
        return np.array(self.df[self.name_x])
79
80
81
82
83

    def return_y(self):
        if '{}_smoothed'.format(self.name_y) in self.df.keys():
            # Return smoothed data
            name = '{}_smoothed'.format(self.name_y)
84
            return np.array(self.df[name])
85
        else:
86
            return np.array(self.df[self.name_y])
87
88
89
90
91
92
93

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

    @x.setter
    def x(self, value):
94
        if len(value) != len(self.x):
95
            self.df = self.df.reindex(range(len(value)))
96
        self.df[self.name_x] = value
97
98
99
100
101
102
103

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

    @y.setter
    def y(self, value):
104
        self.df[self.name_y] = value
105
106
107
108
109
110
111
112
113
114
115

    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

116
117
118
    def rename(self, column_name, new_column_name):
        self.df = self.df.rename(column={column_name: new_column_name})

119
120
121
122
123
124
125
126
127
128
129
130
131
    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)

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

149
        # Check if column/dependent variable already exists, if not --> create
150
151
        for idx, d_name in zip(range(1, len(order_names) + 1),
                               order_names[1:]):
152
153
            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
154
155
                    # Quick check: If independent variable is the same as
                    # already given, just add new column
156
157
158
159
160
161
162
163
164
165
166
167
                    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
168
                for i in range(1, len(data_arrays)):
169
170
171
                    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
172
                        self.df[order_names[i]][df_idx] += data_arrays[i][idx]
173
174
175
                        self.df[order_names[i]][df_idx] /= 2
                    else:
                        # Else just take new value
176
                        self.df[order_names[i]][df_idx] = data_arrays[i][idx]
177
            else:
178
                self.df = self.df.append({key: value[idx] for key, value
179
                                          in zip(order_names, data_arrays)},
180
                                         ignore_index=True)
181
                pass
182
183

    def plot_hv(self, x=None, y=None, height=400, width=800,
184
                title='', color=None):
185
186
187
188
189
190
191
192
193
194
195
196
        """Plot table with Holoviews

        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
197
198
199
200
        title : str
            Title of plot
        color : str
            Color for plot
201
202
        """
        if x is None:
203
            x_val = self.name_x
204
        else:
205
            x_val = x
206
207

        if y is None:
208
            y_val = self.name_y
209
        else:
210
            y_val = y
211

212
213
214
215
        if color is None:
            color = color_scheme[0]
        elif color in cc.keys():
            color = cc[color]
216

217
218
219
        # Plot
        s = hv.Scatter(self.df, x_val, y_val, label=title)
        scatter_plots = hd.dynspread(hd.datashade(hv.Curve(s), cmap=[color]))
220
221
222

        return scatter_plots.opts(plot=dict(height=height, width=width,
                                            show_grid=True))
223

224
    # Plotting #################################################################
Christian Schneider's avatar
Christian Schneider committed
225
226
    def plot(self, style='-o', x_col=None, y_col=None, color=None, xscale=1,
             yscale=1,
227
             plot_fit=True, linewidth=1.5, markersize=3,
228
229
             fit_linewidth=1, plot_errors=True, legend=None,
             legend_pos=0, engine=None, title='', show=True, fig=None,
230
231
232
233
234
235
236
237
238
239
             fitcolor='r', fit_on_top=False, **kwargs):
        """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
240
241
242
243
244
245
        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
246
247
        color : str
            Color shortcut (eg. 'b') or specific color like '#123456'.
Christian Schneider's avatar
Christian Schneider committed
248
            Type cc to see available colors.
249
250
251
252
253
254
255
256
257
258
259
260
        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
261
        plot_errors : bool
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
            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

        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.
        """
289
        # Get default data or specified columns
Christian Schneider's avatar
Christian Schneider committed
290
291
292
        if x_col is None:
            x_col = self.name_x
        if y_col is None:
Christian Schneider's avatar
Christian Schneider committed
293
294
295
296
            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
297

298
299
        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]
300
301
302
303
304
305
306

        # 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320

        # 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)

321
322
323
324
325
326
327
328
329
        # 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

330
331
        # Bokeh
        if engine in ['bokeh', 'b']:
332
333
334
335
            # Create Figure if no figure is given
            if fig is None:
                tools = ['box_zoom', 'pan', 'wheel_zoom', 'reset',
                         'save', 'hover']
336
337
                fig = bp.figure(plot_width=800, plot_height=400, tools=tools,
                                toolbar_location='above', title=title)
338
339
340
341
342
343

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

            # Plot Data
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
            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)
366

367
            # Plot Fit
368
            if plot_fit and self._fit_executed:
Christian Schneider's avatar
Christian Schneider committed
369
370
371
372
373
374
                # Get color
                if fitcolor in color_labels:
                    fc = cc[fitcolor]
                else:
                    fc = fitcolor
                # Plot fit
375
                fig.line(x * xscale, fitfunc(x, *self._fit_parameters) * yscale,
Christian Schneider's avatar
Christian Schneider committed
376
                         line_color=fc, line_width=fit_linewidth)
377
378

            # Format nicer HoverTool
Christian Schneider's avatar
Christian Schneider committed
379
            tooltips = [(x_col, "$x"), (y_col, "$y")]
380
381
382
            fig.select(dict(type=HoverTool)).tooltips = OrderedDict(tooltips)

            # Add labels
Christian Schneider's avatar
Christian Schneider committed
383
384
            fig.xaxis.axis_label = x_col
            fig.yaxis.axis_label = y_col
385
386
387
388
389
390
391

            if show:
                bp.show(fig)
            return fig

        # Matplotlib
        elif engine in ['pyplot', 'p']:
Christian Schneider's avatar
Christian Schneider committed
392
393
394
395
396
            if not fig:
                try:
                    fig = plt.gcf()
                except:
                    fig = plt.figure()
397

Christian Schneider's avatar
Christian Schneider committed
398
            plt.title(title)
399
            # Plot errors
Christian Schneider's avatar
Christian Schneider committed
400
            # Data
401
            if (plot_errors and "{} Errors".format(self.name_y) in
402
                    self.df.keys()):
403
                yerrs = np.array(self.df[self.name_y + ' Errors'][
404
405
                                 self.idx_min:self.idx_max]) * yscale
                plt.errorbar(x * xscale, y * yscale, fmt=style, color=c,
Christian Schneider's avatar
Christian Schneider committed
406
                             yerr=yerrs, markersize=markersize, **kwargs)
407

Christian Schneider's avatar
Christian Schneider committed
408
            else:
409
                plt.plot(x * xscale, y * yscale, style, color=c,
Christian Schneider's avatar
Christian Schneider committed
410
411
                         linewidth=linewidth, markersize=markersize,
                         **kwargs)
412

Christian Schneider's avatar
Christian Schneider committed
413
            # Fit
414
415
            if plot_fit and self._fit_executed:
                if not fit_on_top:
416
                    fit_zorder = 0
417
                else:
418
419
                    fit_zorder = 99
                plt.plot(x * xscale, fitfunc(x, *self._fit_parameters) * yscale,
420
421
422
                         '-', color=fitcolor, linewidth=fit_linewidth,
                         zorder=fit_zorder)

423
            # Labels
Christian Schneider's avatar
Christian Schneider committed
424
425
            plt.xlabel(x_col)
            plt.ylabel(y_col)
426
427
            # Styling
            plt.grid()
428
            plt.xlim([x[0] * xscale, x[-1] * xscale])
429

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

433
    def plot_all(self, colormap=None):
434
435
436
437
438
439
440
441
442
443
444
        """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]:
445
446
447
448
                                         hv.Points([[self.x[0],
                                                     self.df[cols[i]][0]]],
                                                   label=str(cols[i]))
                                    .opts(style=dict(color=colormap[i]))
449
450
451
452
453
                                     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
454
455

    def fit(self, fitfunc, fit_p_init, plot=True, plot_init=True,
456
            plot_params=True, labels=None, **kwargs):
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
        """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.
479
480
        plot_params : bool
            Print paramaters for fit
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
        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

        """
        xsel, ysel = self.x, self.y
        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
529
530
531
        self._fit_data_error = (
                np.sum((fitfunc(xsel, *fit_p_fit) - ysel) ** 2) /
                (len(xsel) - 2))
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
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
        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
682
        return data_table([xnew, f(xnew)], [self.name_x, self.name_y])
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713

    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)