### Example Usage of nsgfwin() Primary Version Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-transforms.md Demonstrates how to use the primary nsgfwin function to compute window functions, reference frequency positions, and hop sizes for a given set of frequencies and Q-factors. This example uses a constant Q-factor and a non-sliced transform. ```python from nsgt.nsgfwin_sl import nsgfwin import numpy as np f = np.array([100, 200, 400, 800, 1600]) # Hz q = np.ones_like(f) * 10 # Constant Q g, rfbas, M = nsgfwin(f, q, sr=44100, Ls=44100, sliced=False) print(f"Bands: {len(g)}") print(f"Hop sizes: {M}") print(f"Window lengths: {[len(gi) for gi in g]}") ``` -------------------------------- ### Install NSGT Library Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/README.md Install the NSGT library using pip. This is the first step before using any of its functionalities. ```bash pip install nsgt ``` -------------------------------- ### Example: NSGT_sliced forward() Usage Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-sliced.md Demonstrates how to initialize NSGT_sliced and use the forward method with a generator yielding signal slices. Shows how to retrieve the first slice of coefficients. ```python from nsgt import NSGT_sliced, OctScale import numpy as np fs = 44100 sl_len = 4096 # Must be divisible by 4 tr_area = 512 # Transition area scale = OctScale(80, 8000, bins=24) nsgt_sl = NSGT_sliced(scale, sl_len, tr_area, fs, real=True) # Generate sliced input def signal_generator(): for i in range(10): yield np.random.randn(sl_len) coef_stream = nsgt_sl.forward(signal_generator()) first_slice = next(coef_stream) print(f"First slice bands: {len(first_slice)}") ``` -------------------------------- ### CQ_NSGT Initialization and Usage Example Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-nsgt.md Demonstrates how to initialize CQ_NSGT for musical note analysis and perform forward and backward transforms. Assumes real-valued input and standard audio parameters. ```python from nsgt import CQ_NSGT import numpy as np # Musical note analysis (A0=27.5 Hz to C8=4186 Hz) cq = CQ_NSGT(fmin=27.5, fmax=4186, bins=12, fs=44100, Ls=44100, real=True) # Forward and backward are identical to NSGT signal = np.random.randn(44100) coefs = cq.forward(signal) recon = cq.backward(coefs) ``` -------------------------------- ### NSGT Forward Transform Example Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-nsgt.md Demonstrates how to compute the non-stationary Gabor transform of a signal using the NSGT class. This example shows the setup of the NSGT object and the output format of the forward transform for a single-channel real signal. ```python import numpy as np from nsgt import NSGT, OctScale # Setup fs = 44100 # 44.1 kHz Ls = 44100 # 1 second scale = OctScale(80, 8000, bins=24) # 80-8000 Hz, 24 bins/octave nsgt = NSGT(scale, fs, Ls, real=True) # Single channel signal = np.random.randn(Ls) coefs = nsgt.forward(signal) print(f"Number of frequency bands: {len(coefs)}") print(f"Coefficients per band shape: {coefs[0].shape}") ``` -------------------------------- ### Instantiate OctScale Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-scales.md Example of creating an OctScale object with specified frequency bounds and number of bins. This is a common way to initialize a frequency scale. ```python from nsgt import OctScale scale = OctScale(80, 8000, bins=24) ``` -------------------------------- ### Musical Constant-Q Analysis with CQ_NSGT_sliced Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-sliced.md Demonstrates how to perform musical constant-Q analysis on an audio stream using CQ_NSGT_sliced. This example shows initialization, creating a dummy audio stream, and performing forward and backward transforms. ```python from nsgt import CQ_NSGT_sliced import numpy as np # Musical constant-Q analysis cq_sl = CQ_NSGT_sliced(fmin=27.5, fmax=4186, bins=12, sl_len=8192, tr_area=1024, fs=44100, real=True) def audio_stream(): for i in range(100): yield np.random.randn(8192) coef_stream = cq_sl.forward(audio_stream()) recon_stream = cq_sl.backward(coef_stream) first_slice = next(recon_stream) ``` -------------------------------- ### Sampling Frequency Example Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/configuration.md Example of setting the sampling frequency in Hz. This value impacts the time-frequency resolution trade-off. ```python 44100 ``` -------------------------------- ### Example Usage of reblock Function Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-slicing.md Demonstrates how to use the reblock function with variable-length input blocks and fixed block size. Shows how the final block is padded if fulllast is True. ```python from nsgt.reblock import reblock import numpy as np def variable_blocks(): yield np.arange(100) yield np.arange(50) yield np.arange(75) reblocked = reblock(variable_blocks(), blocksize=64, fulllast=True) for i, block in enumerate(reblocked): print(f"Block {i}: {len(block)} samples") # Block 0: 64 # Block 1: 64 # Block 2: 64 (padded with zeros) ``` -------------------------------- ### Frequency Scale Example Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/configuration.md Example of defining a frequency scale using OctScale. This parameter determines the distribution of frequency bands in the transform. ```python OctScale(80, 8000, 12) ``` -------------------------------- ### Instantiate SndWriter and Write Audio Blocks Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-audio.md Create a stereo 24-bit WAV file writer and write multiple audio blocks generated randomly. Ensure pysndfile is installed for writing capabilities. ```python from nsgt.audio import SndWriter import numpy as np # Create stereo 24-bit WAV file writer = SndWriter("output.wav", samplerate=44100, filefmt='wav', datafmt='pcm24', channels=2) # Generate and write audio blocks for i in range(100): block = np.random.randn(2, 4410) # 0.1 second at 44.1 kHz writer(iter([block])) print("File written successfully") ``` -------------------------------- ### Import Public API from nsgt Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/module-index.md Imports core transform classes, frequency scales, and optional audio I/O utilities from the nsgt library. Ensure pysndfile is installed for audio I/O. ```python from nsgt import ( # Main transform classes NSGT, # Core non-stationary Gabor transform CQ_NSGT, # Constant-Q variant (auto OctScale) NSGT_sliced, # Streaming version CQ_NSGT_sliced, # Streaming constant-Q # Frequency scales Scale, # Base class OctScale, # Logarithmic (bins per octave) LogScale, # Logarithmic (fixed bands) LinScale, # Linear spacing MelScale, # Mel-frequency scale # Audio I/O (optional, may not import if pysndfile unavailable) SndReader, # Read audio files SndWriter, # Write audio files ) ``` -------------------------------- ### nsigtf() Example: Manual Inverse Transform Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-transforms.md Demonstrates manual reconstruction of a signal using nsigtf() after a forward transform. This is typically done via NSGT.backward() for convenience. Ensure the 'real' and 'reducedform' flags match the forward transform. ```python from nsgt.nsigtf import nsigtf from nsgt.cq import NSGT from nsgt.fscale import OctScale import numpy as np scale = OctScale(80, 8000, 24) nsgt = NSGT(scale, fs=44100, Ls=44100, real=True) signal = np.random.randn(44100) cofes = nsgt.forward(signal) # Manual inverse call recon = nsigtf(coefs, nsgt.gd, nsgt.wins, nsgt.nn, Ls=44100, real=nsgt.real, reducedform=nsgt.reducedform) error = np.linalg.norm(signal - recon) / np.linalg.norm(signal) print(f"Reconstruction error: {error:.2e}") ``` -------------------------------- ### nsigtf_sl() Example: Reconstructing a Signal Slice Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-transforms.md Shows how to use the generator-based nsigtf_sl() to reconstruct a signal slice from a coefficient sequence. This is useful for memory-efficient streaming processing. ```python from nsgt.nsigtf import nsigtf_sl import numpy as np # coef_seq is generator from forward transform recon_gen = nsigtf_sl(coef_seq, gd, wins, nn, Ls=4096, real=True) first_slice = next(recon_gen) print(f"Reconstructed slice length: {len(first_slice)}") ``` -------------------------------- ### Example usage of slicing function Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-slicing.md Demonstrates how to use the slicing function to process a signal stream and print the shape and range of the first slice. Ensure the signal_stream function yields numpy arrays. ```python from nsgt.slicing import slicing import numpy as np def signal_stream(): for i in range(100): yield np.random.randn(4096) sliced = slicing(signal_stream(), sl_len=4096, tr_area=512) first_slice = next(sliced) print(f"Slice shape: {first_slice.shape}") print(f"Slice range: [{first_slice.min():.2f}, {first_slice.max():.2f}]") ``` -------------------------------- ### Get Number of Bands in Scale Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-scales.md Demonstrates how to get the total number of frequency bands defined in a scale object using the len() function. This is useful for understanding the resolution of the scale. ```python num_bands = len(scale) ``` -------------------------------- ### FFT Backend System Overview Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/architecture.md Provides an overview of the `fft.py` module, which abstracts FFT implementations. It lists available backends, classes, and configurable behaviors like benchmarking and data type precision. ```plaintext fft.py provides abstraction over FFT implementations: Available backends (in order of preference): 1. PyFFTW3 (C library, fastest) 2. PyFFTW (pure Python interface to FFTW) 3. NumPy FFT (pure Python, universal) Classes: - fftp() : Forward complex FFT - ifftp() : Inverse complex FFT - rfftp() : Forward real FFT (halves output size) - irfftp() : Inverse real FFT Behavior: - measure=True : FFTW benchmarks and optimizes (slow init, fast exec) - measure=False : FFTW uses estimates (fast init, slower exec) - dtype : Controls precision (float32/float64) ``` -------------------------------- ### Low-Latency Real-Time Streaming with CQ_NSGT_sliced Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/usage-examples.md Demonstrates setting up and using CQ_NSGT_sliced for real-time audio processing with minimal latency. Requires audio interface for input/output. Note the pseudo-code nature of audio interface interaction. ```python from nsgt import CQ_NSGT_sliced import numpy as np # Setup low-latency configuration fs = 48000 sl_len = 2048 # ~42 ms latency tr_area = 256 cq_sl = CQ_NSGT_sliced( fmin=20, fmax=20000, bins=12, sl_len=sl_len, tr_area=tr_area, fs=fs, real=True, multithreading=False # No threading for low latency ) # Input/output buffers (from audio interface) input_buffer = np.zeros(sl_len) output_buffer = np.zeros(sl_len) # Streaming loop (pseudo-code) coef_gen = None recon_gen = None while True: # Read from audio input new_samples = audio_interface.read(sl_len) input_buffer = np.concatenate([input_buffer[sl_len:], new_samples]) # First slice: initialize generators if coef_gen is None: from nsgt.slicing import slicing slices = slicing([input_buffer], sl_len, tr_area) coef_gen = cq_sl.forward(slices) recon_gen = cq_sl.backward(coef_gen) next(recon_gen) # Skip first padding slice next(recon_gen) # Skip second padding slice # Get reconstructed samples reconstructed = next(recon_gen) # Write to audio output (last sl_len/4 samples) audio_interface.write(reconstructed[-sl_len//4:]) # Process frame (e.g., apply effects) # coefs = next(coef_gen) # coefs = [modify(c) for c in coefs] # recon = next(recon_gen) ``` -------------------------------- ### Fast Real-Time Processing (Speech) Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/configuration.md Configure CQ_NSGT_sliced for real-time speech processing. This setup prioritizes low latency and parallel processing for faster analysis. ```python from nsgt import CQ_NSGT_sliced cq_sl = CQ_NSGT_sliced( fmin=50, fmax=8000, bins=12, sl_len=4096, # ~90 ms at 44.1 kHz tr_area=512, # 12.5 ms transition fs=44100, real=True, multithreading=True ) ``` -------------------------------- ### Compute Dual Windows Manually Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-transforms.md Demonstrates how to manually compute dual windows using the nsdual function. This is useful for understanding the process or when the dual windows are not pre-computed during NSGT initialization. ```python from nsgt.nsdual import nsdual from nsgt.cq import NSGT from nsgt.fscale import OctScale scale = OctScale(80, 8000, 24) nsgt = NSGT(scale, fs=44100, Ls=44100) # Dual windows already computed in NSGT.__init__ # But can be computed manually: gd_manual = nsdual(nsgt.g, nsgt.wins, nsgt.nn, nsgt.M) ``` -------------------------------- ### LogScale Constructor and Usage Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-scales.md Instantiate LogScale for logarithmic frequency spacing. Useful when a fixed number of bands is needed, and bands are logarithmically spaced with constant Q-factor. ```python from nsgt import LogScale import numpy as np # 100 logarithmic bands from 20 Hz to 20 kHz scale = LogScale(20, 20000, bnds=100) freqs, q = scale() print(f"Bands: {len(freqs)}") print(f"Spacing ratio: {np.log2(freqs[1]/freqs[0]):.3f}") ``` -------------------------------- ### LogScale Constructor Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-scales.md Initializes a logarithmic frequency scale with a specified number of bands. Frequencies are logarithmically spaced with a constant Q-factor. ```APIDOC ## LogScale(fmin, fmax, bnds, beyond=0) ### Description Logarithmic frequency scale with explicit band count. Alternative to OctScale, specifying total bands directly instead of bins-per-octave. Frequency bands are logarithmically spaced with constant Q-factor. ### Parameters #### Path Parameters - **fmin** (float) - Required - Minimum frequency in Hz. Must be > 0. - **fmax** (float) - Required - Maximum frequency in Hz. Must be > fmin. - **bnds** (int) - Required - Total number of bands (excluding beyond). Must be > 0. - **beyond** (int) - Optional - Extra bands below/above range. Non-negative integer. Defaults to 0. ### Example ```python from nsgt import LogScale import numpy as np # 100 logarithmic bands from 20 Hz to 20 kHz scale = LogScale(20, 20000, bnds=100) freqs, q = scale() print(f"Bands: {len(freqs)}") print(f"Spacing ratio: {np.log2(freqs[1]/freqs[0]):.3f}") ``` ``` -------------------------------- ### Frequency Scale Interface Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/architecture.md Instantiate a frequency scale and retrieve frequency and Q-factor arrays. The number of bands is determined by the length of the scale. ```python scale = SomeScale(fmin, fmax, ...) freqs, q_factors = scale() # Returns frequency and Q-factor arrays num_bands = len(scale) ``` -------------------------------- ### Precision Spectral Analysis (Scientific) Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/configuration.md Configure NSGT with LogScale for scientific spectral analysis requiring high precision and frequency resolution. This setup is optimized for batch processing of long signals. ```python from nsgt import NSGT, LogScale scale = LogScale(1, 22050, bnds=256) # 256 logarithmic bands nsgt = NSGT( scale, fs=44100, Ls=441000, # 10 seconds real=True, dtype=np.float64, # High precision measurefft=True # Optimize FFT for long signals ) ``` -------------------------------- ### CQ_NSGT Constructor Parameters Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-nsgt.md Defines the parameters for initializing the CQ_NSGT, including frequency range, bins per octave, sampling frequency, signal length, and processing options. ```python CQ_NSGT(fmin, fmax, bins, fs, Ls, real=True, matrixform=False, reducedform=0, multichannel=False, measurefft=False, multithreading=False) ``` -------------------------------- ### Transform Audio File with CQ_NSGT and OctScale Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/usage-examples.md Demonstrates transforming an audio file using CQ_NSGT with an OctScale frequency representation. Includes reading audio, performing forward and inverse transforms, calculating reconstruction error, and writing the output to a WAV file. ```python import numpy as np from nsgt import CQ_NSGT, LogScale, LinScale, MelScale, OctScale # Read audio (using pysndfile or ffmpeg) try: from pysndfile import PySndfile sf = PySndfile("audio.wav") fs = sf.samplerate() samples = sf.frames() s = sf.read_frames(samples) except: from scipy.io import wavfile fs, s = wavfile.read("audio.wav") if s.ndim > 1: s = np.mean(s, axis=1) # Convert to mono Ls = len(s) # Choice of frequency scale scale = OctScale(80, 22050, bins=24) # Create transform nsgt = CQ_NSGT( fmin=80, fmax=22050, bins=24, fs=fs, Ls=Ls, real=True, matrixform=False, reducedform=0 ) # Forward transform c = nsgt.forward(s) c = np.asarray(c) print(f"Coefficients shape: {c.shape}") # Inverse transform s_r = nsgt.backward(c) # Compute reconstruction error norm = lambda x: np.sqrt(np.sum(np.abs(np.square(x)))) rec_err = norm(s - s_r) / norm(s) print(f"Reconstruction error: {rec_err:.3e}") # Write reconstructed audio from pysndfile import PySndfile, construct_format sf_out = PySndfile("output.wav", mode='w', format=construct_format('wav', 'pcm24'), channels=1, samplerate=fs) sf_out.write_frames(s_r) sf_out.close() ``` -------------------------------- ### Extensibility for Custom Scales and Windows Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/architecture.md The architecture supports extensibility through custom scale definitions by subclassing `Scale` and modular window generation, allowing easy integration of different windows and FFT backends. ```text - Users can define custom scales by subclassing `Scale`. - Window generation is modular: easy to plug in different windows. - FFT backend can be swapped at runtime (first import wins). ``` -------------------------------- ### Generate Scale Frequencies and Q-factors Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-scales.md Shows how to generate and print the center frequencies and Q-factors for all bands of a scale. This is typically called during NSGT/CQ_NSGT initialization. ```python scale = OctScale(80, 8000, 24) freqs, q_factors = scale() print(f"Number of bands: {len(freqs)}") print(f"Min frequency: {freqs[0]} Hz") print(f"Max frequency: {freqs[-1]} Hz") ``` -------------------------------- ### SndWriter Constructor Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-audio.md Initializes an SndWriter object to create an audio file. It takes the output file path, sample rate, and optional parameters for file format, data format, and number of channels. ```APIDOC ## SndWriter Constructor ### Description Creates an audio file writer. Requires pysndfile for file format support. Files are written sequentially via __call__(). ### Method Signature ```python SndWriter(fn, samplerate, filefmt='wav', datafmt='pcm16', channels=1) ``` ### Parameters #### Path Parameters - **fn** (str) - Required - Output file path. File is created or overwritten. - **samplerate** (int) - Required - Sample rate in Hz. #### Query Parameters - **filefmt** (str) - Optional - Default: 'wav' - File container format: 'wav', 'aiff', 'au', 'raw', etc. See pysndfile documentation. - **datafmt** (str) - Optional - Default: 'pcm16' - Sample data format: 'pcm16', 'pcm24', 'pcm32', 'float', 'double', etc. See pysndfile documentation. - **channels** (int) - Optional - Default: 1 - Number of channels. Usually 1 (mono) or 2 (stereo). ### Raises - `ImportError` — If pysndfile is not installed (required for writing). ### Example ```python from nsgt.audio import SndWriter import numpy as np # Create stereo 24-bit WAV file writer = SndWriter("output.wav", samplerate=44100, filefmt='wav', datafmt='pcm24', channels=2) # Generate and write audio blocks for i in range(100): block = np.random.randn(2, 4410) # 0.1 second at 44.1 kHz writer(iter([block])) print("File written successfully") ``` ``` -------------------------------- ### Q() Method Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-scales.md Returns the constant Q-factor for the scale. This value is consistent across all frequency bands. ```APIDOC ## Q() Method ### Description Returns the constant Q-factor. Returns `self.q` for any specified band. OctScale maintains a constant Q across the entire frequency range. ### Method Signature ```python def Q(self, bnd=None): ... ``` ### Parameters #### Path Parameters - **bnd** (int or None) - Optional - Band index or indices for which to compute the Q-factor. If None, returns the Q-factor for all bands (which will be identical). ### Return Type `float or ndarray` (all elements identical) ``` -------------------------------- ### FFT Backend Abstraction Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/module-index.md Classes for abstracting FFT operations with backend selection. ```APIDOC ## FFT Backend Abstraction ### `fftp(measure=False, dtype=float)` - **Description**: Forward complex FFT. - **Parameters**: - `measure` (bool, optional): Whether to measure performance. Defaults to False. - `dtype` (type, optional): The data type. Defaults to float. - **Returns**: A forward complex FFT object. ### `ifftp(measure=False, dtype=float)` - **Description**: Inverse complex FFT. - **Parameters**: - `measure` (bool, optional): Whether to measure performance. Defaults to False. - `dtype` (type, optional): The data type. Defaults to float. - **Returns**: An inverse complex FFT object. ### `rfftp(measure=False, dtype=float)` - **Description**: Forward real FFT. - **Parameters**: - `measure` (bool, optional): Whether to measure performance. Defaults to False. - `dtype` (type, optional): The data type. Defaults to float. - **Returns**: A forward real FFT object. ### `irfftp(measure=False, dtype=float)` - **Description**: Inverse real FFT. - **Parameters**: - `measure` (bool, optional): Whether to measure performance. Defaults to False. - `dtype` (type, optional): The data type. Defaults to float. - **Returns**: An inverse real FFT object. **Backend Selection**: The FFT classes prioritize backends in the following order: PyFFTW3, PyFFTW, and NumPy FFT (fallback). ``` -------------------------------- ### Streaming and Slicing Process Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/architecture.md Illustrates the input signal processing flow through slicing, transformation, and arrangement for efficient processing. It highlights the internal slice structure and the key insight of 25/75% overlap. ```plaintext Input signal → slicing() → overlapping chunks → transform → arrange() ↓ Slice structure (handled internally): - Forward: output slices are rearranged for efficient processing - Inverse: input slices are un-rearranged before processing Key insight: 25/75% overlap between consecutive slices requires rearrangement to maintain causality and perfect reconstruction. ``` -------------------------------- ### Audio I/O Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/module-index.md Optional utilities for reading and writing audio files, dependent on the `pysndfile` library. ```APIDOC ## SndReader ### Description Utility class for reading audio files. ### Class Signature `SndReader` ``` ```APIDOC ## SndWriter ### Description Utility class for writing audio files. ### Class Signature `SndWriter` ``` -------------------------------- ### Find Executable File Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-audio.md Use findfile to search the system's PATH for a specified executable. It accepts a custom predicate for matching files. ```python def findfile(fn, path=os.environ['PATH'].split(os.pathsep), matchFunc=os.path.isfile): ... ``` -------------------------------- ### Instantiate MelScale Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-scales.md Creates a mel-frequency scale with specified frequency bounds and number of bands. Ensure fmin is greater than 0 and fmax is greater than fmin. ```python from nsgt import MelScale import numpy as np # Mel scale: 50 Hz to 8 kHz in 128 bands scale = MelScale(50, 8000, bnds=128) freqs, q = scale() print(f"Bands: {len(freqs)}") print(f"Min freq: {freqs[0]:.1f} Hz, Max freq: {freqs[-1]:.1f} Hz") ``` -------------------------------- ### nsgfwin() - Legacy Version Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-transforms.md An older version of `nsgfwin` maintained for compatibility. It uses a different API and only returns windows for non-sliced transforms. ```APIDOC ## nsgfwin() - Legacy Version ### Description Older API maintained for compatibility. Returns windows for non-sliced transform only. Consider using nsgfwin_sl version instead. ### Method `nsgfwin(fmin, fmax, bins, sr, Ls, min_win=4)` ### Parameters #### Path Parameters - **fmin** (float) - Required - Minimum frequency in Hz. - **fmax** (float) - Required - Maximum frequency in Hz. - **bins** (int or ndarray) - Required - Bins per octave (scalar) or array of bin counts per octave. - **sr** (int) - Required - Sample rate in Hz. - **Ls** (int) - Required - Signal length in samples. - **min_win** (int) - Optional - Minimum window length. Default: 4. ### Return Type `tuple of (list, ndarray, ndarray)` ``` -------------------------------- ### __call__() Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-scales.md Generates and returns arrays of center frequencies and their corresponding Q-factors for all bands in the scale. This method is typically called during the initialization of NSGT or CQ_NSGT objects. ```APIDOC ## __call__() ### Description Generates frequency and Q-factor arrays for the scale. ### Method ```python def __call__(self): ... ``` ### Return Type `tuple of (ndarray, ndarray)` - First element: frequencies for all bands (Hz). - Second element: Q-factors for all bands. ``` -------------------------------- ### Window Generation Utilities Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/module-index.md Functions for generating various types of windows used in signal processing. ```APIDOC ## Window Generation ### `hannwin(l)` - **Description**: Generates a Hann window of length `l`. - **Parameters**: - `l` (int): The length of the window. - **Returns**: A Hann window. ### `blackharr(n, l=None, mod=True)` - **Description**: Generates a Blackman-Harris window. - **Parameters**: - `n` (int): The number of terms. - `l` (int, optional): The length of the window. Defaults to None. - `mod` (bool, optional): Whether to use the modified version. Defaults to True. - **Returns**: A Blackman-Harris window. ### `blackharrcw(bandwidth, corr_shift)` - **Description**: Generates a complex-weighted Blackman-Harris window. - **Parameters**: - `bandwidth` (float): The bandwidth. - `corr_shift` (int): The correlation shift. - **Returns**: A complex-weighted Blackman-Harris window. ### `cont_tukey_win(n, sl_len, tr_area)` - **Description**: Generates a continuous Tukey window. - **Parameters**: - `n` (int): The number of samples. - `sl_len` (int): The slice length. - `tr_area` (float): The transition area. - **Returns**: A Tukey window. ### `tgauss(ess_ln, ln=0)` - **Description**: Generates a truncated Gaussian window. - **Parameters**: - `ess_ln` (int): The effective signal length. - `ln` (int, optional): The length. Defaults to 0. - **Returns**: A truncated Gaussian window. ``` -------------------------------- ### Scale Constructor Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-scales.md Initializes a Scale object, which represents a distribution of frequency bands. The number of bands is a key parameter. ```APIDOC ## Scale Constructor ### Description Initializes a Scale object with a specified number of frequency bands. ### Method ```python Scale(bnds) ``` ### Parameters #### Path Parameters - **bnds** (int) - Yes - Number of frequency bands. ``` -------------------------------- ### Configuration Objects for State Management Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/architecture.md Scale and NSGT objects encapsulate frequency distribution and transform state, respectively. Initialization is clean, allowing users to create an NSGT object and then use its forward/backward methods. ```text - Scale objects encapsulate frequency distribution logic. - NSGT objects encapsulate all transform state (windows, parameters). - Clean initialization: `NSGT(scale, fs, Ls, ...)` then use `.forward()` / `.backward()`. ``` -------------------------------- ### OctScale Constructor Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-scales.md Initializes an OctScale object to create a constant-Q frequency scale. It divides each octave into `bpo` bands, ensuring a consistent frequency ratio between adjacent bands. ```APIDOC ## OctScale Constructor ### Description Creates a constant-Q scale where frequency bands are logarithmically spaced. Each octave is divided into `bpo` bands, so the frequency ratio between adjacent bands is 2^(1/bpo). All bands have the same Q-factor, matching human auditory perception. ### Method Signature ```python OctScale(fmin, fmax, bpo, beyond=0) ``` ### Parameters #### Path Parameters - **fmin** (float) - Required - Minimum frequency in Hz. Must be > 0. - **fmax** (float) - Required - Maximum frequency in Hz. Must be > fmin. - **bpo** (int) - Required - Bins per octave. Standard values: 12 (semitone), 24 (quarter-tone), 36 (sixth-tone). Must be > 0. - **beyond** (int) - Optional - Number of extra bands below fmin and above fmax. Integer >= 0. Defaults to 0. ### Constructor Attributes - **bnds** (int) - Total number of bands (including beyond bands). - **fmin** (float) - Adjusted minimum frequency after adding beyond bands. - **fmax** (float) - Adjusted maximum frequency after adding beyond bands. - **pow2n** (float) - Frequency ratio per band = 2^(1/bpo). - **q** (float) - Constant Q-factor for all bands. Depends only on bpo, not on frequencies. ### Example ```python from nsgt import OctScale, NSGT import numpy as np # Musical scale: A0 (27.5 Hz) to C8 (4186 Hz), 12 semitones/octave scale = OctScale(27.5, 4186, bpo=12) freqs, q = scale() print(f"Bands: {len(freqs)}") print(f"Octaves: {np.log2(freqs[-1]/freqs[0]):.1f}") # Use in transform nsgt = NSGT(scale, fs=44100, Ls=44100, real=True) signal = np.random.randn(44100) cofs = nsgt.forward(signal) ``` ``` -------------------------------- ### OctScale Constructor and Usage Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-scales.md Instantiate OctScale for a musical scale and use it within an NSGT transform. Requires importing OctScale, NSGT, and numpy. ```python from nsgt import OctScale, NSGT import numpy as np # Musical scale: A0 (27.5 Hz) to C8 (4186 Hz), 12 semitones/octave scale = OctScale(27.5, 4186, bpo=12) freqs, q = scale() print(f"Bands: {len(freqs)}") print(f"Octaves: {np.log2(freqs[-1]/freqs[0]):.1f}") # Use in transform nsgt = NSGT(scale, fs=44100, Ls=44100, real=True) signal = np.random.randn(44100) coefs = nsgt.forward(signal) ``` -------------------------------- ### CQ_NSGT_sliced Constructor Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-sliced.md Initializes the CQ_NSGT_sliced object with specified parameters for Constant-Q Non-Stationary Gabor Transform. Key parameters include frequency range, bins per octave, slice length, transition area, and sampling frequency. ```python CQ_NSGT_sliced(fmin, fmax, bins, sl_len, tr_area, fs, min_win=16, Qvar=1, real=False, recwnd=False, matrixform=False, reducedform=0, multichannel=False, measurefft=False, multithreading=False) ``` -------------------------------- ### Define nsgfwin() Primary Version Parameters Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-transforms.md Defines the parameters for the primary version of the nsgfwin function, including frequency, Q-factors, sample rate, signal length, and windowing options. ```python def nsgfwin(f, q, sr, Ls, sliced=True, min_win=4, Qvar=1, dowarn=True, dtype=np.float64): ... ``` -------------------------------- ### chkM() Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-utility.md Ensures that the hop sizes (M) are provided as an array and match the number of windows. ```APIDOC ## chkM() ### Description Ensures M (hop sizes) is an array matching window count. ### Method Signature ```python def chkM(M: ndarray | int | None, g: list[ndarray]) ``` ### Parameters #### Path Parameters - **M** (ndarray, int, or None) - Required - Hop sizes. If None, inferred from window lengths. If scalar, broadcast to all windows. If ndarray, returned as-is (after validation). - **g** (list of ndarray) - Required - Window list (to determine number of bands). ### Return Type `ndarray` ### Description Returns an ndarray of length len(g) with hop sizes. If M is None, uses len(gii) for each window. If M is scalar, broadcasts to all windows. Validates that result matches window count. ### Example ```python from nsgt.util import chkM import numpy as np g = [np.ones(512), np.ones(1024), np.ones(512)] M = chkM(None, g) print(M) # [512 1024 512] M = chkM(128, g) print(M) # [128 128 128] ``` ``` -------------------------------- ### nsgfwin() - Primary Version Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-transforms.md Computes window functions and transform parameters for sliced or standard transforms. This is the recommended version for most use cases. ```APIDOC ## nsgfwin() - Primary Version ### Description Computes window functions and transform parameters for sliced or standard transforms. Validates Q-factors, creates windows using hannwin() or blackharr() depending on sliced flag. Windows are already in frequency domain (FFT-shifted). ### Method `nsgfwin(f, q, sr, Ls, sliced=True, min_win=4, Qvar=1, dowarn=True, dtype=np.float64)` ### Parameters #### Path Parameters - **f** (ndarray) - Required - Center frequencies in Hz. Length equals number of bands. - **q** (ndarray) - Required - Q-factors for each frequency. Same length as f. - **sr** (int) - Required - Sample rate in Hz. - **Ls** (int) - Required - Signal or slice length in samples. - **sliced** (bool) - Optional - If True, generates windows for sliced transform. If False, standard windows. Default: True. - **min_win** (int) - Optional - Minimum window length in samples. Prevents collapse at low frequencies. Default: 4. - **Qvar** (float) - Optional - Q-factor variation multiplier. > 1 widens windows, < 1 narrows windows. Default: 1. - **dowarn** (bool) - Optional - If True, warns when Q-factor exceeds recommended maximum. Default: True. - **dtype** (numpy.dtype) - Optional - Data type for window functions. Default: np.float64. ### Return Type `tuple of (list, ndarray, ndarray)` - First element: g, list of window functions (one per band). - Second element: rfbas, reference frequency positions in samples. - Third element: M, hop sizes for each band. ### Request Example ```python from nsgt.nsgfwin_sl import nsgfwin import numpy as np f = np.array([100, 200, 400, 800, 1600]) # Hz q = np.ones_like(f) * 10 # Constant Q g, rfbas, M = nsgfwin(f, q, sr=44100, Ls=44100, sliced=False) print(f"Bands: {len(g)}") print(f"Hop sizes: {M}") print(f"Window lengths: {[len(gi) for gi in g]}") ``` ### Raises `ValueError` — if beyond-band adjustment causes fmin <= 0. ``` -------------------------------- ### cont_tukey_win() Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-utility.md Generates a continuous Tukey window (tapered cosine window) with specified output length, slice length, and transition area. ```APIDOC ## cont_tukey_win(n, sl_len, tr_area) ### Description Generates a continuous Tukey window (tapered cosine window) with specified output length, slice length, and transition area. ### Parameters #### Path Parameters - **n** (int) - Required - Number of samples in output. - **sl_len** (int) - Required - Slice length (controls flat region width). - **tr_area** (int) - Required - Transition area width (controls taper width). ### Return Type `ndarray` (dtype: float64) ### Description Creates a window that is zero outside [sl_len/4 - tr_area/2, 3*sl_len/4 + tr_area/2], flat (1.0) in the middle region, and has cosine tapers in the transition areas. Used internally for slicing. ### Example ```python from nsgt.util import cont_tukey_win import numpy as np win = cont_tukey_win(n=4096, sl_len=4096, tr_area=512) print(f"Min: {win.min():.2f}, Max: {win.max():.2f}") print(f"Flat region: {np.count_nonzero(win >= 0.99)}") ``` ``` -------------------------------- ### Window Generation Pipeline Overview Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/architecture.md The nsgfwin function processes frequencies and Q-factors to generate window functions, reference positions, and hop sizes. It includes validation, frequency basis extension, window length computation, and window function generation (Blackman-Harris or Hanning). ```text nsgfwin() [in nsgfwin_sl.py] or nsgfwin() [in nsgfwin.py] | +→ Input: frequencies (f), Q-factors (q), sample rate, signal length | +→ Validate: Q-factors not too high (warn if exceed maximum) | +→ Create frequency basis: | - Extended with DC (f=0) and Nyquist (f=sr/2) | - Extended with mirror frequencies (negative frequencies for real signals) | +→ Compute window lengths (M): | For each band: M[i] = length such that bandwidth = f[i] / q[i] | Clip to min_win (prevent collapse) | +→ Generate window functions: | - Sliced=True: blackharr() windows (Blackman-Harris) | - Sliced=False: hannwin() windows (Hanning) | Already FFT-shifted to frequency domain representation | +→ Compute reference frequency positions (rfbas): | Maps frequency bins to time-domain sample positions | Output: (g, rfbas, M) - g: List of window functions (frequency domain) - rfbas: Reference positions in samples - M: Hop sizes in samples ``` -------------------------------- ### Q() Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-scales.md Computes the Q-factors (frequency divided by bandwidth) for specified bands. This is useful for understanding the frequency resolution at different points in the scale. ```APIDOC ## Q() ### Description Returns Q-factors (frequency / bandwidth) for specified bands. ### Method ```python def Q(self, bnd=None): ... ``` ### Parameters #### Path Parameters - **bnd** (int or ndarray) - No - Band index or array of indices. If None, returns all bands. ### Return Type `float or ndarray` - Same shape as output of F(bnd). ``` -------------------------------- ### CQ_NSGT_sliced Constructor Source: https://github.com/grrrr/nsgt/blob/master/_autodocs/api-reference-sliced.md Initializes the CQ_NSGT_sliced object with specified parameters for constant-Q transform analysis. ```APIDOC ## CQ_NSGT_sliced Constructor ### Description Initializes the CQ_NSGT_sliced object with specified parameters for constant-Q transform analysis. ### Method Signature ```python CQ_NSGT_sliced(fmin, fmax, bins, sl_len, tr_area, fs, min_win=16, Qvar=1, real=False, recwnd=False, matrixform=False, reducedform=0, multichannel=False, measurefft=False, multithreading=False) ``` ### Parameters #### Constructor Parameters - **fmin** (float) - Required - Minimum frequency in Hz. Must be > 0. - **fmax** (float) - Required - Maximum frequency in Hz. Must be > fmin. - **bins** (int) - Required - Bins per octave. Must be > 0. - **sl_len** (int) - Required - Slice length in samples. Must be divisible by 4. - **tr_area** (int) - Required - Transition area width. Must be even. - **fs** (int) - Required - Sampling frequency in Hz. Must be > 0. - **min_win** (int) - Optional - Minimum window length in samples. Defaults to 16. - **Qvar** (float) - Optional - Q-factor variation multiplier. Defaults to 1. - **real** (bool) - Optional - Real signal flag. Defaults to False. - **recwnd** (bool) - Optional - Reconstruction windowing flag. Defaults to False. - **matrixform** (bool) - Optional - Uniform time divisions flag. Defaults to False. - **reducedform** (int) - Optional - Real signal reduction level (0-2). Defaults to 0. - **multichannel** (bool) - Optional - Multi-channel flag. Defaults to False. - **measurefft** (bool) - Optional - FFT measurement flag. Defaults to False. - **multithreading** (bool) - Optional - Parallel processing flag. Defaults to False. ### Constructor Attributes - **fmin** (float) - Minimum frequency in Hz. - **fmax** (float) - Maximum frequency in Hz. - **bins** (int) - Bins per octave. ### Example ```python from nsgt import CQ_NSGT_sliced import numpy as np # Musical constant-Q analysis cq_sl = CQ_NSGT_sliced(fmin=27.5, fmax=4186, bins=12, sl_len=8192, tr_area=1024, fs=44100, real=True) def audio_stream(): for i in range(100): yield np.random.randn(8192) coef_stream = cq_sl.forward(audio_stream()) recon_stream = cq_sl.backward(coef_stream) first_slice = next(recon_stream) ``` ```