### Generating a Scaleogram with Scaleogram Library Source: https://github.com/alsauve/scaleogram/blob/master/doc/scale-to-frequency.ipynb This example demonstrates how to generate a Continuous Wavelet Transform (CWT) scaleogram for a synthetic signal composed of two cosine waves with different periods. It uses the scaleogram library's cws function to visualize the time-frequency representation. Requires numpy, matplotlib, and scaleogram libraries. ```python import numpy as np import matplotlib.pyplot as plt n = 300 time = np.arange(n) p1 = 20; f1 = 1./p1 p2 = 60; f2 = 1./p2 data = np.cos( (2*np.pi*f1) * time) + 0.6*np.cos( (2*np.pi*f2) * time) wavelet='cmor0.7-1.5' fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(14, 6)) fig.subplots_adjust(hspace=0.3) ax1.plot(time, data); ax1.set_xlim(0, n) ax1.set_title('Example 1: time domain signal with two cos() waves with period p1=%ds and p2=%ds'%(p1,p2)) ax2 = scg.cws(time, data, scales=np.arange(1, 150), wavelet=wavelet, ax=ax2, cmap="jet", cbar=None, ylabel="Period [seconds]", xlabel="Time [seconds]", title='Example 1: scaleogram with linear period yscale') txt = ax2.annotate("p1=%ds" % p1, xy=(n/2,p1), xytext=(n/2-10, p1), bbox=dict(boxstyle="round4", fc="w")) txt = ax2.annotate("p2=%ds" % p2, xy=(n/2,p2), xytext=(n/2-10, p2), bbox=dict(boxstyle="round4", fc="w")) ``` -------------------------------- ### Prepare Time Series Data Source: https://github.com/alsauve/scaleogram/blob/master/doc/El-Nino-Dataset.ipynb Extracts the data values from the DataFrame and creates a time array based on the start year and sampling interval. ```python data = nino3.values.squeeze() N = data.size; print("Nb of samples of data:", N) t0 = 1871; dt = 0.25 year = t0 + np.arange(len(data))*dt ``` -------------------------------- ### Initialize Scaleogram Environment Source: https://github.com/alsauve/scaleogram/blob/master/doc/tests.ipynb Imports necessary libraries including scaleogram, matplotlib, and seaborn. It verifies the current version of the scaleogram library and the Python environment. ```python import matplotlib.pyplot as plt %matplotlib inline import scaleogram as scg import seaborn as sns import sys print("TEST notebook for scaleogram version="+scg.__version__+ " python version="+sys.version) ``` -------------------------------- ### Load NINO3.4 Dataset Source: https://github.com/alsauve/scaleogram/blob/master/doc/El-Nino-Dataset.ipynb Imports necessary libraries and loads the NINO3.4 SST dataset from a remote source into a pandas DataFrame. ```python import pandas as pd import numpy as np import scaleogram as scg nino3 = "http://paos.colorado.edu/research/wavelets/wave_idl/sst_nino3.dat" nino3 = pd.read_table(nino3) ``` -------------------------------- ### Handling Data Gaps and Extinction Source: https://github.com/alsauve/scaleogram/blob/master/doc/scale-to-frequency.ipynb Shows how to process signals with missing data (holes) and amplitude ramps to observe their effects on the resulting scaleogram, such as aliasing. ```python data2 = data data2[50:80] = 0 data2[150:n] *= np.arange(n-150, 0, -1)/(n-150) fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(14, 6)) fig.subplots_adjust(hspace=0.3) ax1.plot(time, data2); ax1.set_xlim(0, n) ax1.set_title('Example 2: adding a hole and extinction in the data stream') ax2 = scg.cws(time, data2, scales=np.arange(1, 150, 2), wavelet=wavelet, ax=ax2, cmap="jet", cbar=None, ylabel="Period [seconds]", xlabel="Time [seconds]", title="Example 3 : effect of hole and extinctin in the data [wavelet="+wavelet+"]") ``` -------------------------------- ### Visualize Available Wavelets with plot_wavelets Source: https://context7.com/alsauve/scaleogram/llms.txt Displays a grid of continuous wavelets available in PyWavelets. It supports plotting all wavelets or a specific subset to verify wavelet shapes. ```python import scaleogram as scg from scaleogram.wfun import plot_wavelets, WAVLIST import matplotlib.pyplot as plt # List available wavelets print("Available continuous wavelets:") for wav in WAVLIST: print(f" {wav}") # Plot all wavelets in a grid plot_wavelets(figsize=(14, 10)) plt.suptitle('Continuous Wavelet Gallery', y=1.02) plt.tight_layout() plt.show() # Plot subset of wavelets selected = ['cmor1.5-1.0 : Complex Morlet', 'mexh : Mexican hat', 'morl : Morlet'] plot_wavelets(wavlist=selected, figsize=(12, 4)) plt.show() ``` -------------------------------- ### Adjusting Bandwidth Parameter Source: https://github.com/alsauve/scaleogram/blob/master/doc/scale-to-frequency.ipynb Demonstrates how to modify the bandwidth parameter of a wavelet to control the sensitivity and smoothing on the period axis. ```python wavelet2 = 'cmor3-1.5' ax3 = scg.cws(time, data, scales=np.arange(1, 150, 2), wavelet=wavelet2, figsize=(14, 3), cmap="jet", cbar=None, ylabel="Period [seconds]", xlabel="Time [seconds]", title="Example 2 : effect of the bandwidth parameter $B$ after a *3 factor") ``` -------------------------------- ### Execute Visual Test Suite with test_cws Source: https://context7.com/alsauve/scaleogram/llms.txt Runs the built-in test suite to demonstrate various features and visualization configurations of the scaleogram library. ```python import scaleogram as scg # Run the full graphical test suite scg.test_cws() ``` -------------------------------- ### Visualize Wavelet Properties using plot_wav() Source: https://context7.com/alsauve/scaleogram/llms.txt The `plot_wav()` function and its variants (`plot_wav_time`, `plot_wav_freq`) visualize the time-domain and frequency-domain characteristics of a specified wavelet. This is useful for understanding wavelet behavior and selecting appropriate wavelets for analysis. Multiple wavelets can be compared. ```python import scaleogram as scg from scaleogram.wfun import plot_wav, plot_wav_time, plot_wav_freq import matplotlib.pyplot as plt # Plot default wavelet (time and frequency domains) ax1, ax2 = plot_wav('cmor1-1.5', figsize=(10, 4)) plt.tight_layout() plt.show() # Time domain only fig, ax = plt.subplots(figsize=(6, 4)) plot_wav_time('mexh', real=True, imag=True, ax=ax, legend=True) plt.title('Mexican Hat Wavelet - Time Domain') plt.show() # Frequency domain only fig, ax = plt.subplots(figsize=(6, 4)) plot_wav_freq('cgau5', ax=ax, yscale='linear', annotate=True) plt.title('Complex Gaussian (order 5) - Frequency Support') plt.show() # Compare multiple wavelets wavelets = ['cmor1-1.5', 'cgau5', 'mexh', 'morl'] fig, axes = plt.subplots(len(wavelets), 2, figsize=(10, 12)) for i, wav in enumerate(wavelets): plot_wav(wav, axes=(axes[i, 0], axes[i, 1]), legend=False, annotate=False) plt.tight_layout() plt.show() ``` -------------------------------- ### Run Scaleogram Diagnostic Tests Source: https://github.com/alsauve/scaleogram/blob/master/doc/tests.ipynb Configures matplotlib figure parameters and executes the built-in test suite. This generates various plots including wavelet domains and scaleograms for verification. ```python plt.rcParams['figure.figsize'] = [14,6] plt.rcParams['font.size'] = 14.0 scg.test_cws() ``` -------------------------------- ### plot_wav() - Visualize Wavelet Properties Source: https://context7.com/alsauve/scaleogram/llms.txt The plot_wav() function displays a wavelet's time-domain waveform and frequency-domain support, useful for understanding wavelet characteristics before analysis. ```APIDOC ## plot_wav() - Visualize Wavelet Properties ### Description The `plot_wav()` function displays a wavelet's time-domain waveform and frequency-domain support, useful for understanding wavelet characteristics before analysis. ### Method `scaleogram.wfun.plot_wav(wavelet, axes=None, figsize=(6, 4), real=False, imag=False, yscale='linear', annotate=False, legend=True)` `scaleogram.wfun.plot_wav_time(...)` `scaleogram.wfun.plot_wav_freq(...)` ### Parameters #### Path Parameters None #### Query Parameters - **wavelet** (str) - Required - The name of the wavelet to plot (e.g., 'cmor1-1.5', 'mexh'). - **axes** (tuple) - Optional - A tuple of two matplotlib axes objects (for time and frequency plots). - **figsize** (tuple) - Optional - Figure size for the plots. - **real** (bool) - Optional - Whether to plot the real part of the wavelet (for time domain). - **imag** (bool) - Optional - Whether to plot the imaginary part of the wavelet (for time domain). - **yscale** (str) - Optional - Y-axis scale for the frequency plot ('linear' or 'log'). - **annotate** (bool) - Optional - Whether to annotate frequency support. - **legend** (bool) - Optional - Whether to display the legend. ### Request Example ```python import scaleogram as scg from scaleogram.wfun import plot_wav, plot_wav_time, plot_wav_freq import matplotlib.pyplot as plt # Plot default wavelet (time and frequency domains) ax1, ax2 = plot_wav('cmor1-1.5', figsize=(10, 4)) plt.tight_layout() plt.show() # Time domain only fig, ax = plt.subplots(figsize=(6, 4)) plot_wav_time('mexh', real=True, imag=True, ax=ax, legend=True) plt.title('Mexican Hat Wavelet - Time Domain') plt.show() # Frequency domain only fig, ax = plt.subplots(figsize=(6, 4)) plot_wav_freq('cgau5', ax=ax, yscale='linear', annotate=True) plt.title('Complex Gaussian (order 5) - Frequency Support') plt.show() # Compare multiple wavelets wavelets = ['cmor1-1.5', 'cgau5', 'mexh', 'morl'] fig, axes = plt.subplots(len(wavelets), 2, figsize=(10, 12)) for i, wav in enumerate(wavelets): plot_wav(wav, axes=(axes[i, 0], axes[i, 1]), legend=False, annotate=False) plt.tight_layout() plt.show() ``` ### Response #### Success Response (200) - **plot_wav()**: Returns a tuple of two matplotlib axes objects (time and frequency). - **plot_wav_time()**: Returns a matplotlib axes object. - **plot_wav_freq()**: Returns a matplotlib axes object. #### Response Example (No direct JSON response, returns matplotlib plot objects) ``` -------------------------------- ### Configure Default Wavelet with set_default_wavelet() / get_default_wavelet() Source: https://context7.com/alsauve/scaleogram/llms.txt These functions manage the default wavelet used in scaleogram operations. `get_default_wavelet()` retrieves the currently set default, while `set_default_wavelet()` allows changing it. This simplifies CWT calls by eliminating the need to specify the wavelet repeatedly. ```python import scaleogram as scg # Get current default wavelet current = scg.get_default_wavelet() print(f"Default wavelet: {current}") # 'cmor1-1.5' # Set a different default wavelet scg.set_default_wavelet('cgau5') # Complex Gaussian, order 5 # All subsequent calls use new default import numpy as np signal = np.random.randn(256) scg.cws(signal, title="Using cgau5 wavelet") # Available continuous wavelets: # - 'cmor{B}-{C}' : Complex Morlet (B=bandwidth, C=center freq) # - 'cgau{N}' : Complex Gaussian derivative (N=order, 1-8) # - 'gaus{N}' : Gaussian derivative (N=order, 1-8) # - 'mexh' : Mexican Hat (Ricker wavelet) # - 'morl' : Morlet # - 'shan{B}-{C}' : Shannon (B=bandwidth, C=center freq) # - 'fbsp{M}-{B}-{C}' : Frequency B-Spline # Reset to recommended default scg.set_default_wavelet('cmor1-1.5') ``` -------------------------------- ### Visualize Available Wavelets Source: https://github.com/alsauve/scaleogram/blob/master/doc/tests.ipynb Calls the plot_wavelets function to generate a comprehensive visualization of available wavelets within the scaleogram library. ```python scg.plot_wavelets() ``` -------------------------------- ### Customize Cone of Influence (COI) Styling Source: https://context7.com/alsauve/scaleogram/llms.txt Shows how to toggle and style the Cone of Influence in scaleograms to highlight regions affected by boundary effects. ```python import scaleogram as scg import numpy as np import matplotlib.pyplot as plt signal = np.sin(2 * np.pi * np.arange(512) / 40) scales = np.arange(1, 100) fig, axes = plt.subplots(2, 2, figsize=(12, 8)) # Default COI scg.cws(signal, scales=scales, coi=True, ax=axes[0, 0], title='Default COI', cbar=None) # No COI scg.cws(signal, scales=scales, coi=False, ax=axes[0, 1], title='COI Disabled', cbar=None) # Custom COI styling scg.cws(signal, scales=scales, coi=True, ax=axes[1, 0], coikw={'alpha': 0.8, 'facecolor': 'white', 'hatch': '//'}, title='Custom COI (white fill)', cbar=None) # Pop-art style COI scg.cws(signal, scales=scales, coi=True, ax=axes[1, 1], coikw={'alpha': 0.7, 'facecolor': 'pink', 'edgecolor': 'purple', 'hatch': 'O', 'linewidth': 2}, title='Pop-art COI', cbar=None) plt.tight_layout() plt.show() ``` -------------------------------- ### fastcwt() - Fast Continuous Wavelet Transform Source: https://context7.com/alsauve/scaleogram/llms.txt The fastcwt() function provides an optimized CWT implementation using FFT-based convolution, offering significant speedup (up to 7x) for large signals compared to PyWavelets' standard implementation. ```APIDOC ## fastcwt() - Fast Continuous Wavelet Transform ### Description The `fastcwt()` function provides an optimized CWT implementation using FFT-based convolution, offering significant speedup (up to 7x) for large signals compared to PyWavelets' standard implementation. ### Method `scaleogram.wfun.fastcwt(signal, scales, wavelet, sampling_period=1.0, method='auto')` ### Parameters #### Path Parameters None #### Query Parameters - **signal** (numpy.ndarray) - Required - The input signal. - **scales** (numpy.ndarray) - Required - Array of wavelet scales to use. - **wavelet** (str) - Required - The name of the wavelet (e.g., 'cmor1-1.5', 'cgau5'). - **sampling_period** (float) - Optional - The sampling period of the signal. Defaults to 1.0. - **method** (str) - Optional - The convolution method to use. Options: 'auto', 'fft', 'conv'. Defaults to 'auto'. ### Request Example ```python import scaleogram as scg from scaleogram.wfun import fastcwt import numpy as np # Large signal for performance comparison signal = np.random.randn(50000) scales = np.arange(2, 200) wavelet = 'cmor1-1.5' # Fast CWT (FFT-based, auto-selects optimal method) coefs, freqs = fastcwt(signal, scales, wavelet, sampling_period=1.0, method='auto') print(f"Coefficients shape: {coefs.shape}") print(f"Frequencies shape: {freqs.shape}") # Force FFT method for large data coefs_fft, freqs_fft = fastcwt(signal, scales, wavelet, method='fft') # Force convolution method (slower but sometimes more precise) coefs_conv, freqs_conv = fastcwt(signal[:1000], scales[:50], wavelet, method='conv') ``` ### Response #### Success Response (200) - **coefs** (numpy.ndarray) - The CWT coefficients. - **freqs** (numpy.ndarray) - The corresponding frequencies for each scale. #### Response Example ```json { "coefs": [[...], [...]], "freqs": [0.1, 0.2, 0.3, ...] } ``` ``` -------------------------------- ### Visualizing Scaled Child Wavelets Source: https://github.com/alsauve/scaleogram/blob/master/doc/scale-to-frequency.ipynb Overlays child wavelets onto the scaleogram to visually demonstrate the relationship between scale and temporal smoothing. ```python # build the child s1 = 27; s2 = 90 child1 = scg.child_wav(wavelet, 27) child2 = scg.child_wav(wavelet, 90) # plot again Example 3 ax = scg.cws(time, data2, scales=np.arange(1, 150, 2), wavelet=wavelet, figsize=(14,3), cmap="jet", cbar=None, ylabel="Period [seconds]", xlabel="Time [seconds]", title="Example 3 : overimpression of the scaled child [wavelet="+wavelet+"]") # add the child wavelets over the scaleogram at their corresponding Y location ax.plot(np.arange(len(child1))-len(child1)/2+70, p1+child1.real*100, '-k', linewidth='5') ax.plot(np.arange(len(child1))-len(child1)/2+70, p1+child1.real*100, '-w', linewidth='3') ax.plot(np.arange(len(child2))-len(child2)/2+70, p2+child2.real*200, '-k', linewidth='5') ax.plot(np.arange(len(child2))-len(child2)/2+70, p2+child2.real*200, '-w', linewidth='3') xlim = ax.set_xlim(0,n) ``` -------------------------------- ### Generate Scaleograms with Different Y-axis Views Source: https://context7.com/alsauve/scaleogram/llms.txt Demonstrates how to generate a scaleogram using the `cws` function with different y-axis configurations: 'period', 'frequency', and 'scale'. This function visualizes the time-frequency (or time-scale) representation of a signal. ```python import scaleogram as scg import numpy as np import matplotlib.pyplot as plt fs = 100 # Sampling frequency (Hz) t = np.arange(0, 10, 1/fs) # 10 seconds signal = np.sin(2 * np.pi * 5 * t) + 0.5 * np.sin(2 * np.pi * 15 * t) # 5Hz + 15Hz scales = np.arange(1, 150) fig, axes = plt.subplots(1, 3, figsize=(15, 4)) # Period view (default) scg.cws(t, signal, scales=scales, yaxis='period', ax=axes[0], title="yaxis='period'", ylabel='Period (s)', cbar=None) # Frequency view (auto-enables log yscale) scg.cws(t, signal, scales=scales, yaxis='frequency', ax=axes[1], title="yaxis='frequency'", ylabel='Frequency (Hz)', cbar=None) # Raw scale view scg.cws(t, signal, scales=scales, yaxis='scale', ax=axes[2], title="yaxis='scale'", ylabel='Wavelet Scale', cbar=None) plt.tight_layout() plt.show() ``` -------------------------------- ### Configure Spectrum Types in cws() Source: https://context7.com/alsauve/scaleogram/llms.txt The spectrum parameter allows users to define how CWT coefficients are processed for visualization. This includes standard transformations like amplitude and power, or custom lambda functions for specific data scaling. ```python import scaleogram as scg import numpy as np import matplotlib.pyplot as plt signal = np.random.randn(512) + np.sin(2 * np.pi * np.arange(512) / 30) scales = np.arange(1, 100) fig, axes = plt.subplots(2, 2, figsize=(12, 8)) # Amplitude spectrum (default): abs(CWT) scg.cws(signal, scales=scales, spectrum='amp', ax=axes[0, 0], title="spectrum='amp' (default)", cbar=None) # Power spectrum: abs(CWT)^2 scg.cws(signal, scales=scales, spectrum='power', ax=axes[0, 1], title="spectrum='power'", cbar=None) # Real part only scg.cws(signal, scales=scales, spectrum='real', ax=axes[1, 0], title="spectrum='real'", cbar=None, cmap='RdBu_r') # Custom processing with lambda scg.cws(signal, scales=scales, spectrum=lambda c: np.log10(np.abs(c) + 1), # Log amplitude ax=axes[1, 1], title="Custom: log10(abs+1)", cbar=None) plt.tight_layout() plt.show() ``` -------------------------------- ### Configuring Logarithmic Y-Axis Source: https://github.com/alsauve/scaleogram/blob/master/doc/scale-to-frequency.ipynb Enables a logarithmic scale on the Y-axis of the scaleogram to normalize the visual height of bandwidths across different scales. ```python ax2 = scg.cws(time, data2, scales=np.arange(1, 150, 2), wavelet=wavelet, figsize=(14, 3), cmap="jet", cbar=None, ylabel="Period [seconds]", xlabel="Time [seconds]", title="Example 4 : data from Exemple 3 with Y axis in logscale", yscale='log') ``` -------------------------------- ### set_default_wavelet() / get_default_wavelet() - Wavelet Configuration Source: https://context7.com/alsauve/scaleogram/llms.txt These functions allow you to configure the default wavelet used across all scaleogram operations when no explicit wavelet is specified. ```APIDOC ## set_default_wavelet() / get_default_wavelet() - Wavelet Configuration ### Description These functions allow you to configure the default wavelet used across all scaleogram operations when no explicit wavelet is specified. ### Method `scaleogram.set_default_wavelet(wavelet_name)` `scaleogram.get_default_wavelet()` ### Parameters #### Path Parameters None #### Query Parameters - **wavelet_name** (str) - Required - The name of the wavelet to set as default (e.g., 'cmor1-1.5', 'cgau5'). ### Request Example ```python import scaleogram as scg import numpy as np # Get current default wavelet current = scg.get_default_wavelet() print(f"Default wavelet: {current}") # Set a different default wavelet scg.set_default_wavelet('cgau5') # Complex Gaussian, order 5 # All subsequent calls use new default signal = np.random.randn(256) scg.cws(signal, title="Using cgau5 wavelet") # Reset to recommended default scg.set_default_wavelet('cmor1-1.5') ``` ### Response #### Success Response (200) - **get_default_wavelet()**: Returns the name of the current default wavelet (str). - **set_default_wavelet()**: No return value (void). #### Response Example ```json { "get_default_wavelet": "cmor1-1.5" } ``` ``` -------------------------------- ### Plotting a Wavelet Function with PyWavelet Source: https://github.com/alsauve/scaleogram/blob/master/doc/scale-to-frequency.ipynb This code snippet visualizes a Complex Morlet wavelet function. It plots the wavelet in the time domain and its amplitude in the frequency domain, highlighting the central frequency. Requires the scaleogram and matplotlib libraries. ```python %matplotlib inline import scaleogram as scg axes = scg.plot_wav('cmor1-1.5', figsize=(14,3)) ``` -------------------------------- ### Integrate Scaleograms with Matplotlib Subplots Source: https://context7.com/alsauve/scaleogram/llms.txt Demonstrates how to integrate scaleogram outputs into complex matplotlib layouts, allowing for side-by-side signal and time-frequency analysis. ```python import scaleogram as scg import numpy as np import matplotlib.pyplot as plt # Multi-signal analysis np.random.seed(42) t = np.linspace(0, 10, 1000) signals = [ np.sin(2 * np.pi * 2 * t), np.sin(2 * np.pi * 5 * t) * np.exp(-0.3 * t), np.sin(2 * np.pi * t * (1 + t/5)), ] scales = np.arange(1, 100) fig, axes = plt.subplots(3, 2, figsize=(12, 10)) for i, signal in enumerate(signals): # Time domain axes[i, 0].plot(t, signal) axes[i, 0].set_xlabel('Time (s)') axes[i, 0].set_ylabel('Amplitude') axes[i, 0].set_title(f'Signal {i+1}') # Scaleogram scg.cws(t, signal, scales=scales, ax=axes[i, 1], cbar=None, coi=True, yaxis='frequency', title=f'Scaleogram {i+1}') plt.tight_layout() plt.show() ``` -------------------------------- ### Perform Fast Continuous Wavelet Transform using fastcwt() Source: https://context7.com/alsauve/scaleogram/llms.txt The `fastcwt()` function offers an optimized Continuous Wavelet Transform (CWT) implementation utilizing FFT-based convolution. It provides significant speed improvements, especially for large datasets, compared to standard CWT methods. The `method` parameter allows selection between 'auto', 'fft', or 'conv'. ```python import scaleogram as scg from scaleogram.wfun import fastcwt import numpy as np import pywt # Large signal for performance comparison signal = np.random.randn(50000) scales = np.arange(2, 200) wavelet = 'cmor1-1.5' # Fast CWT (FFT-based, auto-selects optimal method) coefs, freqs = fastcwt(signal, scales, wavelet, sampling_period=1.0, method='auto') print(f"Coefficients shape: {coefs.shape}") # (198, 50000) print(f"Frequencies shape: {freqs.shape}") # (198,) # Method options: # 'auto' - automatically choose fastest method per scale # 'fft' - always use FFT convolution # 'conv' - always use direct convolution # Force FFT method for large data coefs_fft, freqs_fft = fastcwt(signal, scales, wavelet, method='fft') # Force convolution method (slower but sometimes more precise) coefs_conv, freqs_conv = fastcwt(signal[:1000], scales[:50], wavelet, method='conv') ``` -------------------------------- ### cws() - Main Scaleogram Plotting Function Source: https://context7.com/alsauve/scaleogram/llms.txt The `cws()` function is the primary interface for creating scaleogram visualizations. It can compute the CWT on-the-fly or accept a pre-computed `CWT` object, and provides extensive customization options. ```APIDOC ## cws() - Main Scaleogram Plotting Function ### Description The `cws()` function is the primary interface for creating scaleogram visualizations. It can compute the CWT on-the-fly or accept a pre-computed `CWT` object, and provides extensive customization options for the resulting plot. ### Method `scaleogram.cws(time, signal, scales, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import scaleogram as scg import numpy as np import matplotlib.pyplot as plt # Generate test signal: cosine wave with period 52 time = np.arange(1024) - 512 signal = np.cos(2 * np.pi / 52 * time) scales = np.arange(1, 200, 2) # Basic usage - signal only (time auto-generated) ax = scg.cws(signal) # With time array and custom scales ax = scg.cws(time, signal, scales=scales) # Full customization example ax = scg.cws( time, signal, scales=scales, wavelet='cmor1-1.5', # Complex Morlet wavelet spectrum='power', # Display power spectrum (abs^2) yaxis='period', # Y-axis shows period (also: 'frequency', 'scale') cscale='linear', # Color scale ('linear' or 'log') cmap='jet', # Matplotlib colormap clim=(0, 100), # Color range limits cbar='vertical', # Colorbar position ('vertical', 'horizontal', or None) cbarlabel='Power', # Colorbar label coi=True, # Show Cone of Influence coikw={'alpha': 0.5, 'hatch': '/'}, # COI styling xlim=(-400, 400), # X-axis limits ylim=(100, 10), # Y-axis limits (inverted for period) yscale='linear', # Y-axis scale ('linear' or 'log') xlabel='Time (samples)', ylabel='Period', title='Scaleogram of Cosine Signal', figsize=(10, 6) ) plt.tight_layout() plt.show() ``` ### Response #### Success Response (200) - **ax** (matplotlib.axes.Axes) - The matplotlib Axes object containing the scaleogram plot. #### Response Example (A matplotlib Axes object is returned, not a JSON response. The example above shows how to use the function to generate a plot.) ``` -------------------------------- ### Generate Child Wavelets with child_wav Source: https://context7.com/alsauve/scaleogram/llms.txt Retrieves the scaled version of a wavelet at a specific scale. This is useful for analyzing how dilation affects the wavelet structure. ```python import scaleogram as scg from scaleogram.wfun import child_wav import numpy as np import matplotlib.pyplot as plt wavelet = 'cmor1-1.5' # Get child wavelets at different scales scales = [5, 20, 50, 100] fig, axes = plt.subplots(2, 2, figsize=(10, 6)) axes = axes.flatten() for i, scale in enumerate(scales): wav = child_wav(wavelet, scale) axes[i].plot(np.real(wav), label='Real') axes[i].plot(np.imag(wav), label='Imag') axes[i].set_title(f'Scale = {scale} (length={len(wav)})') axes[i].legend() axes[i].set_ylim(-1.5, 1.5) plt.suptitle(f'Child wavelets of {wavelet} at different scales') plt.tight_layout() plt.show() ``` -------------------------------- ### Compute and Reuse CWT with the CWT Class Source: https://context7.com/alsauve/scaleogram/llms.txt The CWT class allows for the pre-computation of wavelet transforms. This is efficient for scenarios where the same transform data needs to be visualized multiple times with different plot settings. ```python import scaleogram as scg import numpy as np # Create sample signal: Gaussian pulse centered at t=0 time = np.arange(200, dtype=np.float16) - 100 signal = np.exp(-0.5 * ((time) / 0.2) ** 2) # Define scales (higher scales = lower frequencies) scales = np.arange(1, 101) # Compute CWT once cwt = scg.CWT(time, signal, scales, wavelet='cmor1-1.5') # Access computed results print(f"Coefficients shape: {cwt.coefs.shape}") # (100, 200) print(f"Frequencies: {cwt.scales_freq[:5]}") # Array of frequencies print(f"Time step: {cwt.dt}") # 1.0 # Plot with full range scg.cws(cwt) # Plot with zoom (reuses same transform) scg.cws(cwt, xlim=(-50, 50), ylim=(20, 1)) ``` -------------------------------- ### Convert Periods to Wavelet Scales using periods2scales() Source: https://context7.com/alsauve/scaleogram/llms.txt The `periods2scales()` function converts desired period values into corresponding wavelet scale values. This is crucial for generating scaleograms with specific period or frequency ranges, ensuring appropriate scale selection for the chosen wavelet and time resolution. ```python import scaleogram as scg import numpy as np # Define desired periods (in same units as time array) periods = np.logspace(np.log10(2), np.log10(100), 50) # 2 to 100, log-spaced # Convert to scales for different wavelets wavelet = 'cmor1-1.5' scales = scg.periods2scales(periods, wavelet=wavelet, dt=1.0) print(f"Periods: {periods[:5]}") # [2.0, 2.24, 2.51, ...] print(f"Scales: {scales[:5]}") # [3.0, 3.36, 3.77, ...] # Use in scaleogram for even spacing in log period data = np.random.randn(512) scg.cws(data, scales=scales, wavelet=wavelet, yscale='log', title="CWT with log-spaced periods") ``` -------------------------------- ### Generate Scaleogram Plot Source: https://github.com/alsauve/scaleogram/blob/master/doc/El-Nino-Dataset.ipynb Calculates wavelet scales and produces a continuous wavelet transform plot using the scaleogram cws function. ```python import scaleogram as scg scales = np.logspace(1.2, 3.1, num=200, dtype=np.int32) ax = scg.cws(year, data, scales, figsize=(12,6), ylabel="Period [Years]", xlabel='Year', yscale='log') ticks = ax.set_yticks([2,4,8, 16,32]) ticks = ax.set_yticklabels([2,4,8, 16,32]) ``` -------------------------------- ### Visualize Scaleograms with cws() Source: https://context7.com/alsauve/scaleogram/llms.txt The cws() function is the primary interface for generating scaleogram plots. It supports direct signal input or pre-computed CWT objects, with extensive customization for axes, colormaps, and COI masking. ```python import scaleogram as scg import numpy as np import matplotlib.pyplot as plt # Generate test signal: cosine wave with period 52 time = np.arange(1024) - 512 signal = np.cos(2 * np.pi / 52 * time) scales = np.arange(1, 200, 2) # Basic usage - signal only (time auto-generated) ax = scg.cws(signal) # With time array and custom scales ax = scg.cws(time, signal, scales=scales) # Full customization example ax = scg.cws( time, signal, scales=scales, wavelet='cmor1-1.5', # Complex Morlet wavelet spectrum='power', # Display power spectrum (abs^2) yaxis='period', # Y-axis shows period (also: 'frequency', 'scale') cscale='linear', # Color scale ('linear' or 'log') cmap='jet', # Matplotlib colormap clim=(0, 100), # Color range limits cbar='vertical', # Colorbar position ('vertical', 'horizontal', or None) cbarlabel='Power', # Colorbar label coi=True, # Show Cone of Influence coikw={'alpha': 0.5, 'hatch': '/'}, xlim=(-400, 400), ylim=(100, 10), yscale='linear', xlabel='Time (samples)', ylabel='Period', title='Scaleogram of Cosine Signal', figsize=(10, 6) ) plt.tight_layout() plt.show() ``` -------------------------------- ### periods2scales() - Convert Periods to Wavelet Scales Source: https://context7.com/alsauve/scaleogram/llms.txt The periods2scales() function converts desired period values to the corresponding wavelet scale values, essential for creating scaleograms with specific period/frequency ranges. ```APIDOC ## periods2scales() - Convert Periods to Wavelet Scales ### Description The `periods2scales()` function converts desired period values to the corresponding wavelet scale values, essential for creating scaleograms with specific period/frequency ranges. ### Method `scaleogram.periods2scales(periods, wavelet='cmor1-1.5', dt=1.0)` ### Parameters #### Path Parameters None #### Query Parameters - **periods** (numpy.ndarray) - Required - Array of desired period values. - **wavelet** (str) - Optional - The name of the wavelet to use (e.g., 'cmor1-1.5', 'cgau5'). Defaults to 'cmor1-1.5'. - **dt** (float) - Optional - The sampling period of the signal. Defaults to 1.0. ### Request Example ```python import scaleogram as scg import numpy as np # Define desired periods (in same units as time array) periods = np.logspace(np.log10(2), np.log10(100), 50) # 2 to 100, log-spaced # Convert to scales for different wavelets wavelet = 'cmor1-1.5' scales = scg.periods2scales(periods, wavelet=wavelet, dt=1.0) print(f"Periods: {periods[:5]}") print(f"Scales: {scales[:5]}") ``` ### Response #### Success Response (200) - **scales** (numpy.ndarray) - Array of corresponding wavelet scale values. #### Response Example ```json { "scales": [3.0, 3.36, 3.77, 4.23, 4.75] } ``` ``` -------------------------------- ### Y-Axis Units: Period, Frequency, and Scale Source: https://context7.com/alsauve/scaleogram/llms.txt The `yaxis` parameter in the `cws()` function controls the units displayed on the Y-axis, offering flexibility for different analysis contexts (period, frequency, or scale). ```APIDOC ## Y-Axis Units: Period, Frequency, and Scale ### Description The `yaxis` parameter controls the units displayed on the Y-axis, providing flexibility for different analysis contexts. Options include 'period', 'frequency', and 'scale'. ### Method `scaleogram.cws(..., yaxis=...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import scaleogram as scg import numpy as np import matplotlib.pyplot as plt # Example demonstrating yaxis='period' signal = np.random.randn(512) scales = np.arange(1, 100) scg.cws(signal, scales=scales, yaxis='period', title="Y-axis: Period") plt.show() # Example demonstrating yaxis='frequency' scg.cws(signal, scales=scales, yaxis='frequency', title="Y-axis: Frequency") plt.show() # Example demonstrating yaxis='scale' (default) scg.cws(signal, scales=scales, yaxis='scale', title="Y-axis: Scale") plt.show() ``` ### Response #### Success Response (200) - **ax** (matplotlib.axes.Axes) - The matplotlib Axes object containing the scaleogram plot. #### Response Example (A matplotlib Axes object is returned, not a JSON response. The example above shows how to generate plots with different y-axis units.) ``` -------------------------------- ### CWT Class - Continuous Wavelet Transform Source: https://context7.com/alsauve/scaleogram/llms.txt The CWT class computes and stores the continuous wavelet transform, allowing reuse for multiple plots without recomputation. ```APIDOC ## CWT Class - Container for Continuous Wavelet Transform ### Description The `CWT` class computes and stores the continuous wavelet transform, allowing you to reuse the same transform for multiple plots with different visualization settings without recomputing the expensive wavelet convolution. ### Method `scaleogram.CWT(time, signal, scales, wavelet='cmor1-1.5')` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import scaleogram as scg import numpy as np # Create sample signal: Gaussian pulse centered at t=0 time = np.arange(200, dtype=np.float16) - 100 signal = np.exp(-0.5 * ((time) / 0.2) ** 2) # Define scales (higher scales = lower frequencies) scales = np.arange(1, 101) # Compute CWT once cwt = scg.CWT(time, signal, scales, wavelet='cmor1-1.5') # Access computed results print(f"Coefficients shape: {cwt.coefs.shape}") print(f"Frequencies: {cwt.scales_freq[:5]}") print(f"Time step: {cwt.dt}") # Plot with full range scg.cws(cwt) # Plot with zoom (reuses same transform) scg.cws(cwt, xlim=(-50, 50), ylim=(20, 1)) ``` ### Response #### Success Response (200) - **cwt.coefs** (numpy.ndarray) - The computed CWT coefficients. - **cwt.scales_freq** (numpy.ndarray) - The frequencies corresponding to the scales. - **cwt.dt** (float) - The time step of the input signal. #### Response Example ```json { "coefs_shape": [100, 200], "frequencies_preview": [0.01, 0.02, 0.03, 0.04, 0.05], "time_step": 1.0 } ``` ``` -------------------------------- ### Spectrum Types in cws() Source: https://context7.com/alsauve/scaleogram/llms.txt The `spectrum` parameter in the `cws()` function controls how the complex CWT coefficients are transformed for display, offering options like amplitude, power, and custom functions. ```APIDOC ## Spectrum Types in cws() ### Description The `spectrum` parameter controls how the complex CWT coefficients are transformed for display. Options include amplitude, power, real/imaginary parts, and custom functions. ### Method `scaleogram.cws(..., spectrum=...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import scaleogram as scg import numpy as np import matplotlib.pyplot as plt signal = np.random.randn(512) + np.sin(2 * np.pi * np.arange(512) / 30) scales = np.arange(1, 100) fig, axes = plt.subplots(2, 2, figsize=(12, 8)) # Amplitude spectrum (default): abs(CWT) scg.cws(signal, scales=scales, spectrum='amp', ax=axes[0, 0], title="spectrum='amp' (default)", cbar=None) # Power spectrum: abs(CWT)^2 scg.cws(signal, scales=scales, spectrum='power', ax=axes[0, 1], title="spectrum='power'", cbar=None) # Real part only scg.cws(signal, scales=scales, spectrum='real', ax=axes[1, 0], title="spectrum='real'", cbar=None, cmap='RdBu_r') # Custom processing with lambda scg.cws(signal, scales=scales, spectrum=lambda c: np.log10(np.abs(c) + 1), # Log amplitude ax=axes[1, 1], title="Custom: log10(abs+1)", cbar=None) plt.tight_layout() plt.show() ``` ### Response #### Success Response (200) - **ax** (matplotlib.axes.Axes) - The matplotlib Axes object containing the scaleogram plot. #### Response Example (A matplotlib Axes object is returned, not a JSON response. The example above shows how to use the function to generate plots with different spectrum types.) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.