### Install PyTorch Wavelets from Source Source: https://github.com/tomrunia/pytorchwavelets/blob/master/README.md Instructions for cloning the repository, navigating to the directory, installing dependencies, and setting up the package locally. ```sh git clone https://github.com/tomrunia/PyTorchWavelets.git cd PyTorchWavelets pip install -r requirements.txt python setup.py install ``` -------------------------------- ### Generate and Plot Scalogram with PyTorch Wavelets Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt This example demonstrates how to generate a scalogram from a noisy sinusoidal signal using `WaveletTransformTorch` and plot it. It includes signal generation, CWT power calculation, and visualization with a clear indication of the expected frequency. ```python f0 = 2.0 signal = np.sin(2 * np.pi * f0 * t) + np.random.normal(0, 0.2, len(t)) batch = signal[None, :] # shape (1, signal_length) wa = WaveletTransformTorch(dt=dt, dj=dj, wavelet=Morlet(), cuda=False) power = wa.power(batch) # shape (1, n_scales, signal_length) fig, axes = plt.subplots(1, 2, figsize=(12, 4)) # Plot raw signal axes[0].plot(t, signal) axes[0].set_title("Input Signal") axes[0].set_xlabel("Time (s)") # Plot scalogram for the single signal (squeeze batch dim) plot_scalogram( power[0], # [n_scales, signal_length] wa.fourier_periods, # y-axis: equivalent Fourier period t, # x-axis: time normalize_columns=True, # normalize power per time step cmap=plt.get_cmap("hot_r"), ax=axes[1], scale_legend=True ) # Mark expected period axes[1].axhline(1.0 / f0, lw=1.5, color='cyan', linestyle='--', label=f'f={f0} Hz') axes[1].legend() plt.tight_layout() plt.savefig("scalogram.png", dpi=150) plt.show() ``` -------------------------------- ### Instantiate and Use Morlet Wavelet Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Demonstrates how to instantiate the Morlet wavelet with a specified frequency and use its methods to compute time-domain values, Fourier periods, and scales. The Morlet wavelet is the default and offers good frequency resolution. ```python from wavelets_pytorch.wavelets import Morlet import numpy as np morlet = Morlet(w0=6) # w0: nondimensional frequency; recommended >= 5 t = np.linspace(-5, 5, 200) values = morlet.time(t, s=1.0) # complex ndarray period = morlet.fourier_period(s=2.0) # equivalent Fourier period scale = morlet.scale_from_period(period) print(f"Morlet fourier_period(s=2): {period:.4f}, back to scale: {scale:.4f}") ``` -------------------------------- ### Initialize and Use Wavelet Transforms in PyTorch Source: https://github.com/tomrunia/pytorchwavelets/blob/master/README.md Demonstrates initializing both SciPy and PyTorch versions of the Wavelet Transform and performing CWT on a batch of signals. The PyTorch version requires `cuda=True` for GPU acceleration. Note that the `cwt` method expects signal batches of shape `[num_signals, signal_length]`. ```python import numpy as np from wavelets_pytorch.transform import WaveletTransform # SciPy version from wavelets_pytorch.transform import WaveletTransformTorch # PyTorch version dt = 0.1 # sampling frequency dj = 0.125 # scale distribution parameter batch_size = 32 # how many signals to process in parallel # Batch of signals to process batch = [batch_size x signal_length] # Initialize wavelet filter banks (scipy and torch implementation) wa_scipy = WaveletTransform(dt, dj) wa_torch = WaveletTransformTorch(dt, dj, cuda=True) # Performing wavelet transform (and compute scalogram) cwt_scipy = wa_scipy.cwt(batch) cwt_torch = wa_torch.cwt(batch) # For plotting, see the examples/plot.py function. # ... ``` -------------------------------- ### Instantiate and Use Paul Wavelet Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Shows how to create a Paul wavelet, which offers good time resolution, and compute its Fourier period. The 'm' parameter controls the order of the wavelet. ```python from wavelets_pytorch.wavelets import Paul import numpy as np paul = Paul(m=4) # m: order t = np.linspace(-5, 5, 200) values_paul = paul.time(t, s=1.0) print("Paul fourier_period(s=1):", paul.fourier_period(s=1.0)) ``` -------------------------------- ### Using Ricker and Mexican_hat Aliases Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Demonstrates that Ricker and Mexican_hat are aliases for the DOG(m=2) wavelet, providing alternative ways to instantiate the same wavelet. ```python from wavelets_pytorch.wavelets import Ricker, Mexican_hat ricker = Ricker() # identical to DOG(m=2) marr = Mexican_hat() # same object ``` -------------------------------- ### Compute Wavelet Transform Scales and Frequencies Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Demonstrates how to use the WaveletTransformBase class (accessible via WaveletTransform instances) to compute optimal scales, minimum scale, and corresponding Fourier periods and frequencies for a given transform configuration. ```python import numpy as np from wavelets_pytorch.transform import WaveletTransform from wavelets_pytorch.wavelets import Morlet wa = WaveletTransform(dt=0.05, dj=0.125, wavelet=Morlet()) wa.signal_length = 200 print("Scales:", wa.scales) # shape (n_scales,) print("Min scale:", wa.scales[0]) print("Max scale:", wa.scales[-1]) s_min = wa.compute_minimum_scale() print("Minimum scale:", s_min) print("Fourier periods:", wa.fourier_periods) # shape (n_scales,) print("Fourier frequencies:", wa.fourier_frequencies) ``` -------------------------------- ### Available Mother Wavelet Classes Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Instantiate any of these wavelet classes to use as the `wavelet` argument in transform classes. Each provides time/frequency domain forms, scale/period conversions, and cone-of-influence calculations. ```python from wavelets_pytorch.wavelets import Morlet, Paul, DOG, Ricker, Mexican_hat import numpy as np ``` -------------------------------- ### Build and Use TorchFilterBank with Real Filters Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Demonstrates the creation of a TorchFilterBank using a list of real-valued filters. This module acts as a low-level nn.Module storing Conv1d layers for wavelet scales and can be used in custom PyTorch models. ```python import numpy as np import torch from wavelets_pytorch.network import TorchFilterBank np.random.seed(42) n_scales = 10 filters = [np.random.randn(11 + 2 * i).astype(np.float32) for i in range(n_scales)] bank = TorchFilterBank(filters=filters, cuda=False) batch_size, signal_length = 4, 128 x = torch.randn(batch_size, 1, signal_length) output = bank(x) print("FilterBank output shape:", output.shape) ``` -------------------------------- ### Instantiate and Use DOG Wavelet Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Illustrates the creation of a Derivative of Gaussian (DOG) wavelet, which is a real-valued wavelet. The 'm' parameter determines the order, with m=2 corresponding to the Mexican Hat wavelet. ```python from wavelets_pytorch.wavelets import DOG import numpy as np dog = DOG(m=2) # m=2 is the Mexican Hat / Ricker wavelet t = np.linspace(-5, 5, 200) values_dog = dog.time(t, s=1.0) print("DOG fourier_period(s=1):", dog.fourier_period(s=1.0)) ``` -------------------------------- ### Build and Use TorchFilterBank with Complex Filters Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Illustrates creating a TorchFilterBank with complex-valued filters. Complex filters result in two output channels per scale (real and imaginary parts). ```python import numpy as np import torch from wavelets_pytorch.network import TorchFilterBank complex_filters = [ (np.random.randn(15 + 2*i) + 1j * np.random.randn(15 + 2*i)).astype(np.complex128) for i in range(n_scales) ] bank_complex = TorchFilterBank(filters=complex_filters, cuda=False) batch_size, signal_length = 4, 128 x = torch.randn(batch_size, 1, signal_length) output_complex = bank_complex(x) print("Complex FilterBank output shape:", output_complex.shape) ``` -------------------------------- ### Update Filters in TorchFilterBank Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Shows how to update the filters within an existing TorchFilterBank instance in-place using the `set_filters` method. This is automatically called when the signal length changes. ```python from wavelets_pytorch.network import TorchFilterBank import numpy as np # Assuming 'bank' is an existing TorchFilterBank instance # bank = TorchFilterBank(filters=..., cuda=False) new_filters = [np.random.randn(9 + 2 * i).astype(np.float32) for i in range(n_scales)] bank.set_filters(new_filters, padding_type='SAME') ``` -------------------------------- ### Perform CWT with Paul Wavelet Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Shows how to use a non-default wavelet (Paul) within the WaveletTransform for performing a Continuous Wavelet Transform. Requires specifying the time step (dt) and scale step (dj). ```python from wavelets_pytorch.transform import WaveletTransform from wavelets_pytorch.wavelets import Paul import numpy as np wa = WaveletTransform(dt=0.05, dj=0.125, wavelet=Paul(m=4)) batch = np.random.randn(8, 200) cwt = wa.cwt(batch) print("Paul CWT shape:", cwt.shape) # complex output ``` -------------------------------- ### Compute Unbiased Power Spectrum with WaveletTransform Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Explains how to compute the unbiased power spectrum using the `power` method of WaveletTransform. Setting `unbias=True` corrects for red-noise bias by dividing the squared CWT by the scale. ```python import numpy as np from wavelets_pytorch.transform import WaveletTransform wa_unbiased = WaveletTransform(dt=0.05, dj=0.125, unbias=True) batch = np.random.randn(8, 200) power_unbiased = wa_unbiased.power(batch) print("Unbiased power shape:", power_unbiased.shape) ``` -------------------------------- ### WaveletTransformTorch — GPU-Accelerated CWT Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Provides a PyTorch-based CWT implementation accelerated by `torch.nn.Conv1d`. It applies all scaled wavelet filters in a single forward pass on GPU, offering significant throughput gains for large batches. Results are returned as NumPy arrays. ```APIDOC ## WaveletTransformTorch — GPU-Accelerated CWT ### Description PyTorch-based CWT backed by `torch.nn.Conv1d`. All scaled wavelet filters are stored as non-trainable `nn.Conv1d` modules inside `TorchFilterBank`. The entire filter bank is applied in a single forward pass on GPU, giving large throughput gains for big batches. Results are returned as NumPy arrays so the API is identical to `WaveletTransform`. ### Method `WaveletTransformTorch(dt, dj, wavelet, unbias=False, cuda=True)` ### Parameters - **dt** (float) - Required - Sampling interval in seconds. - **dj** (float) - Required - Voice-per-octave (smaller values yield more scales). - **wavelet** (object) - Required - An instance of a mother wavelet class (e.g., `Morlet()`). - **unbias** (bool) - Optional - Whether to unbias the power spectrum. Defaults to `False`. - **cuda** (bool) - Optional - Whether to use GPU acceleration. Defaults to `True`. ### Methods - **cwt(batch)**: Computes the Continuous Wavelet Transform (CWT) for a given batch of signals. - **batch** (numpy.ndarray) - Input signals, shape `[n_batch, signal_length]` or `[signal_length]`. - Returns: `numpy.ndarray` - The CWT of the input signals, shape `[n_batch, n_scales, signal_length]` or `[n_scales, signal_length]`. - **power(batch)**: Computes the power spectrum (scalogram) of the input signals. - **batch** (numpy.ndarray) - Input signals, shape `[n_batch, signal_length]` or `[signal_length]`. - Returns: `numpy.ndarray` - The power spectrum, shape `[n_batch, n_scales, signal_length]` or `[n_scales, signal_length]`. ### Properties - **scales**: `numpy.ndarray` - The computed scales for the transform. - **fourier_periods**: `list` - Equivalent Fourier periods for each scale. ### Request Example ```python import numpy as np from wavelets_pytorch.transform import WaveletTransformTorch from wavelets_pytorch.wavelets import Morlet dt = 0.05 dj = 0.125 batch_size = 64 t = np.linspace(0, 10.0, int(10.0 / dt)) frequencies = np.random.uniform(0.5, 4.0, size=batch_size) batch = np.array([np.sin(2 * np.pi * f * t) for f in frequencies]) batch += np.random.normal(0, 0.1, batch.shape) wa_torch = WaveletTransformTorch(dt=dt, dj=dj, wavelet=Morlet(), unbias=False, cuda=True) cwt = wa_torch.cwt(batch) power = wa_torch.power(batch) print("CWT shape:", cwt.shape) print("Power shape:", power.shape) new_batch = np.random.randn(64, 500) cwt_new = wa_torch.cwt(new_batch) print("New CWT shape:", cwt_new.shape) ``` ### Response Example ``` CWT shape: (64, n_scales, 200) Power shape: (64, n_scales, 200) New CWT shape: (64, n_scales_new, 500) ``` ``` -------------------------------- ### SciPy CWT with WaveletTransform Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Use WaveletTransform for CPU-only CWT. The filter bank is built on the first call. Supports batch processing of 1D signals. ```python import numpy as np from wavelets_pytorch.transform import WaveletTransform from wavelets_pytorch.wavelets import Morlet # Parameters dt = 0.05 # sampling interval (seconds) dj = 0.125 # voice-per-octave (smaller = more scales) batch_size = 16 signal_length = 200 # samples # Generate a batch of sinusoidal signals at random frequencies t = np.linspace(0, signal_length * dt, signal_length) frequencies = np.random.uniform(0.5, 4.0, size=batch_size) batch = np.array([np.sin(2 * np.pi * f * t) for f in frequencies]) # batch.shape => (16, 200) # Initialize the SciPy wavelet transform wa = WaveletTransform(dt=dt, dj=dj, wavelet=Morlet(), unbias=False) # Compute CWT — filter bank is built automatically on first call cwt = wa.cwt(batch) # cwt.shape => (16, n_scales, 200), dtype=np.complex128 # Compute power spectrum (scalogram) |CWT|^2 power = wa.power(batch) # power.shape => (16, n_scales, 200), dtype=np.float64 print("Scales:", wa.scales.shape) # (n_scales,) print("Fourier periods:", wa.fourier_periods) # equivalent periods for each scale print("CWT shape:", cwt.shape) print("Power shape:", power.shape) # Single signal (no batch dimension) — batch dim is auto-squeezed single = np.sin(2 * np.pi * 2.0 * t) cwt_single = wa.cwt(single) # cwt_single.shape => (n_scales, 200) ``` -------------------------------- ### GPU-Accelerated CWT with WaveletTransformTorch Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Use WaveletTransformTorch for GPU-accelerated CWT via `torch.nn.Conv1d`. Handles batch processing and returns NumPy arrays. The filter bank is reset if signal length changes. ```python import numpy as np from wavelets_pytorch.transform import WaveletTransformTorch from wavelets_pytorch.wavelets import Morlet dt = 0.05 dj = 0.125 batch_size = 64 t = np.linspace(0, 10.0, int(10.0 / dt)) frequencies = np.random.uniform(0.5, 4.0, size=batch_size) batch = np.array([np.sin(2 * np.pi * f * t) for f in frequencies]) # Add noise batch += np.random.normal(0, 0.1, batch.shape) # Initialize PyTorch transform — set cuda=False if no GPU is available wa_torch = WaveletTransformTorch(dt=dt, dj=dj, wavelet=Morlet(), unbias=False, cuda=True) # CWT: internally converts to FloatTensor, moves to GPU, returns np.ndarray cwt = wa_torch.cwt(batch) # cwt.shape => (64, n_scales, 200), dtype=np.complex128 # Power spectrum power = wa_torch.power(batch) # power.shape => (64, n_scales, 200), dtype=np.float64 print("CWT shape:", cwt.shape) print("Power shape:", power.shape) # Changing signal length resets the filter bank automatically new_batch = np.random.randn(64, 500) cwt_new = wa_torch.cwt(new_batch) print("New CWT shape:", cwt_new.shape) # (64, n_scales_new, 500) ``` -------------------------------- ### Wavelet Classes Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Available mother wavelet classes that can be passed to the transform classes. Each class provides methods for time-domain and frequency-domain representations, scale-frequency conversions, and cone-of-influence calculations. ```APIDOC ## Wavelet Classes — Mother Wavelets ### Description Five mother wavelets are available. Each class exposes `time(t, s)` for the time-domain form, `frequency(w, s)` for the Fourier form, `fourier_period(s)` and `scale_from_period(period)` for scale↔frequency conversion, and `coi(s)` for the cone-of-influence e-folding time. Pass any instance as the `wavelet` argument to either transform class. ### Available Wavelets - **Morlet** - **Paul** - **DOG** (Difference of Gaussians) - **Ricker** - **Mexican_hat** ### Usage Example ```python from wavelets_pytorch.wavelets import Morlet, Paul, DOG, Ricker, Mexican_hat import numpy as np # Instantiate a wavelet morlet_wavelet = Morlet() # Example parameters t = np.linspace(-5, 5, 100) # Time vector s = 1.0 # Scale w = np.linspace(-10, 10, 100) # Frequency vector period = 2 * np.pi # Fourier period # Get time-domain form psi_t = morlet_wavelet.time(t, s) # Get frequency-domain form psi_f = morlet_wavelet.frequency(w, s) # Get Fourier period for a scale fourier_p = morlet_wavelet.fourier_period(s) # Convert period to scale scale_from_p = morlet_wavelet.scale_from_period(period) # Get cone-of-influence e-folding time coi_time = morlet_wavelet.coi(s) print(f"Morlet time shape: {psi_t.shape}") print(f"Morlet frequency shape: {psi_f.shape}") print(f"Fourier period for scale {s}: {fourier_p}") print(f"Scale for period {period}: {scale_from_p}") print(f"COI time for scale {s}: {coi_time}") ``` ``` -------------------------------- ### Dynamically Change dt in WaveletTransform Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Illustrates how changing the `dt` (time step) parameter of a WaveletTransform instance automatically rebuilds the internal filter bank and updates the scales. ```python from wavelets_pytorch.transform import WaveletTransform # Assuming 'wa' is an existing WaveletTransform instance # wa = WaveletTransform(dt=0.05, dj=0.125, wavelet=Morlet()) wa.dt = 0.1 print("New scales after dt change:", wa.scales.shape) ``` -------------------------------- ### WaveletTransform — SciPy CWT Source: https://context7.com/tomrunia/pytorchwavelets/llms.txt Provides a SciPy-based continuous wavelet transform implementation. It iterates over signals sequentially, convolving each with scaled wavelet filters. This is suitable for CPU-only environments or as a reference baseline. ```APIDOC ## WaveletTransform — SciPy CWT ### Description SciPy-based continuous wavelet transform. Iterates over signals in the batch sequentially, convolving each with every scaled wavelet filter via `scipy.signal.convolve(..., mode='same')`. Suitable for CPU-only environments or as a reference baseline. ### Method `WaveletTransform(dt, dj, wavelet, unbias=False)` ### Parameters - **dt** (float) - Required - Sampling interval in seconds. - **dj** (float) - Required - Voice-per-octave (smaller values yield more scales). - **wavelet** (object) - Required - An instance of a mother wavelet class (e.g., `Morlet()`). - **unbias** (bool) - Optional - Whether to unbias the power spectrum. Defaults to `False`. ### Methods - **cwt(batch)**: Computes the Continuous Wavelet Transform (CWT) for a given batch of signals. - **batch** (numpy.ndarray) - Input signals, shape `[n_batch, signal_length]` or `[signal_length]`. - Returns: `numpy.ndarray` - The CWT of the input signals, shape `[n_batch, n_scales, signal_length]` or `[n_scales, signal_length]`. - **power(batch)**: Computes the power spectrum (scalogram) of the input signals. - **batch** (numpy.ndarray) - Input signals, shape `[n_batch, signal_length]` or `[signal_length]`. - Returns: `numpy.ndarray` - The power spectrum, shape `[n_batch, n_scales, signal_length]` or `[n_scales, signal_length]`. ### Properties - **scales**: `numpy.ndarray` - The computed scales for the transform. - **fourier_periods**: `list` - Equivalent Fourier periods for each scale. ### Request Example ```python import numpy as np from wavelets_pytorch.transform import WaveletTransform from wavelets_pytorch.wavelets import Morlet dt = 0.05 dj = 0.125 batch_size = 16 signal_length = 200 t = np.linspace(0, signal_length * dt, signal_length) frequencies = np.random.uniform(0.5, 4.0, size=batch_size) batch = np.array([np.sin(2 * np.pi * f * t) for f in frequencies]) wa = WaveletTransform(dt=dt, dj=dj, wavelet=Morlet(), unbias=False) cwt = wa.cwt(batch) power = wa.power(batch) print("Scales:", wa.scales.shape) print("Fourier periods:", wa.fourier_periods) print("CWT shape:", cwt.shape) print("Power shape:", power.shape) single = np.sin(2 * np.pi * 2.0 * t) cwt_single = wa.cwt(single) print("Single CWT shape:", cwt_single.shape) ``` ### Response Example ``` Scales: (n_scales,) Fourier periods: [...] CWT shape: (16, n_scales, 200) Power shape: (16, n_scales, 200) Single CWT shape: (n_scales, 200) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.