SpectroData#
- class osekit.core_api.spectro_data.SpectroData(items: list[SpectroItem] | None = None, audio_data: AudioData = None, begin: Timestamp | None = None, end: Timestamp | None = None, name: str | None = None, fft: ShortTimeFFT | None = None, db_ref: float | None = None, v_lim: tuple[float, float] | None = None, colormap: str | None = None)#
SpectroDatarepresent spectrogram data retrieved fromSpectroFiles.The
SpectroDatahas a collection ofSpectroItem. The data is accessed via aSpectroItemobject perSpectroFile.Alternatively, the
SpectroDatavalue can be computed from anAudioData, thanks to a givenShortTimeFFTinstance.Initialize a
SpectroData.The
SpectroDatacan be initialized either from a list ofSpectroItemsor from anAudioDataand a givenShortTimeFFTinstance.Parameters#
- items: list[SpectroItem]
List of the
SpectroItemconstituting theSpectroData.- audio_data: AudioData
The
AudioDatafrom which to compute the spectrogram.- begin: Timestamp | None
Only effective if items is
None. Set the begin of the empty data.- end: Timestamp | None
Only effective if items is
None. Set the end of the empty data.- name: str | None
Name of the exported files.
- fft: ShortTimeFFT
The short time FFT used for computing the spectrogram.
- db_ref: float | None
Reference value for computing sx values in decibel.
- v_lim: tuple[float,float]
Lower and upper limits (in
dB) of the colormap used for plotting the spectrogram.- colormap: str
Colormap to use for plotting the spectrogram.
- property begin: Timestamp#
Return the begin timestamp of the data.
- property db_ref: float#
Reference value for computing sx values in decibel.
If no reference is specified (
self._db_ref is None), the sx db values will be given indB FS.
- property db_type: Literal['FS', 'SPL_instrument', 'SPL_parameter']#
Return whether the spectrogram
dBvalues are indB FSordB SPL.Returns#
Literal[“FS”, “SPL_instrument”, “SPL_parameter”]:
"FS": The values are expressed indB FS."SPL_instrument": The values are expressed indB SPLrelative to the linkedAudioData.instrument.P_REFproperty."SPL_parameter": The values are expressed indB SPLrelative to theself._db_reffield.
- property end: Timestamp#
Return the end timestamp of the data.
- classmethod from_audio_data(data: AudioData, fft: ShortTimeFFT, v_lim: tuple[float, float] | None = None, colormap: str | None = None) SpectroData#
Instantiate a
SpectroDataobject from aAudioDataobject.Parameters#
- data: AudioData
AudioDatafrom which theSpectroDatashould be computed.- fft: ShortTimeFFT
The
ShortTimeFFTused to compute the spectrogram.- v_lim: tuple[float,float]
Lower and upper limits (in
dB) of the colormap used for plotting the spectrogram.- colormap: str
Colormap to use for plotting the spectrogram.
Returns#
- SpectroData:
The
SpectroDataobject.
- classmethod from_dict(dictionary: dict, sft: ShortTimeFFT | None = None) Self#
Deserialize a
SpectroDatafrom a dictionary.Parameters#
- dictionary: dict
The serialized dictionary representing the
AudioData.- sft: ShortTimeFFT | None
The
ShortTimeFFTused to compute the spectrogram. If not provided, the SFT parameters must be included in the dictionary.
Returns#
- SpectroData
The deserialized
SpectroData.
- classmethod from_files(files: list[SpectroFile], begin: Timestamp | None = None, end: Timestamp | None = None, name: str | None = None, **kwargs) SpectroData#
Return a
SpectroDataobject from a list ofSpectroFiles.Parameters#
- files: list[SpectroFile]
List of
SpectroFilescontaining the data.- begin: Timestamp | None
Begin of the data object. Defaulted to the begin of the first file.
- end: Timestamp | None
End of the data object. Defaulted to the end of the last file.
- name: str | None
Name of the exported files.
- kwargs
Keyword arguments that are passed to the
clsconstructor.colormap: str Colormap to use for plotting the spectrogram.
Returns#
- SpectroData:
The
SpectroDatainstance.
- static get_default_ax() Axes#
Return a default-formatted
Axeson a new figure.The default osekit spectrograms are plotted on wide, borderless spectrograms. This method set the default figure and axes parameters.
Returns#
- plt.Axes:
The default
Axeson a new figure.
- classmethod get_overlapped_bins(sd1: SpectroData, sd2: SpectroData) ndarray#
Compute the bins that overflow between the two spectro data.
The idea is that if there is a
SpectroDatasd2that followssd1,sd1.get_value()will return the bins up to the first overlapping bin, andsd2will return the bins from the first overlapping bin.Signal processing guys might want to burn my house to the ground for it, but it seems to effectively resolve the issue we have with visible junction between spectrogram zoomed parts.
Parameters#
- sd1: SpectroData
The spectro data that ends before
sd2.- sd2: SpectroData
The spectro data that starts after
sd1.
Returns#
- np.ndarray:
The overlapped bins. If there are
pbins,sd1andsd2values should be concatenated as:np.hstack(sd1[:,:-p], result, sd2[:,p:])
- get_value() ndarray#
Return the Sx matrix of the spectrogram.
The Sx matrix contains the absolute square of the STFT.
- get_welch(nperseg: int | None = None, detrend: str | callable | False = 'constant', scaling: Literal['density', 'spectrum'] = 'density', average: Literal['mean', 'median'] = 'mean', *, return_onesided: bool = True) np.ndarray#
Estimate power spectral density of the
SpectroDatausing Welch’s method.This method uses the
scipy.signal.welch()function. The window, sample rate, overlap and mfft are taken from theSpectroData.fftproperty.Parameters#
- nperseg: int|None
Length of each segment. Defaults to
None, but if window isstrortuple, is set to256, and if window isarray_like, is set to the length of the window.- detrend: str | callable | False
Specifies how to detrend each segment. If detrend is a
str, it is passed as the type argument to the detrend function. If it is afunc, it takes a segment and returns a detrended segment. If detrend isFalse, no detrending is done. Defaults to'constant'.- return_onesided: bool
If
True, return a one-sided spectrum for real data. IfFalse, return a two-sided spectrum. Defaults toTrue, but for complex data, a two-sided spectrum is always returned.- scaling: Literal[“density”, “spectrum”]
Selects between computing the power spectral density (
'density') wherePxxhas units ofV**2/Hzand computing the squared magnitude spectrum ('spectrum') wherePxxhas units ofV**2, ifxis measured inVandfsis measured inHz. Defaults to'density'.- average: Literal[“mean”, “median”]
Method to use when averaging periodograms. Defaults to
'mean'.
Returns#
- np.ndarray
Power spectral density or power spectrum of the
SpectroData.
- item_cls#
alias of
SpectroItem
- link(folder: Path) None#
Link the
SpectroDatato aSpectroFilein the folder.The given folder should contain a file named
"str(self).npz". Linking is intended forSpectroDataobjects that have already been written to disk. After linking, theSpectroDatawill have a single item with the same properties of the targetSpectroFile.Parameters#
- folder: Path
Folder in which is located the
SpectroFileto which theSpectroDatainstance should be linked.
- link_audio_data(audio_data: AudioData) None#
Link the
SpectroDatato a givenAudioData.Parameters#
- audio_data: AudioData
The
AudioDatato which thisSpectroDatawill be linked.
- property nb_bytes: int#
Total bytes consumed by the spectro values.
- plot(ax: plt.Axes | None = None, sx: np.ndarray | None = None, scale: Scale | None = None) None#
Plot the spectrogram on a specific
Axes.Parameters#
- ax: plt.axes | None
Axeson which the spectrogram should be plotted. Defaulted toSpectroData.get_default_ax().- sx: np.ndarray | None
Spectrogram
sxvalues. Will be computed ifNone.- scale: osekit.core_api.frequecy_scale.Scale
Custom frequency scale to use for plotting the spectrogram.
- save_spectrogram(folder: Path, ax: plt.Axes | None = None, sx: np.ndarray | None = None, scale: Scale | None = None) None#
Export the spectrogram as a
pngimage.Parameters#
- folder: Path
Folder in which the spectrogram should be saved.
- ax: plt.Axes | None
Axes on which the spectrogram should be plotted. Defaulted to
SpectroData.get_default_ax().- sx: np.ndarray | None
Spectrogram
sxvalues. Will be computed ifNone.- scale: osekit.core_api.frequecy_scale.Scale
Custom frequency scale to use for plotting the spectrogram.
- property shape: tuple[int, ...]#
Shape of the
SpectroData.
- split(nb_subdata: int = 2, **kwargs) list[SpectroData]#
Split the spectro data object in the specified number of spectro subdata.
Parameters#
- nb_subdata: int
Number of subdata in which to split the data.
- kwargs:
None
Returns#
- list[SpectroData]
The list of
SpectroDatasubdata objects.
- property sx_dtype: type[complex]#
Data type used to represent the sx values.
Should either be
floatorcomplex. Ifcomplex, the phase info will be included in the computed spectrum. Iffloat, only the absolute value of the spectrum will be kept.
- to_db(sx: ndarray) ndarray#
Convert the
sxvalues todB.If the
self.audio_data.instrument is not None, the values are converted todB SPL(reself.audio_data.instrument.P_REF). Otherwise, the values are converted todB FS.Parameters#
- sx: np.ndarray
Sx values of the spectrum.
Returns#
- np.ndarray
Converted Sx values.
- to_dict(*, embed_sft: bool = True) dict#
Serialize a
SpectroDatato a dictionary.Parameters#
- embed_sft: bool
If
True, the SFT parameters will be included in the dictionary. In a case where multipleSpectroDatathat share a same SFT are serialized, SFT parameters shouldn’t be included in the dictionary, as the window values might lead to large redundant data. Rather, the SFT parameters should be serialized in aSpectroDatasetdictionary so that it can be only stored once for allSpectroDatainstances.
Returns#
- dict:
The serialized dictionary representing the
SpectroData.
- property v_lim: tuple[float, float]#
Limits (in
dB) of the colormap used for plotting the spectrogram.
- write(folder: Path, *, sx: np.ndarray | None = None, link: bool = False) None#
Write the Spectro data to file.
Parameters#
- folder: pathlib.Path
Folder in which to write the Spectro file.
- sx: np.ndarray | None
Spectrogram
sxvalues. Will be computed ifNone.- link: bool
If
True, theSpectroDatawill be bound to the writtennpzfile. Its items will be replaced with a single item, which will match the whole newSpectroFile.
- write_welch(folder: Path, px: np.ndarray | None = None, nperseg: int | None = None, detrend: str | callable | False = 'constant', scaling: Literal['density', 'spectrum'] = 'density', average: Literal['mean', 'median'] = 'mean', *, return_onesided: bool = True) None#
Write the psd (welch) of the
SpectroDatato anpzfile.Parameters#
- folder: pathlib.Path
Folder in which to write the Spectro file.
- px: np.ndarray | None
Welch
pxvalues. Will be computed if not provided.- nperseg: int|None
Length of each segment. Defaults to
None, but if window isstrortuple, is set to256, and if window isarray_like, is set to the length of the window.- detrend: str | callable | False
Specifies how to detrend each segment. If detrend is a
str, it is passed as the type argument to the detrend function. If it is afunc, it takes a segment and returns a detrended segment. If detrend isFalse, no detrending is done. Defaults to'constant'.- return_onesided: bool
If
True, return a one-sided spectrum for real data. IfFalse, return a two-sided spectrum. Defaults toTrue, but for complex data, a two-sided spectrum is always returned.- scaling: Literal[“density”, “spectrum”]
Selects between computing the power spectral density (
'density') wherePxxhas units ofV**2/Hzand computing the squared magnitude spectrum ('spectrum') wherePxxhas units ofV**2, ifxis measured inVandfsis measured inHz. Defaults to'density'.- average: Literal[“mean”, “median”]
Method to use when averaging periodograms. Defaults to
'mean'.