Coverage for ana/signalanalyzer.py : 74%
Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# SPDX-FileCopyrightText: 2020 Jonathan Pieper <jpieper@stud.uni-frankfurt.de>
2#
3# SPDX-License-Identifier: GPL-3.0-or-later
5"""
6================
7SA
8================
10Evaluate data from signal analyzer.
11"""
13from .single import SingleM
15import logging
16import numpy as np
17import pandas as pd
18import scipy.stats
20import matplotlib.pyplot as plt
23class SA(SingleM):
24 """Loads and analyzes datafiles from :instrument:`SR785`"""
25 def __init__(self, *args, **kwargs):
26 """
27 Args:
28 *args:
29 **kwargs:
31 Returns:
32 None
34 Raises:
35 * ValueError
36 """
37 super().__init__()
38 self.logger = logging.getLogger('SA')
39 self.name = 'SA'
40 try:
41 self.data = kwargs.get('data', args[0])
42 except Exception:
43 error_message = "Not Able to find DataFrame. Please use SA_measurement(data)."
44 self.logger.critical(error_message)
45 raise ValueError(error_message)
47 if isinstance(self.data, dict):
48 self.df = self.data.get('data')
49 self.info = self.data.get('info')
50 else:
51 self.df = self.data
53 # Convert data to numeric values
54 try:
55 self.df.f = pd.to_numeric(self.df.f, errors='coerce')
56 self.df.Vx = pd.to_numeric(self.df.Vx, errors='coerce')
57 self.df.Vy = pd.to_numeric(self.df.Vy, errors='coerce')
58 except Exception:
59 error_message = "Unable to convert data to numeric."
60 self.logger.critical(error_message)
61 raise ValueError(error_message)
63 # Redirect functions
64 self._draw_oneoverf = self.style.draw_oneoverf
65 self._set_plot_settings = self.style.set_plot_settings
66 self._calc_log = self.calc_log
68 def __repr__(self):
69 ret = 'SA Measurement (Nr. %s)\n' % self.info.get('Nr', 0)
70 for key, val in self.info.items():
71 ret += '%s:\t%s\n' % (key, val)
72 return ret
75 def plot(self, **kwargs):
76 """Plotting the Data on given Axis or creating a new Plot for plotting.
78 .. code-block:: python
79 :linenos:
80 :caption: Signature
82 plot(ax, label=None, color=None, linestyle=None,
83 plot_x='f', plot_y='Vx', dont_set_plot_settings=False,
85 xscale='log', yscale='log', xlim=(None, None), ylim=(None,
86 None), legend_location='best', grid=None, title=None,
87 xlabel='f [Hz]', ylabel='S_VH [V2/Hz]',
89 )
91 Args:
92 **kwargs:
94 Note:
95 If **dont_set_plot_settings** is True, all kwargs below are not
96 used.
97 """
98 ax = kwargs.get('ax')
99 if not ax:
100 fig, ax = plt.subplots()
102 plotargs = {}
103 if 'label' in kwargs:
104 plotargs['label'] = kwargs.get('label')
105 if 'color' in kwargs:
106 plotargs['color'] = kwargs.get('color')
107 if 'linestyle' in kwargs:
108 plotargs['linestyle'] = kwargs.get('linestyle')
110 ax.plot(self.df[kwargs.get('plot_x', 'f')],
111 self.df[kwargs.get('plot_y', 'Vx')],
112 **plotargs)
114 if not (kwargs.get('dont_set_plot_settings', False)):
115 self._set_plot_settings(**kwargs)
117 def fit(self, fit_range=(1e-2, 1e0)):
118 """Fits a linear regression
120 Args:
121 fit_range (tuple, optional, default: (1e-2, 1e0).):
122 """
123 self.calc_log(self.df, ['f', 'Vx', 'Vy'])
124 xmin, xmax = fit_range
126 fit_area = self.df[self.df['f'] < xmax]
127 fit_area = fit_area[fit_area.f > xmin]
128 f = scipy.stats.linregress(fit_area.lnf, fit_area.lnVx)
130 self.info['Slope'] = f.slope
131 self.info['Intercept'] = f.intercept
132 return f.intercept, f.slope