measpy package
measpy.audio module
- measpy.audio.audio_get_devices()
Returns a list of audio devices present in the system
- measpy.audio.audio_run_measurement(M)
Runs a measurement defined in the object of the class measpy.measurement.Measurement given as argument.
Once the data acquisition process is terminated, the measurement object given in argument contains a property in_sig consisting of a list of signals.
- Parameters:
M (measpy.measurement.Measurement) – The measurement object that defines the measurement properties
- Returns:
Nothing, the measurement passed as argument is modified in place.
- measpy.audio.audio_run_synced_measurement(M, in_chan=0, out_chan=0)
Before running a measurement, one second of silence is added at the begining and end of the selected output channel. The measurement is then run, and the time lag between a selected acquired signal and the output signal is computed from cross-correlation calculation. All the acquired signals are then re-synced from the time lag value.
- Parameters:
M (measpy.measurement.Measurement) – The measurement object
out_chan (int) – The selected output channel for synchronization. It is the index of the selected output signal in the list
M.out_sig
in_chan (int) – The selected input channel for synchronization. It is the index of the selected input signal in the list
M.in_sig
measpy.measurement module
- class measpy.measurement.Measurement(**params)
Bases:
object
- classmethod from_dir(dirname)
Load a measurement object from a directory
- Parameters:
dirname (str) – Name of the directory
- classmethod from_hdf5(filename)
- load_h5data()
- sync_prepare(out_chan=0, added_samples=None)
Prepare measurement for synchronization
- Parameters:
out_chan (int) – The selected output channel for synchronization. It is the index of the selected output signal in the list
M.out_sig
in_chan (int) – The selected input channel for synchronization. It is the index of the selected input signal in the list
M.in_sig
added_time (float) – Duration of silence added before and after the selected output signal
- sync_render(out_chan=0, in_chan=0, added_samples=None)
- to_dir(dirname)
Stores the parameters and signals in a directory
- Parameters:
dirname (str) – Name of the directory, a (1), (2)… is added to the name if directory exists
- Returns:
Actual name to the saved folder (if name conflit is detected)
- Return type:
str
- to_hdf5(filename)
Save Measurement in hdf5 file
- Parameters:
filename (str) – hdf5 file
measpy.ni module
- class measpy.ni.ni_callback_measurement(M)
Bases:
object
Measurment using a callback function called when specified number of sample is written from the device to the buffer. Using nidaqmx.Task.register_every_n_samples_acquired_into_buffer_event
- reset_callback(callback_method, n_values)
- run(stop=<threading.Event at 0x7f69d16d1e50: unset>, duration='default')
Run the measurment :param stop: Trigger to stop the measurment, defaults to Event() :type stop: threading.Event, optional :param duration: Duration of measurment in seconds if default it use the duration in M, defaults to “default” :type duration: float, optional :return: Nothing
- set_callback(callback_method, n_values)
Create the buffer containing n_values and set the callback that read and use the data using the custom ‘callback_method’, it is called every ‘n_values’ written into buffer. :param callback_method: Method with 2 arguments, the buffer and buffer lenght :type callback_method: callable :param n_values: Number of datapoint read each call :type n_values: int :return: Nothing
- stop()
- measpy.ni.ni_get_devices()
Get the list of NI devices present in the system
- Returns:
A list of devices object
- measpy.ni.ni_run_measurement(M, filename=None, duration='default')
Runs a measurement defined in the object of the class measpy.measurement.Measurement given as argument.
Run callback at refresh_rate with data acquired
Once the data acquisition process is terminated, the measurement object given in argument contains a property in_sig consisting of a list of signals.
- Parameters:
M (measpy.measurement.Measurement) – The measurement object that defines the measurement properties
filename (str or Path, optional) – .h5 filename to direct write on disk, defaults to None
duration (float, optional) – optional duration in second, take value in M is default, defaults to “default”
- Returns:
Nothing, the measurement passed as argument is modified in place.
- measpy.ni.ni_run_synced_measurement(M, in_chan=0, out_chan=0)
Before running a measurement, added_time second of silence is added at the begining and end of the selected output channel. The measurement is then run, and the time lag between a selected acquired signal and the output signal is computed from cross-correlation calculation. All the acquired signals are then re-synced from the time lag value.
- Parameters:
M (measpy.measurement.Measurement) – The measurement object
out_chan (int) – The selected output channel for synchronization. It is the index of the selected output signal in the list
M.out_sig
in_chan (int) – The selected input channel for synchronization. It is the index of the selected input signal in the list
M.in_sig
added_time (float) – Duration of silence added before and after the selected output signal
- Returns:
Measured delay between i/o sync channels
- Return type:
float
measpy.pico module
- measpy.pico.Fill_Signal_Queue(Sig, q_in, unit_in='mV', Ndata=None)
- class measpy.pico.Pico_thread(M, output_queue=None, pre_process=picosdk.functions.adc2mV, save_into_Signal=True, min_chunksize_processed=0, filename=None, buffersize=20000, max_samples=100000, serial=None, stop_event=<threading.Event at 0x7f69d10d4d50: unset>)
Bases:
ABC
,Thread
- This needs M to contain the following properties:
- in_rangea list of strings specifying the voltage range.
Possible voltage ranges are “10MV”, “20MV”, “50MV”, “100MV”, “200MV”, “500MV”, “1V”, “2V”, “5V”, “10V”, “20V”, “50V”, “100V”
upsampling_factor : upsampling factor
- in_couplingCoupling configuration of the channels.
Can be “ac” or “dc”
- Channels = {}
- Data_type = {}
- channel_name = {}
- channels_setup()
- abstractmethod close_unit()
Close picoscope
- dataqueue = <queue.Queue object>
- dbfs_save()
save h5file with dbfs according to channel parameter :return: None :rtype: None
- methods_setup()
- abstractmethod open_unit()
Open picoscope
- abstractmethod static pico_range(prange)
Picoscope voltage range (mapped from picoscope lib) This property should be overridden, used by dbfs_save
- run()
self.start() run this into a thread
- abstractmethod setup_callback()
Setup the callback method to read data. should return the callback metod used to read and put data into dataqueue
- abstractmethod setup_channel(chan_index)
setup a channel.
should define channel status (used or not), channel coupling(ac or dc), channel range and channel data buffer.
- setup_preprocess()
- setup_threads()
- abstractmethod start_measurment()
Run the scope.
- measpy.pico.Queue2array(q_in)
- measpy.pico.Queue2prealocated_array(q_in, array)
- measpy.pico.convert_to_mutichannel(listSig)
- measpy.pico.detect_rising_pulses_threshold_ind(values, threshold, ind0, previous_data_point)
Detect rising pulse using a threshold
- Parameters:
values (List) – Data.
ind0 (int) – indice of the first data point.
previous_data_point (number) – Value of the last data point (indice = ind0-1). useful to not lose the peak at ind0
threshold (int) – threshold (in adc values).
- Returns:
List of indices where a rising pulse is detected.
- Return type:
List
- measpy.pico.dispatch(q_in, qs_out)
- measpy.pico.findindex(l, e)
- measpy.pico.ps2000_plot(M, plotting_class, plotbuffersize=20000, updatetime=0.1, serial=None, **kwargs)
- measpy.pico.ps2000_pulse_detection(M, serial=None, min_chunksize_processed=10000, **kwargs)
- This function needs M to contain the property
in_threshold : a list of threshold for pulse height (in Volt) for each channel
- measpy.pico.ps2000_run_measurement(M, serial=None, filename=None, **kwargs)
- measpy.pico.ps4000_plot(M, plotting_class, plotbuffersize=20000, updatetime=0.1, serial=None, **kwargs)
- measpy.pico.ps4000_pulse_detection(M, serial=None, min_chunksize_processed=10000, **kwargs)
- This function needs M to contain the property
in_threshold : a list of threshold for pulse height (in Volt) for each channel
- measpy.pico.ps4000_run_measurement(M, serial=None, filename=None, **kwargs)
- measpy.pico.transposelist(L)
measpy.signal module
- class measpy.signal.Signal(**kwargs)
Bases:
object
Signal definition class
The class signal encapsulates all the data describing the data acquisition of a physical signal:
the actual data as a numpy array (
_rawvalues
)the sampling frequency (
fs
)a descriptor string (
desc
)the physical unit (
unit
, optional, dimensionless if not specified)the calibration information, that allows to convert the data in volts to the actual physical unit (
cal
, optional, unitary if not specified)an additionnal conversion factor used if the acquired data is proportionnal but not equal to the actual volts going into the AD converted, typically for soundcards (
dbfs
, optional, unitary if not specified)start time of the signal (
t0
) : the actual time of the first sampleany additionnal user property (string, float, int)
The class defines methods for signal processing, saving, restoring the data, plotting, etc. Most of the signal processing methods internally call numpy/scipy functions.
Examples of signal creation:
An empty signal of unit Pascals, and sampling frequency 48kHz :
import measpy as mp pa = mp.Signal(fs=48000, unit='Pa')
A signal of unit Pascals, and sampling frequency 48kHz, filled with 1000 random values, followed by a plot:
import measpy as mp import numpy as np pa = mp.Signal(fs=48000, unit='Pa', values=np.random.rand(1000)) pa.plot()
To generate some standard signals, there are some classical waveform creation methods. For example a five seconds logarithmic sweep from 20Hz to 20kHz, of dimension volts:
import measpy as mp pa = mp.Signal.log_sweep(freq_min=20,freq_max=20,dur=5,unit='V) pa.plot()
Other examples and tutorials are found in the example folder of measpy project.
At creation, the following parameters can be given (transmitted to the __init__ function of the class Signal):
- Parameters:
desc (str, optional) – Description of the signal, defaults to ‘A signal’
fs (float, optional) – Sampling frequency, defaults to 1
unit (str or None, optional) – Unit of the signal given as a string that unyt can understand, defaults to None
cal (float, optional) – calibration in V/unit, defaults to 1.0
dbfs (float, optional) – dbfs of the input data acquisition card, defaults to 1.0
raw (1D numpy array, optional) – raw data of the signal, defaults to array(None)
volts (1D numpy array, optional) – data of the signal given in volts
values (1D numpy array, optional) – data of the signal givent in its physical units
any – Any other parameter can be given. They are stored as a new property for a user-personalized use. For instance, the log_sweep creation method introduced above stores the low and high frequencies in the properties freq_min and freq_max, as it can be useful to keep track of these values for later signal processing.
Some defined properties are calculated on demand when called. For instance, the duration of the signal depends on the number of samples and sampling frequency.
import measpy as mp pa = mp.Signal(fs=48000, unit='Pa', values=np.random.rand(1000)) # show duration print(pa.dur) # show the corresponding time vector (numpy array) print(pa.time)
The following properties are implemented:
values (values expressed in unit, calibrations applied)
volts (only dbfs applied)
raw (same as _rawvalues)
length (data length)
dur (duration in seconds)
time (time array)
max, min : max value, min value
tmax, tmin : time at max or min value
rms : Root mean square of the signal
- abs()
Absolute value
- Returns:
Another signal with the absolute values
- Return type:
- add_silence(**kwargs)
Add zeros at the begining and the end of the signal
- Parameters:
extrat (tuple, optional) – time in seconds before and after the original signal, defaults to [0,0]
extras (tuple, optional) – number of samples before and after the original signal, defaults to [0,0]
- Returns:
New signal
- Return type:
- angle(unwrap=True)
Compute the angle of the signal, if complex
- Parameters:
unwrap (bool) – If True, the angle data is unwrapped
- Returns:
The angle part of the signal, unit=rad
- Return type:
measpy.signal
- apply_calibrations()
Returns the same signal with all calibrations applied and cal=1.0, dfbs=1.0
- as_raw()
Returns the signal raw values, dimensionless, no calibration applied, no dbfs applied.
- Returns:
A signal
- Return type:
- as_volts()
Returns the signal in volts, no calibration applied.
- Returns:
A signal
- Return type:
- property cal
cal property the calibration data (a value, tuple of values or a string function)
- coh(x, **kwargs)
Compute the coherence between signal x and the actual signal
- Parameters:
x (measpy.signal.Signal) – Other signal to compute the coherence with
window (str, optional) – Window function type, default ‘hann’
nperseg (int, optional) – Length of each segment. Defaults to the power of two closest to one second duration, so that the frequency spacing is approx. 1Hz.
noverlap – Number of points to overlap between segments. If None, noverlap = nperseg // 2. Defaults to None.
nfft (int or None, optional) – Length of the FFT used, if a zero padded FFT is desired. If None, the FFT length is nperseg. Defaults to None.
detrend (str or function or False, optional) – Specifies how to detrend each segment. If detrend is a string, it is passed as the type argument to the detrend function. If it is a function, it takes a segment and returns a detrended segment. If detrend is False, no detrending is done. Defaults to ‘constant’.
return_onesided (bool, optional) – If True, return a one-sided spectrum for real data. If False return a two-sided spectrum. Defaults to True, but for complex data, a two-sided spectrum is always returned. Defaults to True.
scaling (str, optional) – Selects between computing the power spectral density (‘density’) where Pxx has units of V**2/Hz and computing the power spectrum (‘spectrum’) where Pxx has units of V**2, if x is measured in V and fs is measured in Hz. Defaults to ‘density’
average (str, optional) – Method to use when averaging periodograms. Defaults to ‘mean’.
- Returns:
A Spectral object
- convolve(other, **kwargs)
Convolution of two signals
Optional arguments are that of the scipy.signal.convolve function.
- Parameters:
other (meapsy.signal.Signal) – Other signal to convolve with
mode (str, {'full', 'valid', 'same'}) – A tring indicating the size of the output. Optional. See scipy docs for details
method (str {'auto', 'direct', 'fft'}) – A string indicating which method to use to calculate the convolution. Optional. See scipy docs for details
- Returns:
A signal representing the linear convolution of the two signals.
- Return type:
- corr(x, **kwargs)
Compute the cross correlation between signal x and the actual signal
- Parameters:
x (measpy.signal.Signal) – Other signal to compute the coherence with
- Returns:
A signal representing the cross-correlation
- Return type:
- cut(**kwargs)
Cut signal between positions.
- Parameters:
pos (tuple of int, optional) – Start and stop positions of the new signal, given as indices, defaults to (0,-1)
dur (tuple of float, optional) – Start and stop positions of the new signal, given as time values
- Returns:
Faded signal
- Return type:
pos and dur cannot be both specified. An exception is raised in that case.
Negative values are possible, as well as values beyond the end of the signal. The signal is looped in that case.
pos[1] can be lower that pos[0], in that case, the signal is reversed.
NOTE : cut ignores the timeshift _t0 property
- dB(ref)
Computes 20*log10(self.values/ref) ref is for instance a pressure or volage reference that has to be of same units as the signal.
- Parameters:
ref (unyt.array.unyt_quantity) – Reference quantity that has to be of same dimension
- Returns:
A signal of dimension dB
- Return type:
- dB_SPL()
Computes 20*log10(self.values/PREF). PREF is the reference pressure in air (20e-6 Pa)
- Returns:
Signal of unit dB
- Return type:
- dB_SVL()
Computes 20*log10(self.values/VREF). VREF is the reference particle velocity (5e-8 m/s)
- Returns:
Signal of unit dB
- Return type:
- property dbfs
dbfs properties specifies the ratio between voltage signal and actual recorded signal
- delay(dt)
Returns a delayed signal by dt. The data arrays are not changed. Instead dt is added to the property t0.
- Parameters:
dt (float) – Delay time
- Returns:
The delayed signal
- Return type:
- diff()
Compute time derivative
- Returns:
Time derivative of signal (unit/s)
- Return type:
- property dur
Duration of the signal
- fade(fades)
Apply fades at the begining and the end of the signal
- Parameters:
fades ((int,int)) – Tuple of ints specifying the fade in and fade out lengths
- Returns:
Faded signal
- Return type:
- fft(norm='backward')
FFT of the signal. Returns a Spectral object. Unit is preserved during the process.
- classmethod from_csvwav(filename, **kwargs)
Load a signal from a pair of csv and wav files
- Parameters:
filename (str) – base file name
convert_to_fp (bool) – If True, the eventual integer data is converted to floats in the range [-1.0, 1.0], defaults to True.
- Returns:
The loaded signal
- Return type:
- classmethod from_hdf5(hdf5_object, dataset_name='')
Load Signal from hdf5 object (file or dataset)
- Parameters:
hdf5_object (str,Path or opened h5file handle) – File or dataset from opened hdf5 file
chan (int) – channel if there are more than one dataset in the file. Optional, defaults to 1.
- Returns:
The loaded signal
- Return type:
- classmethod from_wav(filename, **kwargs)
Load a signal from a wav file
- Parameters:
filename (str) – base file name
convert_to_fp (bool) – If True, the eventual integer data is converted to floats in the range [-1.0, 1.0], defaults to True.
desc (float) – Description of the generated signal, defaults to filename
unit – Unit of the generated signal, defaults to None
cal – Calibration of the generated signal, defaults to None
dbfs – dBFS value of the generated signal, defaults to None
- Returns:
The loaded signal
- Return type:
- harmonic_disto(nh=4, freq_min=20.0, freq_max=20000.0, delay=None, win_max_length=32768, prop_before=0.25, nsmooth=24, debug_plot=False)
Compute the harmonic distorsion of an in/out system using the method proposed by Farina (2000) and adapted by Novak et al. (2015) to correctly estimate the phase of the higher harmonics.
The signal object (
`self`
) is the response of a nonlinear system to a logarithmic sweep created with the`Signal.log_sweep`
method.- Parameters:
nh (int, optional) – number of harmonics, including harmonic 0 (the linear part of the response), defaults to 4
freqs (tuple, optional) – frequencies between which the output signal that was used sweeps, defaults to [20,20000]
delay (float, optional) – the mean delay between output and input, defaults to None. If None, the delay is estimated looking at the max value of the cross correlation of the signal with the input logarithmic sweep.
win_max_length – Maximum window length for each harmonic Fourier analysis in number of samples. Has to be even. Defaults to 2**15. When treating higher harmonics, the window can be shortened so that there is no overlapping with the next window.
prop_before (float, optionnal) – Proportion of the window that is before the peak center for each harmonic content. Defaults to 0.25 (1/4th of the window is before the harmonic peak)
nsmooth (int) – Parameter for 1/nsmooth smoothing before Weighting conversion, defaults to 12
debug_plot (bool) – Specifies if debugging plots are shown during the process, defaults to False
- Returns:
A four element tuple containing: - A dictionary of Spectral objects representing the different harmonics as function of the frequency, not frequency aligned - A dictionnary of Spectral objects, representing the different harmonics, smoothed and frequency aligned - The total harmonic distortion (THD) (Spectral object) - The delay between output (sent signal) and input (measure signal)
- Return type:
tuple
- hilbert()
Computes the hilbert transform of a signal Warning: This method the imaginary part of the hilbert function of the scipy module.
- Returns:
A signal
- Return type:
- hilbert_ana()
Computes the analytical signal through hilbert transform of a signal Note: This method is exactly the hilbert function of the scipy module.
- Returns:
A signal
- Return type:
- iir(N=2, Wn=(20, 20000), rp=None, rs=None, btype='band', ftype='butter')
Infinite impulse response filter of a signal.
The signal is filtered accordingly to the parameters. This method is a wrapper around the scipy.signal iir functions, most of the parameters are hence the same.
- Parameters:
N (int, optional) – Filter order, defaults to 2
Wn (tuple, optional) – a cutoff frequency (if low or highpass) or a tuple of frequency (if bandpass/stop), defaults to (20,20000)
rp (float, optional) – For Chebyshev and elliptic filters, provides the maximum ripple in the passband. (dB)
rs (float, optional) – For Chebyshev and elliptic filters, provides the minimum attenuation in the stop band. (dB)
btype (str in {'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional) – Type of filter (band, hp, lp), defaults to ‘band’
ftype (str, optional) – Type of filter (butter, elliptic, etc.), defaults to ‘butter’
- Returns:
A filtered signal
- Return type:
- imag()
Imaginary part of the signal, calibrations applied
- Returns:
The imaginary part of the signal
- Return type:
- property invcal
invcal property the calibration data
- property length
Length of the signal (number of samples)
- classmethod log_sweep(fs=44100, dur=2.0, amp=1.0, freq_min=20.0, freq_max=20000.0, unit=None, cal=None, dbfs=None, desc=None)
ogarithmic sweep signal creation
- Parameters:
fs – Sampling frequency. Defaults to 44100.
dur – Duration in seconds. Defaults to 2.0.
amp – Amplitude. Defaults to 1.0.
freq_min – Start frequency. Defaults to 20.0.
freq_max – Stop frequency. Defaults to 20000.0.
unit – Unit of the generated signal. Defaults to None (->dimensionless)
cal – Calibration. Defaults to None (->1).
dbfs – Zero dB full scale value. Defaults to None (->1).
desc – Description of the generated signal. Defaults to None, so that the default description is ‘Logsweep freq_min-freq-max.
- Returns:
A sweep signal
- Return type:
- property max
Max value of a signal
- Returns:
Max value
- Return type:
unyt.array.unyt_quantity
- property mean
Mean value
- property min
Min value of a signal
- Returns:
Min value
- Return type:
unyt.array.unyt_quantity
- property nchannels
Number of channels
- classmethod noise(fs=44100, dur=2.0, amp=1.0, freq_min=20.0, freq_max=20000.0, unit=None, cal=None, dbfs=None, desc=None)
Logarithmic sweep signal creation
- Parameters:
fs – Sampling frequency. Defaults to 44100.
dur – Duration in seconds. Defaults to 2.0.
amp – Amplitude. Defaults to 1.0.
freq_min – Start frequency. Defaults to 20.0.
freq_max – Stop frequency. Defaults to 20000.0.
unit – Unit of the generated signal. Defaults to None (->dimensionless)
cal – Calibration. Defaults to None (->1).
dbfs – Zero dB full scale value. Defaults to None (->1).
desc – Description of the generated signal. Defaults to None, so that the default description is ‘Noise freq_min-freq-max.
- Returns:
A noise signal
- Return type:
- normalize()
Normalize a signal
- Returns:
Dimensionless normalized signal
- Return type:
- classmethod pack(sigs)
Pack signals in the form of a list of signals and return a multichannel signal
- pack_with(other)
Pack the signal with other signal
Signals must have compatible length and sampling frequencies. This method returns a new multichannel signal with values packed as columns. The other properties of the resulting signal are arranged as lists or numpy array if possible
- plot(ax=None, **kwargs)
Plot the signal with axes captions and labels. Except the axis specifier ax, all other optionnal arguments are passed to the matplotlib plot function.
- Parameters:
ax (matplotlib.axes._axes.Axes) – specifies an existing axis object to plot on. If not specified, a new one is created and returned
- Returns:
an axes object
- Return type:
matplotlib.axes._axes.Axes
- psd(**kwargs)
Compute power spectral density of the signal object Optional arguments are the same as the welch function in scipy.signal
Optional arguments are the same as scipy.welch()
- Parameters:
window (str, optional) – Window function type, default ‘hann’
nperseg (int, optional) – Length of each segment. Defaults to the power of two closest to one second duration, so that the frequency spacing is approx. 1Hz.
noverlap – Number of points to overlap between segments. If None, noverlap = nperseg // 2. Defaults to None.
nfft (int or None, optional) – Length of the FFT used, if a zero padded FFT is desired. If None, the FFT length is nperseg. Defaults to None.
detrend (str or function or False, optional) – Specifies how to detrend each segment. If detrend is a string, it is passed as the type argument to the detrend function. If it is a function, it takes a segment and returns a detrended segment. If detrend is False, no detrending is done. Defaults to ‘constant’.
return_onesided (bool, optional) – If True, return a one-sided spectrum for real data. If False return a two-sided spectrum. Defaults to True, but for complex data, a two-sided spectrum is always returned. Defaults to True.
scaling (str, optional) – Selects between computing the power spectral density (‘density’) where Pxx has units of V**2/Hz and computing the power spectrum (‘spectrum’) where Pxx has units of V**2, if x is measured in V and fs is measured in Hz. Defaults to ‘density’
average (str, optional) – Method to use when averaging periodograms. Defaults to ‘mean’.
- Returns:
A Spectral object containing the psd
- Return type:
- property raw
Raw values as 1D numpy array
- real()
Real part of the signal, calibrations applied
- Returns:
The real part of the signal
- Return type:
- resample(fs)
Changes sampling rate of the signal
- Parameters:
fs (float) – Desired sampling rate
- Returns:
A resampled signal
- Return type:
- rfft(norm='backward')
Real FFT of the signal. Returns a Spectral object. Unit is preserved during the process.
- property rms
Compute the RMS of the complete Signal
- Returns:
A quantity
- Return type:
unyt.Quantity
- rms_smooth(nperseg=512)
Compute the RMS of the Signal over windows of width nperseg samples
- Parameters:
nperseg (int, optionnal) – Window size, defaults to 512
- Returns:
A resampled signal
- Return type:
- classmethod saw(fs=44100, dur=2.0, amp=1.0, freq=1000.0, unit=None, cal=None, dbfs=None, desc=None)
- similar(**kwargs)
Returns a copy of the Signal object with properties changed as specified by the optional arguments.
- Parameters:
fs (int, optional) – Sampling frequency
desc (str, optional) – Description
unit (str, unyt.Unit, optional) – Signal unit
cal (float, optional) – Calibration in volts/unit
dbfs (float, optional) – Input voltage for raw value = 1
values (numpy.array, optional) – Signal values given in unit
volts (numpy.array, optional) – Signal values given in volts
raw (numpy.array, optional) – Signal values given as raw samples
t0 (float, optional) – Timeshift of the signal
any (float, int, string) – Any other parameter can be specified
- Returns:
A signal
- Return type:
Only one of the following parameters should be specifified : raw, volts, values If values is specified, the two others are not taken into account. If volts and raw are given, only volts is taken into account.
- classmethod sine(fs=44100, dur=2.0, amp=1.0, freq=1000.0, unit=None, cal=None, dbfs=None, desc=None)
- smooth(nperseg=512)
Compute the RMS of the Signal over windows of width nperseg samples
- Parameters:
nperseg (int, optionnal) – Window size, defaults to 512
- Returns:
A resampled signal
- Return type:
- spectrogram(ax=None, logy=False, dbvalue=False, **kwargs)
Spectrogram plot of a signal :param logy: Logarithmic y (frequency) scale :type logy: bool, optional, default to False :param dbvalue: Amplitude in db :type dbvalue: bool, optional, default to False :param ax: an axes object to plot on :type ax: axis type
Additionnal kwargs arguments are all passed scipy.signal.spectrogram function
- Returns:
an axes object
- Return type:
matplotlib.axes._axes.Axes
- property t0
Time shifting of the signal (reads the t0 value if it exists, else 0)
- tfe_farina(freqs, in_unit='V')
Compute the transfer function between x and the actual signal where x is was a logarithmic sweep of same duration between freqs[0] and freqs[1] (i.e. created with measpy.signal.Signal.log_sweep)
- Parameters:
freqs (Tuple of floats) – The start and stop frequencies of the input logarithmic sweep whose actual signal is the response
in_unit – Unit of the input signal. Defaults to ‘V’
- Returns:
The FRF calculated by the Farina’s method (2000)
- Return type:
- tfe_welch(x, **kwargs)
Compute transfer function between signal x and the actual signal. Optional parameters are the same as scipy.signal.csd or scipy.signal.welch
- Parameters:
x (measpy.signal.Signal) – Other signal from which the transfert function is computed
window (str, optional) – Window function type, default ‘hann’
nperseg (int, optional) – Length of each segment. Defaults to the power of two closest to one second duration, so that the frequency spacing is approx. 1Hz.
noverlap – Number of points to overlap between segments. If None, noverlap = nperseg // 2. Defaults to None.
nfft (int or None, optional) – Length of the FFT used, if a zero padded FFT is desired. If None, the FFT length is nperseg. Defaults to None.
detrend (str or function or False, optional) – Specifies how to detrend each segment. If detrend is a string, it is passed as the type argument to the detrend function. If it is a function, it takes a segment and returns a detrended segment. If detrend is False, no detrending is done. Defaults to ‘constant’.
return_onesided (bool, optional) – If True, return a one-sided spectrum for real data. If False return a two-sided spectrum. Defaults to True, but for complex data, a two-sided spectrum is always returned. Defaults to True.
scaling (str, optional) – Selects between computing the power spectral density (‘density’) where Pxx has units of V**2/Hz and computing the power spectrum (‘spectrum’) where Pxx has units of V**2, if x is measured in V and fs is measured in Hz. Defaults to ‘density’
average (str, optional) – Method to use when averaging periodograms. Defaults to ‘mean’.
- Returns:
A Spectral object
- property time
Time values of the signal as 1D numpy array
- timelag(x)
Estimate the time delay between two correlated signals, by computing the time at maximum cross-correlation between the two signals.
- Parameters:
x (measpy.signal.Signal) – Other signal to compute the timelag with
- property tmax
Time at max value of a signal
- Returns:
Time of maximum
- Return type:
unyt.array.unyt_quantity
- to_csv(filename, datatype='raw', includetime=False)
Saves the signal into a single CSV file
If the str parameter filename=’file’, the created file is file.csv
- Parameters:
filename (str) – string for the base file name (no extension)
datatype (str) – string for the optionnal data format (defaults to ‘raw’)
includetime (bool) – does the txt contains a time column ?
- to_csvtxt(filename, datatype='raw', includetime=False)
Saves the signal into a pair of files:
A CSV file with the signal parameters
A TXT file with the data
If the str parameter filename=’file’, the created files are file.csv and file.wav
- Parameters:
filename (str) – string for the base file name
datatype (str) – string for the optionnal data format (defaults to ‘raw’)
includetime (bool) – does the txt contains a time column ?
- to_csvwav(filename)
Saves the signal into a pair of files:
A CSV file with the signal parameters
A WAV file with the raw data
If the str parameter filename=’file’, the created files are file.csv and file.wav
- Parameters:
filename (str) – string for the base file name
- to_hdf5(hdf5_object, dataset_name='in_sigs', data_type=None, Channel_map=None)
Saves the signal in an hdf5 file
Save Signal in hdf5 file
- Parameters:
hdf5_object (str, Path or opened h5file handle) – The file or hdf5 object where to save the data
dataset_name (str) – Name of the hdf5 dataset
data_type (str) – Data format (Numpy dtype)
Channel_map (list of int) – Map of channel inside the queue,
If parameter hdf5_object is str or path, it is opened with statement, else it is an opened h5file handle already in with statement
- classmethod tri(fs=44100, dur=2.0, amp=1.0, freq=1000.0, unit=None, cal=None, dbfs=None, desc=None)
- property unit
Physical unit of the signal(s)
- unit_to(newunit)
Change Signal unit
- Parameters:
unit (unyt.unit or str) – Unit to convert to (has to be compatible)
- Raises:
Exception – ‘Incompatible units’
- Returns:
Signal converted to the new unit
- Return type:
- unit_to_std()
Change Signal unit to the standard base equivalent
- Returns:
Signal converted to the new unit
- Return type:
- unpack(add_chan_in_desc=True)
Unpack a multichannel signal and returns a list of signals
- property values
Values as 1D numpy array
- property volts
Volt values as 1D numpy array
- window(win='hann')
Apply the selected window function to the signal. Possible windows are that implemented by scipy package.
- Parameters:
win (string, float, or tuple) – Window
- Returns:
A windowed signal
- Return type:
measpy.signal.Signal, default to “hann”
- class measpy.signal.Spectral(**kwargs)
Bases:
object
Class that holds a set of values as function of evenly spaced frequencies. Usualy contains tranfert functions, spectral densities, etc.
Frequencies are not stored. If needed they are constructed using sampling frequencies and length of the values array by calling the property freqs.
- Parameters:
fs (int, optional) – Sampling frequency, defaults to 1
desc (str, optional) – Description, defaults to ‘Spectral data’
unit (str, unyt.Unit, optional) – Spectral data unit
values (numpy.array, optional) – Values of the pectral data
full (bool, optionnal) – If true, the full spectrum is given, from 0 to fs, if false, only up to fs/2
norm (string, optionnal) – Type of normalization “backward”, “ortho” or “full”. See numpy.fft doc.
values and dur cannot be both specified. If dur is given, values are initialised at 0
- angle(unwrap=True)
Compute the angle of the spectrum
- Parameters:
unwrap (bool) – If True, the angle data is unwrapped
- Returns:
The angle part of the signal, unit=rad
- Return type:
measpy.signal
- apply_dBA()
Apply dBA weighting
- Returns:
Weighted spectrum
- Return type:
- apply_dBC()
Apply dBC weighting
- Returns:
Weighted spectrum
- Return type:
- apply_weighting(w, inverse=False)
Applies weighting w to the spectral object
- Parameters:
inverse (Bool, optional) – If true, applies division instead of multiplication. Defaults to False.
- Returns:
New spectral object (with new unit)
- Return type:
- dBV()
Convert to dB dBV Signal unit has to be compatible with Volts
- Returns:
Weighted spectrum
- Return type:
- dB_SPL()
Convert to dB SPL (20 log10 ||P||/P0) Signal unit has to be compatible with Pa
- Returns:
Weighted spectrum
- Return type:
- dB_SVL()
Convert to dB SVL (20 log10 ||V||/V0) Signal unit has to be compatible with m/s
- Returns:
Weighted spectrum
- Return type:
- dBu()
Convert to dB dBu Signal unit has to be compatible with Volts
- Returns:
Weighted spectrum
- Return type:
- diff()
Compute frequency derivative
- Returns:
Frequency derivative of spectral (unit/Hz)
- Return type:
- property dur
Duration of the signal in time domain that corresponds to this spectral object.
- filterout(freqsrange)
Cancels values below and above a given frequency Returns a Spectral class object
- property freqs
Frequencies as 1D numpy array. If the property full=True, max frequency is fs. If full=False, max frequency is fs/2 or fs*(n-1)/(2n) if the sample_number is even or odd respectively.
- group_delay()
Compute group delay
- Returns:
Group delay (s)
- Return type:
- ifft()
Compute the inverse Fourier transform of the spectral data set
- imag()
Imaginary part
- Returns:
Real part (same unit)
- Return type:
- irfft(l=None)
Compute the real inverse Fourier transform of the spectral data set
- property length
Length of the spectral data (i.e. number of elements in its array values or freqs properties)
- nth_oct_smooth(n, fmin=5, fmax=20000)
Nth octave smoothing Works on real valued spectra. For complex values, use nth_oct_smooth_complex.
- Parameters:
n (int, optionnal) – Ratio of smoothing (1/nth smoothing), defaults to 3
fmin (float, int, optionnal) – Min value of the output frequencies, defaults to 5
fmax (float, int, optionnal) – Max value of the output frequencies, defaults to 20000
- Returns:
A smoothed spectral object
- Return type:
- nth_oct_smooth_complex(n, fmin=5, fmax=20000)
Nth octave smoothing Complex signal version
- Parameters:
n (int, optionnal) – Ratio of smoothing (1/nth smoothing), defaults to 3
fmin (float, int, optionnal) – Min value of the output frequencies, defaults to 5
fmax (float, int, optionnal) – Max value of the output frequencies, defaults to 20000
- Returns:
A smoothed spectral object
- Return type:
- nth_oct_smooth_to_weight(n=3, fmin=5, fmax=20000)
Nth octave smoothing Works on real valued spectra. For complex values, use nth_oct_smooth_to_weight_complex.
Converts a Spectral object into a Weighting object (a series of frequencies logarithmically spaced, with a corresponding complex value, expressed as amplitude and phase)
- Parameters:
n (int, optionnal) – Ratio of smoothing (1/nth smoothing), defaults to 3
fmin (float, int, optionnal) – Min value of the output frequencies, defaults to 5
fmax (float, int, optionnal) – Max value of the output frequencies, defaults to 20000
- nth_oct_smooth_to_weight_complex(n, fmin=5, fmax=20000)
Nth octave smoothing, complex version
- Parameters:
n (int, optionnal) – Ratio of smoothing (1/nth smoothing), defaults to 3
fmin (float, int, optionnal) – Min value of the output frequencies, defaults to 5
fmax (float, int, optionnal) – Max value of the output frequencies, defaults to 20000
- Returns:
A weighting object
- Return type:
- plot(ax=None, logx=True, dby=True, plot_phase=True, unwrap_phase=True, unwrap_around=0, **kwargs)
Plot spectral data
- Parameters:
ax (Axis type, optional) – Axis where to plot the data, defaults to None
logx (bool, optional) – If true, the frequency axis is in log scale, defaults to True
dby (bool, optional) – If true dB are plotted (20 log10 of absolute value), defaults to True
plot_phase (bool, optional) – If True, also plots the phase , defaults to True
unwrap_phase (bool, optional) – If True, phase is unwrapped, defaults to True
unwrap_around (float) – Frequency around which phase is unwrapped, defaults to 0.
- Returns:
An axes type object if plotphase is False, a list of two axes objects if plotphase is True
- Return type:
axes, or list of axes
- real()
Real part
- Returns:
Real part (same unit)
- Return type:
- property sample_number
Number of samples of the signal in time domain that corresponds to this spectral object. If the property full=True, sample_number=length. If full=False (half spectrum of a real signal), the number of samples depends on the odd property.
- similar(**kwargs)
Returns a copy of the Spectral object with properties changed as specified by the optionnal arguments.
It is possible to construct a new Spectral object by interpolating a Weighting object (parameter w)
- Parameters:
fs (int, optional) – Sampling frequency
desc (str, optional) – Description
unit (str, unyt.Unit, optional) – unit
values (numpy array, optionnal) – values of the spectral data
w (measpy.signal.Weighting, optionnal) – A Weighting object from which the spectrum is constructed by interpolation
- Returns:
A Spectral object
- Return type:
- classmethod tfe(x, y, **kwargs)
Initializes a spectral object by computing the transfer function between two signals of same sampling frequency and length. Optional arguments are the same as measpy.Signal.tfe_welch
- Parameters:
x (measpy.Signal.signal) – Input signal
y (measpy.Signal.signal) – Output signal
- Returns:
A spectral object
- Return type:
measpy.Signal.spectral
- property unit
- unit_to(newunit)
Converts to a new compatible unit
- Returns:
New spectral object (with new unit)
- Return type:
- property values
Values as 1D numpy array
- values_at_freqs(freqlist)
Get a series of values of the spectral object at given frequencies, using interpolation :param freqlist: A list of frequencies :type freqlist: Number or list or Numpy array :return: A complex number or an array of complex numbers
- class measpy.signal.Weighting(freqs, amp, phase=None, desc='Weigthing function')
Bases:
object
Class for weighting functions
Amplitudes are stored as absolute values and phase (in radians)
A Weighting object stores:
A list of frequencies (numpy.array)
Corresponding amplitudes (numpy.array)
Corresponding phases in radians (numpy.array)
A descriptor (string)
- property acomplex
Weighting values represented as a complex number
- property adb
Amplitude in dB Computes 20 log10 of the modulus of the amplitude
- classmethod from_csv(filename, asdB=True, asradians=True)
Loads a weighting object from a csv file The file must contain three columns:
One frequency column
One amplitude column (linear or as dB, which must be specified in the asdB boolean optional argument)
One phase column (as radians or degree, which must be specified in the asradians boolean optional argument)
- Parameters:
filename (str) – File name of the csv file to load
asdB (bool) – Specifies if the amplitude is given in dB or not
asradians (bool) – Specifies if the phase is given in radians or degrees
- Returns:
A Weighting object
- Return type:
measpy.weighting.Weighting
- to_csv(filename, asdB=True, asradians=True)
Saves a weighting object to a csv file The file then contains three columns:
One frequency column
One amplitude column (linear or as dB, which must be specified in the asdB boolean optional argument)
One phase column (as radians or degree, which must be specified in the asradians boolean optional argument)
- Parameters:
filename (str) – File name of the csv file to load
asdB (bool) – Specifies if the amplitude is given in dB or not
asradians (bool) – Specifies if the phase is given in radians or degrees
measpy.utils module
- measpy.utils.mic_calibration_freq(sig, sigref, Wref=None, noct=3, nperseg=None)
Microphone frequency response calibration function
- Parameters:
sig (measpy.signal.Signal) – Signal recorded by the microphone to calibrate
sigref (measpy.signal.Signal) – Signal recorded by the reference microphone
Wref (measpy.signal.Weighting) – Reference microphone response function as a Weighting object
noct (int) – Specifies the frequency averaging to apply. The returned measpy.signal.Weighting object will be 1/noct frequency averaged
nperseg (int) – Window size when transfer function estimation is made
- Returns:
A Weighting object containing the frequency response of the microphone
- Return type:
- Howto use:
Record mic and refmic signals using for example:
import measpy as mp FS = 48000 DUR = 10 pa = mp.Signal(fs=FS, unit='Pa',cal=...) paref = mp.Signal(fs=FS, unit='Pa', cal=...) M = mp.Measurement( device_type='audio', fs = FS, in_sig=[pa,paref], in_map=[1,2], dur=DUR, in_device='Default') audio_run_measurement(M)
Recorded signal is then analysed to get actual calibration
micresp = mic_calibration_freq(M.in_sig[0],M.in_sig[1],Wref=...)
Wref=… corresponds to the reference mic response curve.
Calibration curve is then the returned measpy.Weighting object
- measpy.utils.mic_calibration_level(sig, current_cal=1.0, target_db=94.0)
Microphone calibration function
- Parameters:
sig (float) – Signal recorded by the microphone to calibrate
current_cal – Calibration indicated in the recorded signal sig
target_db (float) – dB SPL level of the microphone calibrator
- Returns:
The actual value to use as calibration level, so that measured dB SPL equals to target_db
- Return type:
float
- Howto use:
Record mic signal with pistonphone using
import measpy as mp FS = 48000 DUR = 10 pa = mp.Signal(fs=FS, unit='Pa') M = mp.Measurement( device_type='audio', fs = FS, in_sig=[pa], in_map=[1], dur=DUR, in_device='Default') audio_run_measurement(M)
Recorded signal is then analysed to get actual calibration
newcal = mic_calibration_level(M.in_sig[0],current_cal=1.)
Calibration is then the value to use at signal creation
- measpy.utils.siglist_to_wav(sigl, filename)
Takes a list of signals and export it to a multichannel wave file. Sampling frequencies have to match. Use the resample method if necessary.
- Parameters:
sigl (list of measpy.signal.Signal) – A list of single channel signals
filename (string) – Name of wave file (without extension)
- Returns:
True if succeded, False if error
- Return type:
bool