Biotuner object#
- class compute_biotuner(sf, data=None, peaks_function='EMD', precision=0.1, compute_sub_ratios=False, n_harm=10, harm_function='mult', extension_method='consonant_harmonic_fit', ratios_n_harms=5, ratios_harms=False, ratios_inc=True, ratios_inc_fit=False, scale_cons_limit=0.1)[source]#
Bases:
objectClass used to derive peaks information, musical tunings, rhythms and related harmonicity metrics from time series (EEG, ECG, EMG, gravitational waves, noise, …)
Basic usage#
>>> biotuning = compute_biotuner(sf = 1000) >>> biotuning.peaks_extraction(data) >>> biotuning.peaks_extension() >>> biotuning.peaks_metrics()
- Parameters:
sf (int) – Sampling frequency (in Hz)
data (array (numDataPoints,)) – Time series to analyze.
peaks_function (str, default=’EMD’) – Defines the method to use for peak extraction.
- ‘NON-HARMONIC PEAK EXTRACTIONS’
- ‘fixed’ :
Power Spectrum Density (PSD) estimated using Welch’s method on fixed frequency bands. Peaks correspond to frequency bins with the highest power.
- ‘adapt’ :
PSD estimated using Welch’s method on each frequency band derived from the alpha peak position. Peaks correspond to frequency bins with the highest power.
- ‘FOOOF’ :
PSD is estimated with Welch’s method. ‘FOOOF’ is applied to remove the aperiodic component and find physiologically relevant spectral peaks.
- ‘SIGNAL DECOMPOSITION BASED PEAK EXTRACTION’
- ‘EMD’:
Intrinsic Mode Functions (IMFs) are derived with Empirical Mode Decomposition (EMD) PSD is computed on each IMF using Welch. Peaks correspond to frequency bins with the highest power.
- ‘EEMD’ :
Intrinsic Mode Functions (IMFs) are derived with Ensemble Empirical Mode Decomposition (EEMD). PSD is computed on each IMF using Welch. Peaks correspond to frequency bins with the highest power.
- ‘CEEMDAN’Intrinsic Mode Functions (IMFs) are derived with Complex
Ensemble Empirical Mode Decomposition with Adaptive Noise (CEEMDAN). PSD is computed on each IMF using Welch.
- ‘EMD_FOOOF’ :
Intrinsic Mode Functions (IMFs) are derived with Ensemble Empirical Mode Decomposition (EEMD). PSD is computed on each IMF with Welch’s method. ‘FOOOF’ is applied to remove the aperiodic component and find physiologically relevant spectral peaks.
- ‘HH1D_max’ :
Maximum values of the 1D Hilbert-Huang transform on each IMF using EMD.
- ‘HH1D_FOOOF’ :
TODO. Hilbert-Huang transform on each IMF with Welch’s method ‘FOOOF’ is applied to remove the aperiodic component and find physiologically relevant spectral peaks.
- ‘SSA’ :
TODO. Singular Spectrum Analysis. The name “singular spectrum analysis” relates to the spectrum of eigenvalues in a singular value decomposition of a covariance matrix.
- ‘SECOND-ORDER STATISTICAL PEAK EXTRACTION’
- ‘cepstrum’:
Peak frequencies of the cepstrum (inverse Fourier transform (IFT) of the logarithm of the estimated signal spectrum).
- ‘HPS (to come)’ :
Harmonic Product Spectrum (HPS) corresponds to the product of the spectral power at each harmonic. Peaks correspond to the frequency bins with the highest value of the HPS.
- ‘Harmonic_salience (to come)’ :
A measure of harmonic salience computed by taking the sum of the squared cosine of the angle between a harmonic and its neighbors.
- ‘CROSS-FREQUENCY COUPLING BASED PEAK EXTRACTION’
- ‘Bicoherence’ :
Corresponds to the normalized cross-bispectrum. It is a third-order moment in the frequency domain. It is a measure of phase-amplitude coupling.
- ‘PAC’ :
Phase-amplitude coupling. A measure of phase-amplitude coupling between low-frequency phase and high-frequency amplitude.
- ‘PEAK SELECTION BASED ON HARMONIC PROPERTIES’
- ‘EIMC’ :
Endogenous InterModulation Components (EIMC) correspond to spectral peaks that are sums or differences of other peaks harmonics (f1+f2, f1+2f2, f1-f2, f1-2f2…). PSD is estimated with Welch’s method. All peaks are extracted.
- ‘harmonic_recurrence’ :
PSD is estimated with Welch’s method. All peaks are extracted. Peaks for which other peaks are their harmonics are kept.
‘PEAKS EXTRACTION PARAMETERS’
precision (float, default=0.1) – Precision of the peaks (in Hz). When HH1D_max is used, bins are in log scale by default.
compute_sub_ratios (bool, default=False) – When set to True, include ratios < 1 in peaks_ratios attribute.
scale_cons_limit (float, default=0.1) – The minimal value of consonance needed for a peaks ratio to be included in the peaks_ratios_cons attribute.
‘EXTENDED PEAKS PARAMETERS’
n_harm (int, default=10) – Set the number of harmonics to compute in harmonic_fit function.
harm_function (str, default=’mult’) –
- ‘mult’Computes harmonics from iterative multiplication
(x, 2x, 3x…)
‘div’: Computes harmonics from iterative division (x, x/2, x/3…).
extension_method (str, default=’consonant_harmonic_fit’) –
- ‘consonant_harmonic_fit’computes the best-fit of harmonic peaks
according to consonance intervals (eg. octaves, fifths).
- ‘all_harmonic_fit’computes the best-fit of harmonic peaks without
considering consonance intervals.
‘RATIOS EXTENSION PARAMETERS’
ratios_n_harms (int, default=5) – The number of harmonics used to compute extended peaks ratios.
ratios_harms (bool, default=False) – When set to True, harmonics (x*1, x*2, x*3…,x*n) of specified ratios will be computed.
ratios_inc (bool, default=True) – When set to True, exponentials (x**1, x**2, x**3,…x**n) of specified ratios will be computed.
ratios_inc_fit (bool, Default=False) – When set to True, a fit between exponentials (x**1, x**2, x**3,…x**n) of specified ratios will be computed.
- peaks_extraction(data=None, peaks_function=None, FREQ_BANDS=None, precision=None, sf=None, min_freq=1, max_freq=60, min_harms=2, compute_sub_ratios=False, ratios_extension=False, ratios_n_harms=None, scale_cons_limit=None, octave=2, harm_limit=128, n_peaks=5, prominence=1.0, rel_height=0.7, nIMFs=5, graph=False, nperseg=None, nfft=None, noverlap=None, max_harm_freq=None, EIMC_order=3, min_IMs=2, smooth_fft=1, verbose=False, keep_first_IMF=False, identify_labels=False)[source]#
The peaks_extraction method is central to the use of the Biotuner. It uses a time series as input and extract spectral peaks based on a variety of methods. See peaks_function parameter description in __init__ function for more details.
- Parameters:
data (array (numDataPoints,)) – biosignal to analyse
peaks_function (str) – refer to __init__
FREQ_BANDS (List of lists of float) – Each list within the list of lists sets the lower and upper limit of a frequency band
precision (float, default=0.1 -> __init__) – Precision of the peaks (in Hz) When HH1D_max is used, bins are in log scale.
sf (int) – Sampling frequency (in Hertz).
min_freq (float, default=1) – minimum frequency value to be considered as a peak Used with ‘harmonic_recurrence’ and ‘HH1D_max’ peaks functions
max_freq (float, default=60) – maximum frequency value to be considered as a peak Used with ‘harmonic_recurrence’ and ‘HH1D_max’ peaks functions
min_harms (int, default=2) – minimum number of harmonics to consider a peak frequency using the ‘harmonic_recurrence’ function.
compute_sub_ratios (Boolean, default=False) – If set to True, will include peaks ratios (x/y) when x < y
ratios_extension (Boolean, default=False) – When set to True, peaks_ratios harmonics and increments are computed.
ratios_n_harms (int, default=5 -> __init__) – number of harmonics or increments to use in ratios_extension method
scale_cons_limit (float, default=0.1) – minimal value of consonance to be reach for a peaks ratio to be included in the peaks_ratios_cons attribute.
octave (float, default=2) – value of the octave
harm_limit (int, default=128) – Maximum harmonic position for ‘harmonic_recurrence’ method.
n_peaks (int, default=5) – Number of peaks when using ‘FOOOF’ and ‘cepstrum’, and ‘harmonic_recurrence’ functions. Peaks are chosen based on their amplitude.
prominence (float, default=1.0) – Minimum prominence of peaks.
rel_height (float, default=0.7) – Minimum relative height of peaks.
nIMFs (int, default=5) – Number of intrinsic mode functions to keep when using ‘EEMD’ or ‘EMD’ peaks function.
graph (boolean, default=False) – When set to True, a graph will accompanies the peak extraction method (except for ‘fixed’ and ‘adapt’).
nperseg (int, default=None) – Length of each segment. If None, nperseg = nfft/smooth
nfft (int, default=None) – Length of the FFT used, if a zero padded FFT is desired. If None, nfft = sf/(1/precision)
noverlap (int, default=None) – Number of points to overlap between segments. If None, noverlap = nperseg // 2.
max_harm_freq (int, default=None) – Maximum frequency value of the find peaks function when harmonic_recurrence or EIMC peaks extraction method is used.
EIMC_order (int, default=3) – Maximum order of the Intermodulation Components.
min_IMs (int, default=2) – Minimal number of Intermodulation Components to select the associated pair of peaks.
smooth_fft (int, default=1) – Number used to divide nfft to derive nperseg.
verbose (boolean, default=True) – When set to True, number of detected peaks will be displayed.
keep_first_IMF (boolean, default=False) – When set to True, the first IMF is kept.
identify_labels (boolean, default=False) – When set to True, the labels of peaks ratios will be identified from the interval_names dictionary.
- self.peaks#
1D array of peaks frequencies
- Type:
array (float)
- self.amps#
1D array of peaks amplitudes
- Type:
array (float)
- self.peaks_ratios#
1D array of peaks ratios
- Type:
array (float)
- self.peaks_ratios_cons#
1D array of peaks ratios when more consonant than scale_cons_limit parameter.
- Type:
array (float)
- .. note::
- The following attributes are only present if `ratios_extension = True`
- self.peaks_ratios_harm#
List of peaks ratios and their harmonics
- Type:
List (float)
- self.peaks_ratios_inc#
List of peaks ratios and their increments (ratios**n)
- Type:
List (float)
- self.peaks_ratios_inc_bound#
List of peaks ratios and their increments (ratios**n) bound within one octave
- Type:
List (float)
- self.peaks_ratios_inc_fit#
List of peaks ratios and their congruent increments (ratios**n)
- Type:
List (float)
- peaks_extension(peaks=None, n_harm=None, method='harmonic_fit', harm_function='mult', div_mode='add', cons_limit=0.1, ratios_extension=False, harm_bounds=0.1, scale_cons_limit=None)[source]#
This method is used to extend a set of frequencies based on the harmonic congruence of specific elements (extend). It can also restrict a set of frequencies based on the consonance level of specific peak frequencies.
- Parameters:
peaks (List of float) – List of frequency peaks.
n_harm (int, default=10) – Set the number of harmonics to compute in harmonic_fit function
method (str, default=’harmonic_fit’) –
‘harmonic_fit’
‘consonant’
‘multi_consonant’,
‘consonant_harmonic_fit’
‘multi_consonant_harmonic_fit’
harm_function (str, default=’mult’) –
‘mult’ : Computes harmonics from iterative multiplication (x, 2x, 3x, …nx)
‘div’ : Computes harmonics from iterative division (x, x/2, x/3, …x/n)
div_mode (strm default=’add’) – Defines the way the harmonics are computed when harm_function is ‘div’
‘div’: x, x/2, x/3 …, x/n
‘div_add’: x, (x+x/2), (x+x/3), … (x+x/n)
‘div_sub’: x, (x-x/2), (x-x/3), … (x-x/n)
cons_limit (float) – Defines the minimal consonance level used in the method.
ratios_extension (Boolean, default=False) – If is True, ratios_extensions are computed accordingly to what was defined in __init__.
harm_bounds (float, default=0.1) – Maximal distance in Hertz between two frequencies to consider them as equivalent.
scale_cons_limit (float, default=None) – Minimal value of consonance to be reach for a peaks ratio to be included in the extended_peaks_ratios_cons attribute. When None, scale_cons_limit = 0.1, as defined in __init__
- Returns:
self.extended_peaks (List (float)) – List of extended peaks frequencies.
self.extended_amps (List (float)) – List of extended peaks amplitudes.
self.extended_peaks_ratios (List (float)) – List of pairwise extended peaks ratios.
self.extended_peaks_ratios_cons (List (float)) – List of pairwise extended peaks ratios when more consonant than scale_limit_cons parameter.
- .. note::
- The following attributes are only present if `ratios_extension = True`
- self.peaks_ratios_harm#
List of extended peaks ratios and their harmonics
- Type:
List (float)
- self.peaks_ratios_inc#
List of extended peaks ratios and their increments (ratios**n)
- Type:
List (float)
- self.peaks_ratios_inc_fit#
List of extended peaks ratios and their congruent increments (ratios**n).
- Type:
List (float)
- plot_peaks(xmin=1, xmax=60, show_bands=True, show_matrix=False, matrix_metric='harmsim', **kwargs)[source]#
Plot the extracted peaks with unified biotuner styling.
This is a convenience method that calls the plot_peaks function from plot_utils. All parameters from plot_peaks are supported.
- Parameters:
xmin (float, default=1) – Minimum frequency for x-axis (Hz)
xmax (float, default=60) – Maximum frequency for x-axis (Hz)
show_bands (bool, default=True) – Whether to show frequency bands (Delta, Theta, Alpha, etc.)
show_matrix (bool, default=False) – Whether to show a 3-panel layout with harmonicity matrix
matrix_metric (str, default=’harmsim’) – Metric for harmonicity matrix: ‘harmsim’, ‘cons’, ‘tenney’, ‘denom’, ‘subharm_tension’
**kwargs (dict) – Additional parameters passed to plot_peaks, including: - n_peaks : int (for harmonic_recurrence method) - n_pairs : int (for EIMC method) - use_db : bool (for dB scale) - etc.
- Returns:
fig (matplotlib.figure.Figure) – The figure object
ax (matplotlib.axes.Axes or np.ndarray) – Single axes (if show_matrix=False) or array of 3 axes (if show_matrix=True)
Examples
>>> bt = compute_biotuner(sf=1000, peaks_function='FOOOF') >>> bt.peaks_extraction(data=signal, min_freq=1, max_freq=50) >>> fig, ax = bt.plot_peaks(show_bands=True, show_matrix=True) >>> plt.show()
>>> # With EIMC method >>> bt = compute_biotuner(sf=1000, peaks_function='EIMC') >>> bt.peaks_extraction(data=signal, min_freq=1, max_freq=50) >>> fig, ax = bt.plot_peaks(n_pairs=3, show_matrix=True)
- plot_peaks_summary(xmin=1, xmax=60, show_bands=True, show_matrix=True, matrix_metric='harmsim', **kwargs)[source]#
Alias for plot_peaks() - plots comprehensive peak summary.
- plot_peaks_spectrum(xmin=1, xmax=60, show_bands=True, **kwargs)[source]#
Plot only the spectral peaks on PSD (no additional panels).
- Parameters:
xmin, xmax (float) – Frequency range
show_bands (bool, default=True) – Whether to show frequency bands
**kwargs (dict) – Additional parameters
- Returns:
fig, ax (matplotlib figure and axes)
- plot_peaks_amplitude(xmin=1, xmax=60, **kwargs)[source]#
Plot peak amplitude distribution as bar chart.
- Parameters:
xmin, xmax (float) – Frequency range
**kwargs (dict) – Additional parameters
- Returns:
fig, ax (matplotlib figure and axes)
- plot_peaks_matrix(metric='harmsim', **kwargs)[source]#
Plot peak ratios harmonicity matrix.
- Parameters:
metric (str, default=’harmsim’) – Metric for matrix: ‘harmsim’, ‘cons’, ‘tenney’, ‘denom’, ‘subharm_tension’
**kwargs (dict) – Additional parameters
- Returns:
fig, ax (matplotlib figure and axes)
- plot_tuning(tuning='peaks_ratios', metric='harmsim', ratio_type='all', vmin=None, vmax=None, panels=4, extra_panels=None, show_summary=True, show_source_curve=True, max_denom=100, figsize=None, **kwargs)[source]#
Plot comprehensive tuning analysis with unified biotuner styling.
This is a convenience method that calls plot_tuning_ratios from plot_utils.
- Parameters:
tuning (str, default=’peaks_ratios’) – Which tuning to plot: - ‘diss_curve’: Dissonance curve scale (requires compute_diss_curve first) - ‘HE’: Harmonic entropy scale (requires compute_harmonic_entropy first) - ‘harm_tuning’: Harmonic tuning (auto-computed if needed) - ‘harm_fit_tuning’: Harmonic fit tuning (auto-computed if needed) - ‘peaks_ratios’: Peaks ratios (auto-computed if needed) - ‘euler_fokker’: Euler-Fokker scale (auto-computed if needed)
metric (str, default=’harmsim’) – Metric for consonance matrix: ‘harmsim’, ‘cons’, ‘tenney’, ‘denom’, ‘subharm_tension’
ratio_type (str, default=’all’) – Type of ratios: ‘all’, ‘pos_harm’, ‘sub_harm’
vmin (float, optional) – Minimum value for color scale
vmax (float, optional) – Maximum value for color scale
panels (int, default=4) – Number of panels (2, 4, or 5 with summary)
extra_panels (list of str, optional) – Extra panels for 4-panel mode. Default: [‘step_sizes’, ‘consonance_profile’] Options: ‘step_sizes’, ‘consonance_profile’, ‘interval_distribution’, ‘harmonic_deviation’
show_summary (bool, default=True) – Show 5th summary panel with interval matches
show_source_curve (bool, default=True) – If True and tuning is ‘diss_curve’ or ‘HE’, automatically shows the source curve (dissonance or entropy) as a top full-width panel
max_denom (int, default=100) – Maximum denominator for fraction simplification (e.g., 5/4 instead of 1.25). Lower values produce simpler fractions. Default 100 works well for most scales.
figsize (tuple, optional) – Figure size. Default: (16, 16)
**kwargs (dict) – Additional parameters passed to plot_tuning_ratios
- Returns:
fig (matplotlib.figure.Figure) – The figure object
Examples
>>> bt = compute_biotuner(sf=1000) >>> bt.peaks_extraction(data=signal) >>> fig = bt.plot_tuning_ratios(tuning='peaks_ratios') >>> plt.show()
>>> # Plot dissonance curve scale >>> bt.compute_diss_curve(input_type='peaks', plot=False) >>> fig = bt.plot_tuning_ratios(tuning='diss_curve')
>>> # Plot harmonic tuning (auto-computed) >>> fig = bt.plot_tuning_ratios(tuning='harm_tuning')
- plot_tuning_summary(tuning='peaks_ratios', metric='harmsim', ratio_type='all', vmin=None, vmax=None, panels=4, extra_panels=None, show_summary=True, show_source_curve=True, max_denom=100, figsize=None, **kwargs)[source]#
Alias for plot_tuning() - plots comprehensive tuning summary.
- plot_tuning_scale(tuning='peaks_ratios', max_denom=100, figsize=None, **kwargs)[source]#
Plot only the tuning scale as bar chart (no other panels).
- Parameters:
tuning (str, default=’peaks_ratios’) – Which tuning to plot
max_denom (int, default=100) – Maximum denominator for fractions
figsize (tuple, optional) – Figure size
**kwargs (dict) – Additional parameters
- Returns:
fig, ax (matplotlib figure and axes)
- plot_tuning_matrix(tuning='peaks_ratios', metric='harmsim', ratio_type='all', vmin=None, vmax=None, max_denom=100, figsize=None, **kwargs)[source]#
Plot only the consonance matrix for a tuning (no other panels).
- Parameters:
tuning (str, default=’peaks_ratios’) – Which tuning to plot
metric (str, default=’harmsim’) – Consonance metric
ratio_type (str, default=’all’) – Ratio type: ‘all’, ‘pos_harm’, ‘sub_harm’
vmin, vmax (float, optional) – Color scale limits
max_denom (int, default=100) – Maximum denominator for fractions
figsize (tuple, optional) – Figure size
**kwargs (dict) – Additional parameters
- Returns:
fig, ax (matplotlib figure and axes)
- plot_tuning_intervals(tuning='peaks_ratios', max_denom=100, figsize=None, **kwargs)[source]#
Plot melodic intervals (step sizes) between adjacent notes.
- Parameters:
tuning (str, default=’peaks_ratios’) – Which tuning to plot
max_denom (int, default=100) – Maximum denominator for fractions
figsize (tuple, optional) – Figure size
**kwargs (dict) – Additional parameters
- Returns:
fig, ax (matplotlib figure and axes)
- plot_tuning_consonance_profile(tuning='peaks_ratios', metric='harmsim', ratio_type='all', max_denom=100, figsize=None, **kwargs)[source]#
Plot consonance profile showing distribution of consonance for each scale degree.
- Parameters:
tuning (str, default=’peaks_ratios’) – Which tuning to plot
metric (str, default=’harmsim’) – Consonance metric
ratio_type (str, default=’all’) – Ratio type: ‘all’, ‘pos_harm’, ‘sub_harm’
max_denom (int, default=100) – Maximum denominator for fractions
figsize (tuple, optional) – Figure size
**kwargs (dict) – Additional parameters
- Returns:
fig, ax (matplotlib figure and axes)
- plot_tuning_curve(curve_type='auto', max_ratio=2.0, show_minima=True, figsize=None, **kwargs)[source]#
Plot source curve (dissonance or harmonic entropy) with local minima.
- Parameters:
curve_type (str, default=’auto’) – Type of curve: ‘dissonance’, ‘entropy’, or ‘auto’ (auto-detect from available data)
max_ratio (float, default=2.0) – Maximum ratio to display
show_minima (bool, default=True) – Show markers at local minima
figsize (tuple, optional) – Figure size
**kwargs (dict) – Additional parameters
- Returns:
fig, ax (matplotlib figure and axes)
- plot_tuning_interval_table(tuning='peaks_ratios', max_denom=100, tolerance_cents=5.0, max_intervals=10, figsize=None, **kwargs)[source]#
Plot a table showing known musical intervals matched to the tuning scale.
- Parameters:
tuning (str or list, default=’peaks_ratios’) – Tuning type or list of ratios
max_denom (int, default=100) – Maximum denominator for fractions
tolerance_cents (float, default=5.0) – Tolerance in cents for matching intervals
max_intervals (int, default=10) – Maximum number of intervals to display
figsize (tuple, optional) – Figure size
**kwargs (dict) – Additional parameters
- Returns:
fig, ax (matplotlib figure and axes)
- plot_harmonic_fit(n_harm=None, harm_bounds=0.5, function='mult', div_mode='div', xmin=1, xmax=60, show_bands=True, figsize=(16, 12), **kwargs)[source]#
Plot comprehensive harmonic fit analysis showing harmonic structures.
This visualization shows how peaks relate harmonically to each other, displaying original peaks, extended peaks, harmonic relationships, and consonance patterns across multiple intuitive panels.
- Parameters:
n_harm (int, optional) – Number of harmonics to compute. Default: self.n_harm
harm_bounds (float, default=0.5) – Maximum distance (Hz) between frequencies to consider a harmonic fit
function (str, default=’mult’) – Harmonic function type: - ‘mult’: Natural harmonics (x, 2x, 3x, …) - ‘div’: Sub-harmonics (x, x/2, x/3, …) - ‘exp’: Exponential harmonics (x, x^2, x^3, …)
div_mode (str, default=’div’) – Sub-harmonic mode when function=’div’: - ‘div’: x, x/2, x/3, … - ‘div_add’: x, x+x/2, x+x/3, … - ‘div_sub’: x, x-x/2, x-x/3, …
xmin (float, default=1) – Minimum frequency (Hz) for x-axis
xmax (float, default=60) – Maximum frequency (Hz) for x-axis
show_bands (bool, default=True) – Whether to show EEG frequency bands
figsize (tuple, default=(16, 12)) – Figure size (width, height)
**kwargs (dict) – Additional plotting parameters
- Returns:
fig (matplotlib.figure.Figure) – The figure object
axes (np.ndarray) – Array of axes (2x2 grid)
Examples
>>> bt = compute_biotuner(sf=1000) >>> bt.peaks_extraction(data=signal) >>> fig, axes = bt.plot_harmonic_fit(n_harm=10) >>> plt.show()
>>> # Focus on sub-harmonic relationships >>> fig, axes = bt.plot_harmonic_fit(function='div', n_harm=5)
Notes
The plot contains 4 panels: 1. Top-left: Original peaks with their harmonic series overlay 2. Top-right: Original vs Extended peaks comparison 3. Bottom-left: Harmonic connectivity/relationship matrix 4. Bottom-right: Consonance analysis and fit quality
- plot_harmonic_fit_network(n_harm: int | None = None, harm_bounds: float = 0.5, function: str = 'mult', figsize: tuple = (10, 10), ax=None, **kwargs)[source]#
Plot harmonic network showing relationships between peaks.
Creates a circular network where nodes are peaks and edges show the number of shared harmonics between peak pairs.
- Parameters:
n_harm (int, optional) – Number of harmonics per peak. Default: self.n_harm
harm_bounds (float, default=0.5) – Frequency threshold (Hz) for considering harmonics as matching
function (str, default=’mult’) – Harmonic function: ‘mult’, ‘div’, or ‘exp’
figsize (tuple, default=(10, 10)) – Figure size
ax (plt.Axes, optional) – Existing axes to plot on
**kwargs (dict) – Additional plotting parameters
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- plot_harmonic_fit_matrix(n_harm: int | None = None, harm_bounds: float = 0.5, figsize: tuple = (8, 7), ax=None, **kwargs)[source]#
Plot harmonic connectivity matrix showing shared harmonics between peak pairs.
- Parameters:
n_harm (int, optional) – Number of harmonics per peak. Default: self.n_harm
harm_bounds (float, default=0.5) – Frequency threshold (Hz) for considering harmonics as matching
figsize (tuple, default=(8, 7)) – Figure size
ax (plt.Axes, optional) – Existing axes to plot on
**kwargs (dict) – Additional plotting parameters
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- plot_harmonic_fit_positions(n_harm: int | None = None, harm_bounds: float = 0.5, function: str = 'mult', figsize: tuple = (14, 6), **kwargs)[source]#
Plot harmonic position analysis in two side-by-side panels.
Left panel: Bipartite network showing which harmonic positions are shared Right panel: Histogram of harmonic position distribution
- Parameters:
n_harm (int, optional) – Number of harmonics per peak. Default: self.n_harm
harm_bounds (float, default=0.5) – Frequency threshold (Hz) for considering harmonics as matching
function (str, default=’mult’) – Harmonic function: ‘mult’, ‘div’, or ‘exp’
figsize (tuple, default=(14, 6)) – Figure size
**kwargs (dict) – Additional plotting parameters
- Returns:
fig (matplotlib.figure.Figure)
axes (np.ndarray) – Array of axes [ax_left, ax_right]
- plot_harmonic_position_mappings(n_harm: int = 10, harm_bounds: float = 0.5, function: str = 'mult', figsize: tuple = (14, 10), **kwargs)[source]#
Plot harmonic position mappings between peak pairs.
Shows which specific harmonic positions (1st, 2nd, 3rd, etc.) of one peak match with which harmonic positions of another peak.
- Parameters:
n_harm (int, default=10) – Number of harmonics to compute for each peak
harm_bounds (float, default=0.5) – Frequency threshold (Hz) for considering harmonics as matching
function (str, default=’mult’) – Harmonic function to use: - ‘mult’: Natural harmonics (f, 2f, 3f, …) - ‘div’: Sub-harmonics (f, f/2, f/3, …)
figsize (tuple, default=(14, 10)) – Figure size (width, height) in inches
**kwargs (dict) – Additional keyword arguments passed to the plotting function
- Returns:
fig (matplotlib.figure.Figure) – The figure object
ax (matplotlib.axes.Axes) – The axes object
Examples
>>> bt.plot_harmonic_position_mappings(n_harm=10, harm_bounds=0.5) >>> bt.plot_harmonic_position_mappings(n_harm=15, function='div')
- ratios_extension(ratios, ratio_fit_bounds=0.001, ratios_n_harms=None)[source]#
This method takes a series of ratios as input and returns the harmonics (ratio*2, ratio*3, …, ratio*n) or the increments (ratio**2, ratio**3, …, ratio**n).
- Parameters:
ratios (List (float)) – List of frequency ratios.
ratio_fit_bounds (float, default=0.001) – Minimal distance between two ratios to consider a fit for the harmonic_fit function.
ratios_n_harms (int, default=None) – Number of harmonics or increments to compute. When None, the number of harmonics or increments is set to the value of the attribute ratios_n_harms.
- Returns:
ratios_harms_ (List (float)) – List of ratios harmonics.
ratios_inc_ (List (float)) – List of ratios increments.
ratios_inc_fit_ (List (float)) – List of ratios increments that fit.
- time_resolved_harmonicity(input='IF', method='harmsim', keep_first_IMF=False, nIMFs=3, IMFs=None, delta_lim=20, limit_cons=0.2, min_notes=3, graph=False, window=None)[source]#
Compute the time-resolved harmonicity of the input data, which involves computation of instantaneous frequency (IF) or SpectroMorph analysis on the input data, followed by harmonicity computation on the IFs or SpectroMorph data. :Parameters: * input (str, default=’IF’) – The input type for harmonicity computation, either ‘IF’ (instantaneous frequency) or ‘SpectralCentroid’.
method (str, default=’harmsim’) – The method used for harmonicity computation, such as ‘harmsim’.
keep_first_IMF (bool, default=False) – Whether to keep the first intrinsic mode function (IMF) after EMD.
nIMFs (int, default=3) – The number of IMFs to consider in the analysis.
IMFs (array_like, default=None) – Precomputed IMFs. If None, IMFs are computed within the method.
delta_lim (int, default=20) – The limit for delta when method is ‘subharm_tension’.
limit_cons (float, default=0.2) – The limit for consonance for spectral chords.
min_notes (int, default=3) – The minimum number of notes required for spectral chords.
graph (bool, default=False) – If True, a graph of the computed harmonicity will be displayed.
window (int, default=None) – The window size for SpectroMorph analysis. If None, it is set to half of the sampling frequency.
- Returns:
tuple – A tuple containing the following: - time_resolved_harmonicity : array_like
The time-resolved harmonicity of the input data.
- spectro_chordsList of lists (float)
Each sublist corresponds to a list of harmonious instantaneous frequencies (IFs).
- spectro_chord_posList (int)
Positions in the time series where each chord from self.spectro_chords is located.
- self.spectro_chords#
Each sublist corresponds to a list of harmonious instantaneous frequencies (IFs).
- Type:
List of lists (float)
- self.time_resolved_harmonicity#
The time-resolved harmonicity of the input data.
- Type:
array_like
- self.spectro_EMD#
The spectroMorph analysis of the input data.
- Type:
array_like
- self.IFs#
The instantaneous frequencies of the input data.
- Type:
array_like
- self.IMFs#
The intrinsic mode functions (IMFs) of the input data.
- Type:
array_like
- compute_spectromorph(IMFs=None, sf=None, method='SpectralCentroid', window=None, overlap=1, nIMFs=5)[source]#
This method computes spectromorphological metrics on each Intrinsic Mode Function (IMF).
- Parameters:
IMFs (array (nIMFs, numDataPoints)) – Intrinsic Mode Functions. When set to ‘None’, the IMFs are computed in the method.
sf (int) – Sampling frequency.
method (str, default=’SpectralCentroid’) –
Spectromorphological metric to compute.
‘SpectralCentroid’,
‘SpectralCrestFactor’,
‘SpectralDecrease’,
‘SpectralFlatness’,
‘SpectralFlux’,
‘SpectralKurtosis’,
‘SpectralMfccs’,
‘SpectralPitchChroma’,
‘SpectralRolloff’,
‘SpectralSkewness’,
‘SpectralSlope’,
‘SpectralSpread’,
‘SpectralTonalPowerRatio’,
‘TimeAcfCoeff’,
‘TimeMaxAcf’,
‘TimePeakEnvelope’,
‘TimeRms’,
‘TimeStd’,
‘TimeZeroCrossingRate’,}
window (int) – Window size in samples.
overlap (int) – Value of the overlap between successive windows.
- self.spectro_EMD#
Spectromorphological metric vector for each IMF.
- Type:
array (numDataPoints, nIMFs)
- self.spectro_chords#
Each sublist corresponds to a list of consonant spectromorphological metrics.
- Type:
List of lists (float)
- compute_peaks_metrics(n_harm=None, harm_bounds=0.5, delta_lim=20)[source]#
This function computes consonance metrics on peaks attribute.
- Parameters:
n_harm (int) – Set the number of harmonics to compute in harmonic_fit function
harm_bounds (float, default=0.5) – Maximal distance in Hertz between two frequencies to consider them as equivalent.
- self.peaks_metrics#
Dictionary with keys corresponding to the different metrics.
‘cons’
‘euler’
‘tenney’
‘harm_fit’
‘harmsim’
‘n_harmonic_recurrence’,
‘n_harmonic_recurrence_ratio’
‘harm_pos’
‘common_harm_pos’
- Type:
dict
- compute_diss_curve(input_type='peaks', denom=1000, max_ratio=2, euler_comp=False, method='min', plot=False, n_tet_grid=12, scale_cons_limit=None)[source]#
Compute dissonance curve based on peak frequencies.
- Parameters:
input_type (str, default=’peaks’) – Defines whether peaks or extended_peaks are used.
‘peaks’
‘extended_peaks’
denom (int, default=1000) – Maximal value of the denominator when computing frequency ratios.
max_ratio (float, default=2) – Value of the maximal frequency ratio to use when computing the dissonance curve. When set to 2, the curve spans one octave. When set to 4, the curve spans two octaves.
euler_comp (Boolean, default=False) – Defines if euler consonance is computed. Can be computationally expensive when the number of local minima is high.
method (str, default=’min’) – Refer to dissmeasure function in scale_construction.py for more information.
‘min’
‘product’
plot (Boolean, default=False) – When set to True, dissonance curve is plotted.
n_tet_grid (int, default=12) – Defines which N-TET tuning is indicated, as a reference, in red in the dissonance curve plot.
scale_cons_limit (float, default=None) – Minimal value of consonance to be reach for a peaks ratio to be included in the self.diss_scale_cons attribute. When set to None, the value of self.scale_cons_limit is used.
- self.diss_scale#
List of frequency ratios corresponding to local minima.
- Type:
List (float)
- self.diss_scale_cons#
List of frequency ratios corresponding to consonant local minima.
- Type:
List (float)
- self.scale_metrics#
Add 4 metrics related to the dissonance curve tuning:
‘diss_euler’
‘dissonance’
‘diss_harm_sim’
‘diss_n_steps’
- Type:
dict
- compute_harmonic_entropy(input_type='peaks', res=0.001, spread=0.01, plot_entropy=True, plot_tenney=False, octave=2, rebound=True, sub=False, scale_cons_limit=None)[source]#
Computes the harmonic entropy from a series of spectral peaks. Harmonic entropy has been introduced by Paul Elrich [http://www.tonalsoft.com/enc/e/erlich/harmonic-entropy_with- commentary.aspx]
- Parameters:
input_type (str, default=’peaks’) – Defines whether peaks or extended_peaks are used.
‘peaks’
‘extended_peaks’
res (float, default=0.001) – Resolution of the ratio steps.
spread (float, default=0.01) – Spread of the normal distribution used to compute the weights.
plot_entropy (Boolean, default=True) – When set to True, plot the harmonic entropy curve.
plot_tenney (Boolean, default=False) – When set to True, plot the tenney heights (y-axis) across ratios (x-axis).
octave (int, default=2) – Value of the octave.
rebound (Boolean, default=True) – When set to True, peaks ratios are bounded within the octave.
sub (Boolean, default=False) – When set to True, will include ratios below the unison (1)
scale_cons_limit (type, default=None) – Minimal value of consonance to be reach for a peaks ratio to be included in the self.diss_scale_cons attribute. When set to None, the value of self.scale_cons_limit is used.
- self.HE_scale#
List of frequency ratios corresponding to local minima.
- Type:
List (float)
- self.HE_scale_cons#
List of frequency ratios corresponding to consonant local minima.
- Type:
List (float)
- self.scale_metrics#
Four metrics related to the dissonance curve tuning:
‘HE’
‘HE_n_steps’
‘HE_harm_sim’
- Type:
dict
- euler_fokker_scale(method='peaks', octave=2)[source]#
Create a scale in the Euler-Fokker Genera. which is a musical scale in just intonation whose pitches can be expressed as products of some of the members of some multiset of generating primer numbers.
- Parameters:
method (str, default=’peaks’) – Defines which set of frequencies are used.
‘peaks’
‘extended_peaks’
octave (float, default=2) – Value of period interval.
- Returns:
self.euler_fokker (List (float)) – Euler-Fokker genera.
- self.euler_fokker#
Euler-Fokker genera.
- Type:
List (float)
- harmonic_tuning(list_harmonics=None, octave=2, min_ratio=1, max_ratio=2)[source]#
Generates a tuning based on a list of harmonic positions.
- Parameters:
list_harmonics (List of int) – harmonic positions to use in the scale construction
octave (int, default=2) – value of the period reference
min_ratio (float, default=1) – Value of the unison.
max_ratio (float, default=2) – Value of the octave.
- Returns:
ratios (List (float)) – Generated tuning.
- self.harmonic_tuning#
Generated tuning.
- Type:
List (float)
- harmonic_fit_tuning(n_harm=128, bounds=0.1, n_common_harms=2)[source]#
Extracts the common harmonics of spectral peaks and compute the associated harmonic tuning.
- Parameters:
n_harm (int) – Number of harmonics to consider in the harmonic fit`.
bounds (float, default=0.1) – Maximal distance in Hertz between two frequencies to consider them as equivalent.
n_common_harms (int, default=2) – minimum number of times the harmonic is found to be sent to most_common_harmonics output.
- Returns:
self.harmonic_fit_tuning (List (float)) – Generated tuning
- self.harmonic_fit_tuning#
Generated tuning
- Type:
List (float)
- pac(sf=None, method='duprelatour', n_values=10, drive_precision=0.05, max_drive_freq=6, min_drive_freq=3, sig_precision=1, max_sig_freq=50, min_sig_freq=8, low_fq_width=0.5, high_fq_width=1, plot=False)[source]#
Computes the phase-amplitude coupling and returns to pairs of frequencies that have highest coupling value.
- Parameters:
sf (int) – Sampling frequency in hertz.
method (str, default=’duprelatour’) –
- Choice of method for PAC calculation.
STANDARD_PAC_METRICS:
‘ozkurt’
‘canolty’
‘tort’
‘penny’
‘vanwijk’
DAR_BASED_PAC_METRICS:
‘duprelatour’
COHERENCE_PAC_METRICS:
‘jiang’
‘colgin’
BICOHERENCE_PAC_METRICS:
‘sigl’
‘nagashima’
‘hagihira’
‘bispectrum’
n_values (int, default=10) – Number of pairs of frequencies to return.
drive_precision (float, default=0.05) – Step-size between each phase signal bins.
max_drive_freq (float, default=6) – Maximum value of the phase signal in hertz.
min_drive_freq (float, default=3) – Minimum value of the phase signal in hertz.
sig_precision (float, default=1) – Step-size between each amplitude signal bins.
max_sig_freq (float, default=50) – Maximum value of the amplitude signal in hertz.
min_sig_freq (float, default=8) – Minimum value of the amplitude signal in hertz.
low_fq_width (float, default=0.5) – Bandwidth of the band-pass filter (phase signal)
high_fq_width (float, default=1) – Bandwidth of the band-pass filter (amplitude signal)
plot (Boolean, default=False) – When set to True, a plot of the comodulogram is generated.
- Returns:
pac_freqs (List of lists (float)) – Pairs of frequencies with highest coupling value. Stored in self.pac_freqs.
pac_coupling (List (float)) – Values of coupling for each pair in pac_freqs. Stored in self.pac_coupling.
- rhythm_construction(scale='peaks_ratios', mode='default', cons_threshold=0.2, max_denom=8, n_steps_down=3, graph=False, optimal_offsets=True)[source]#
Computes Euclidean rhythms from a scale defined between unison and octave.
- Parameters:
scale (str, default=’peaks_ratios’) – The scale from which Euclidean rhythms are generated. Options include ‘peaks_ratios’, ‘extended_peaks_ratios’, ‘diss_scale’, ‘HE_scale’, ‘harmonic_fit_tuning’, ‘harmonic_tuning’, and ‘euler_fokker’, each corresponding to a different scale computation method within the class.
mode (str, default=’default’) – The rhythm generation mode. Options are ‘default’ for basic Euclidean rhythms and ‘consonant’ for rhythms with maximized consonance, based on the ‘cons_threshold’ parameter and the use of shared denominator values.
cons_threshold (float, default=0.2) – Consonance threshold used in ‘consonant’ mode to maximize consonance between rhythm pairs. See the ‘compute_consonance’ function in the ‘scale_construction’ module for more information.
max_denom (int, default=8) – The maximum denominator used in the rhythm generation process, controlling the complexity of the rhythm. Only used in ‘consonant’ mode.
n_steps_down (int, default=3) – The number of steps by which the generated Euclidean rhythm is transposed down. Only used in ‘consonant’ mode.
- Raises:
RuntimeError – If the specified ‘scale’ is not computed prior to invoking this method.
- Returns:
tuple – The first element is a list of generated Euclidean rhythms. The second element is their corresponding referential strings, derived from comparing the generated rhythms to known referent patterns.
Notes
This method requires the prior computation of the specified ‘scale’. For instance, ‘peaks_ratios’ requires the ‘peaks_extraction’ method to be called beforehand. The method’s return values are integral to further rhythm analysis and comparison within the Biot
- compute_peaks_ts(data, peaks_function='EMD', FREQ_BANDS=None, precision=0.5, sf=None, min_freq=1, max_freq=80, min_harms=2, harm_limit=128, n_peaks=5, prominence=1.0, rel_height=0.7, nIMFs=None, graph=False, noverlap=None, average='median', nfft=None, nperseg=None, max_harm_freq=None, EIMC_order=3, min_IMs=2, smooth_fft=1, keep_first_IMF=False)[source]#
Extract peak frequencies. This method is called by the peaks_extraction method.
- Parameters:
data (array (numDataPoints,)) – Niosignal to analyse
peaks_function (str) – Refer to __init__
FREQ_BANDS (List of lists of floats) – Each list within the list of lists sets the lower and upper limit of a frequency band
precision (float, default=0.5) – Precision of the peaks (in Hz) When HH1D_max is used, bins are in log scale.
sf (int, default=None) – Sampling frequency in hertz.
min_freq (float, default=1) – Minimum frequency value to be considered as a peak Used with ‘harmonic_recurrence’ and ‘HH1D_max’ peaks functions
max_freq (float, default=80) – Maximum frequency value to be considered as a peak Used with ‘harmonic_recurrence’ and ‘HH1D_max’ peaks functions
min_harms (int, default=2) – Minimum number of harmonics to be considered for peaks extraction
harm_limit (int, default=128) – Maximum harmonic position for ‘harmonic_recurrence’ method.
n_peaks (int, default=5) – Number of peaks when using ‘FOOOF’ and ‘cepstrum’, and ‘harmonic_recurrence’ functions. Peaks are chosen based on their amplitude.
prominence (float, default=1.0) – Minimum prominence value to be considered as a peak Used with ‘harmonic_recurrence’ and ‘HH1D_max’ peaks functions
rel_height (float, default=0.7) – Minimum relative height value to be considered as a peak
nIMFs (int, default=None) – number of intrinsic mode functions to keep when using ‘EEMD’ or ‘EMD’ peaks function.
graph (boolean, default=False) – When set to True, a graph will accompanies the peak extraction method (except for ‘fixed’ and ‘adapt’).
noverlap (int, default=None) – Number of samples overlap between each fft window. When set to None, equals sf//10.
average (str, default=’median’) – Method to use when averaging periodograms.
‘mean’: average periodograms
‘median’: median periodograms
max_harm_freq (int, default=None) – Maximum frequency value of the find peaks function when harmonic_recurrence or EIMC peaks extraction method is used.
EIMC_order (int, default=3) – Maximum order of the Intermodulation Components.
min_IMs (int, default=2) – Minimal number of Intermodulation Components to select the associated pair of peaks.
smooth_fft (int, default=1) – Number used to divide nfft to derive nperseg. When set to 1, nperseg = nfft.
keep_first_IMF (boolean, default=False) – When set to True, the first IMF is kept.
- Returns:
peaks (List (float)) – List of peaks frequencies.
amps (List (float)) – List of amplitudes associated with peaks frequencies.
- self.freqs#
Vector representing the frequency bins of the Power Spectrum Density (PSD)
- Type:
array
- self.psd#
Vector representing the PSD values for each frequency bin.
- Type:
array
- self.IMFs#
Intrinsic mode functions resulting from decomposing the signal with Empirical Mode Decomposition.
- Type:
array (nIMFs, numDataPoints)
- self.IF#
instantaneous frequencies for each IMF. Only when ‘HH1D_max’ is used as peaks extraction method.
- Type:
array (nIMFs, numDataPoints)
- self.all_harmonics#
List of all harmonic positions when harmonic_recurrence method is used.
- Type:
List (int)
- self.FREQ_BANDS#
List of frequency bands.
- Type:
List of lists (float)
- compute_resonance(harm_thresh=30, PPC_thresh=0.6, smooth_fft=2, harmonicity_metric='harmsim', delta_lim=50)[source]#
Compute resonances between pairs of frequency peaks in the data.
- Parameters:
harm_thresh (int, default=30) – The minimum harmonic similarity between a peak pair required to be considered a resonance. Must be a positive integer.
PPC_thresh (float, default=0.6) – The minimum bispectral power correlation required for a peak pair to be considered a resonance. Must be a float between 0 and 1.
smooth_fft (int, default=2) – The number of times to smooth the data using a Hamming window before computing the FFT. Must be a positive integer. When smooth_fft=1, nperseg=nfft.
harmonicity_metric (str, default=’harmsim’) – The metric to use for computing the harmonic similarity between a pair of peaks. Choose between:
‘harmsim’
‘subharm_tension’
delta_lim (int, default=50) – The maximum number of subharmonic intervals to consider when using the ‘subharm_tension’ metric. Must be a positive integer.
- Returns:
Tuple[float, List[Tuple[float, float]], List[float], List[float]] – A tuple containing the following elements:
resonance: a float representing the mean weighted bicorrelation coefficient across all harmonic pairs that meet the specified criteria for harmonicity and PPC
resonant_freqs: a list of tuples, where each tuple contains two floats representing the frequencies of a pair of resonant harmonics that meet the specified criteria for harmonicity and PPC
harm_all: a list of floats representing the harmonic similarity metric between all possible harmonic pairs
bicor_all: a list of floats representing the bicorrelation coefficient between all possible harmonic pairs
- listen_scale(scale, fund=250, length=500)[source]#
Play a scale of notes using pygame.
- Parameters:
scale (str or np.ndarray) – The scale to play. If scale is a string, it can be one of:
‘peaks’: the scale is set to the biotuner object’s peaks_ratios attribute
‘diss’: the scale is set to the biotuner object’s diss_scale attribute
‘HE’: the scale is set to the biotuner object’s HE_scale attribute
If scale is a numpy array, it should be an array of scale ratios.
fund (float, default=250) – The fundamental frequency of the scale.
length (float, default=500) – The length of each note in milliseconds.
- Returns:
None
- fit_all(data, compute_diss=True, compute_HE=True, compute_peaks_extension=True)[source]#
Fit biotuning metrics to input data using various optional computations.
- Parameters:
data (array, shape (n_samples,)) – A single time series of EEG data.
compute_diss (bool, optional, default=True) – If True, compute the dissonance curve.
compute_HE (bool, optional, default=True) – If True, compute the harmonic entropy.
compute_peaks_extension (bool, optional, default=True) – If True, compute the peaks extension using the multi-consonant harmonic fit method.
- Returns:
biotuning (Biotuning object) – The fitted biotuning object containing the computed metrics.
- fit_biotuner(ts, bt_dict)[source]#
Compute biotuner metrics on a single time series using a specified set of parameters.
- Parameters:
ts (array, shape (n_samples,)) – A single time series of EEG data.
bt_dict (dict) – A dictionary containing the parameters to compute biotuner metrics. See the compute_biotuner and tuning_to_metrics functions documentation for details on the required keys and values.
- Returns:
bt_dict (dict) – The modified input dictionary with the computed biotuner metrics added.