> ## Documentation Index
> Fetch the complete documentation index at: https://spec2vec.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Spec2Vec Noise Generation and Synthetic Signal Utilities

> Reference for Spec2Vec noise generation tools: ColoredNoiseGenerator, white_noise_series, AR-driven and PSD-driven series, and synthetic signal models.

Spec2Vec includes a suite of utilities for generating colored noise time-series and simple synthetic signals. These tools serve two primary purposes: building noise reference banks for pairwise metric extraction, and generating labeled synthetic datasets for prototyping and benchmarking your analysis pipeline. The core generators live in `noise_lib.py`, and higher-level signal models are in `simple_synth_data_models.py`.

## Import

```python theme={null}
from SPEC2VEC.utils.noise_lib import (
    ColoredNoiseGenerator,
    white_noise_series,
    ar_driven_noise_series,
    psd_driven_noise_series,
)
from SPEC2VEC.utils.simple_synth_data_models import (
    gen_additive_synthetic_signal,
    gen_multiplicative_synthetic_signal,
)
```

***

## ColoredNoiseGenerator (Class)

`ColoredNoiseGenerator` generates time-series of different spectral colors by shaping white Gaussian noise in the frequency domain. Instantiate it with the desired number of samples `N`, then call any color method.

```python theme={null}
from SPEC2VEC.utils.noise_lib import ColoredNoiseGenerator

L = 1000   # number of samples (Fs * duration)
gen = ColoredNoiseGenerator(N=L)

white  = gen.white()               # flat power spectrum
pink   = gen.pink()                # power ∝ 1/f
red    = gen.brownian()            # power ∝ 1/f²  (Brownian / red)
blue   = gen.blue()                # power ∝ f
violet = gen.violet()              # power ∝ f²
f3     = gen.higher_order_noise_3()  # power ∝ 1/f³
f4     = gen.higher_order_noise_4()  # power ∝ 1/f⁴
f5     = gen.higher_order_noise_5()  # power ∝ 1/f⁵
```

> [!NOTE]
>
> The method for Brownian (red) noise is `brownian()`, not `red()`. When you pass `'red'` to `noiselist` in `compute_imgbank_dict()`, the pipeline internally calls `gen.brownian()` on your behalf.

The table below summarizes the spectral shape of each noise color and its typical geophysical context.

| Color | Method | PSD shape | Geophysical relevance |
| - | - | - | - |
| **White** | `white()` | Flat (`1`) | Instrument self-noise, thermal noise |
| **Pink** | `pink()` | `1/f` | Background seismic hum, infrasound |
| **Red / Brownian** | `brownian()` | `1/f²` | Ocean microseisms, long-period ground motion |
| **Blue** | `blue()` | `f` | High-frequency anthropogenic noise |
| **Violet** | `violet()` | `f²` | Strongly high-frequency dominated processes |
| **f3** | `higher_order_noise_3()` | `1/f³` | Very long-period or deep Earth processes |
| **f4** | `higher_order_noise_4()` | `1/f⁴` | Very long-period or deep Earth processes |
| **f5** | `higher_order_noise_5()` | `1/f⁵` | Very long-period or deep Earth processes |

> [!NOTE]
>
> All `ColoredNoiseGenerator` methods return a `numpy` array of length `N`. The output is not amplitude-normalized by default. If you need unit-scale signals for spectrogram generation, normalize with `sklearn.preprocessing.MinMaxScaler(feature_range=(-1, 1))` before computing the STFT or CWT.

***

## white\_noise\_series (function)

Generates a simple white noise time-series drawn from a normal distribution. This is a standalone function — use it when you need a quick white noise segment without instantiating `ColoredNoiseGenerator`.

```python theme={null}
from SPEC2VEC.utils.noise_lib import white_noise_series

ts = white_noise_series(L=1000, amp=1, mu=0, sd=1)
```

### Parameters

**L** `int` *required*

Length of the time series (number of samples).

**amp** `float` (default: 1)

Amplitude multiplier applied to the noise output.

**mu** `float` (default: 0)

Mean of the normal distribution.

**sd** `float` (default: 1)

Standard deviation of the normal distribution.

### Returns

**noise** `np.ndarray`

1D array of length `L` containing the generated white noise signal.

***

## ar\_driven\_noise\_series (function)

Generates a noise time-series from a linear autoregressive (AR) system driven by white noise. The AR coefficients `a_k` define the resonant structure of the output signal. You can use this to synthesize signals with known spectral shapes (e.g., narrow-band resonances) for testing your pipeline.

```python theme={null}
from SPEC2VEC.utils.noise_lib import ar_driven_noise_series

ts, times, freq_series, freqs, psd = ar_driven_noise_series(
    T=10,
    sampling_rate=100,
    P=1.0,
    a_k=[1, -2.2137, 2.9403, -2.1697, 0.9606]
)
```

### Parameters

**T** `float` (default: 2)

Length of the time series in seconds.

**sampling\_rate** `int` (default: 1000)

Sampling rate of the output time series in Hz.

**P** `float` (default: 1)

Variance of the driving white noise.

**a\_k** `list or np.ndarray` (default: \[1, -2.2137, 2.9403, -2.1697, 0.9606])

Autoregressive coefficients. The first element must be `1`. The roots of the characteristic polynomial defined by `a_k` must all lie inside the unit circle for the system to be stable.

**fmin** `float or None` (default: None)

Minimum frequency (Hz) for PSD computation. When `None`, defaults to `0`.

**fmax** `float or None` (default: None)

Maximum frequency (Hz) for PSD computation. When `None`, defaults to the Nyquist frequency.

### Returns

**time\_series** `np.ndarray`

The synthesized time-series signal.

**times** `np.ndarray`

Corresponding time vector.

**frequency\_series** `np.ndarray`

Complex Fourier series of the signal.

**frequencies** `np.ndarray`

Frequency vector matching the spectral length.

**psd** `np.ndarray`

Power Spectral Density array at the returned frequency bins. Compare this against the empirical spectrogram as a sanity check.

***

## psd\_driven\_noise\_series (function)

Synthesizes a noise time-series directly from a custom PSD curve you supply. Use this when you have a measured or modeled PSD and want to generate realizations of a signal with that exact spectral shape.

```python theme={null}
from SPEC2VEC.utils.noise_lib import psd_driven_noise_series
import numpy as np

f_custom = np.linspace(0, 50, 100)
psd_custom = 1 / (1 + f_custom**2)  # example Lorentzian PSD

times, ts, freqs, freq_series, psd = psd_driven_noise_series(
    f=f_custom,
    PSD=psd_custom,
    T=10,
    sampling_rate=100
)
```

### Parameters

**f** `np.ndarray` *required*

A vector of uniformly separated frequencies (Hz) over which the PSD is defined.

**PSD** `np.ndarray` *required*

A vector of PSD values corresponding to `f`.

**T** `float` (default: 2)

Total length of the desired signal in seconds.

**sampling\_rate** `int` (default: 1000)

Sampling rate of the desired signal in Hz.

**fmin** `float or None` (default: None)

Minimum frequency to compute. Defaults to `0` when `None`.

**fmax** `float or None` (default: None)

Maximum frequency to compute. Defaults to the Nyquist frequency when `None`.

### Returns

**times** `np.ndarray`

Time vector for the synthesized signal.

**time\_series** `np.ndarray`

The synthesized real time-series signal.

**frequencies** `np.ndarray`

Frequency vector matching the signal's spectral length.

**frequency\_series** `np.ndarray`

Complex Fourier series of the signal.

**psd** `np.ndarray`

Power Spectral Density interpolated at the output frequency bins.

***

## Building a Noise Bank

Pairwise metric extraction requires a noise reference bank: a collection of spectrogram images computed from multiple realizations of different noise types. The bank defines the statistical "background" against which your target signal's amplitude distribution is aligned before GMM labeling and GLSZM zone metric computation.

Use `GISQAPipeline.compute_imgbank_dict()` to build a bank programmatically. Pass `spec_types=['stft']` and a list of noise color strings in `noiselist`. The method generates `total_realizations` independent noise realizations per noise color and STFT parameter combination, converts each to a spectrogram, and stores all images in a structured dictionary.

```python theme={null}
from SPEC2VEC.utils.gisqa_compute_updated import GISQAPipeline

giq = GISQAPipeline()

img_bank = giq.compute_imgbank_dict(
    spec_types=['stft'],
    noiselist=['white', 'pink', 'red'],
    Fs=100,
    time_in_sec=10,
    total_realizations=50,
    f_min=0,
    f_max=50,
    save_path='my_noise_bank.h5'
)

# img_bank keys look like: 'white_stft_w32_olap0.5', 'pink_stft_w64_olap0.75', ...
print(list(img_bank.keys()))
```

Each key in the returned dictionary corresponds to one noise type and STFT window configuration. The values are sub-dictionaries with the following fields:

| Field | Shape | Description |
| - | - | - |
| `'image'` | `(realizations, 1, H, W)` | Stack of spectrogram images |
| `'hilbert_image'` | `(realizations, H*W)` | Hilbert-curve-flattened versions of the images |
| `'time_series'` | `(realizations, L)` | Raw noise time-series used to generate each image |
| `'f'` | `(H,)` | Frequency axis |
| `'t'` | `(W,)` | Time axis |

> [!WARNING]
>
> The noise bank must be built at the same spectrogram resolution (height × width) as the target spectrograms you plan to analyze. If you process signals with multiple resolutions, build a separate bank for each resolution or use the `interp_size` parameter in `compute_imgbank_dict()` to standardize all images to a common shape.

***

***

## Simple Synthetic Signal Models

`simple_synth_data_models.py` provides functions for constructing controlled synthetic time-series. These are useful for generating labeled training sets, validating your pipeline on signals with known properties, and designing sensitivity tests.

### Additive processes

An additive signal is the superposition of multiple sinusoidal components:

```text theme={null}
x(t) = A₁·sin(2π·f₁·t) + A₂·sin(2π·f₂·t) + ··· + Aₙ·sin(2π·fₙ·t)
```

```python theme={null}
from SPEC2VEC.utils.simple_synth_data_models import gen_additive_synthetic_signal
import numpy as np

t, signal = gen_additive_synthetic_signal(
    fs=100,
    T=10,
    w=np.array([5.0, 20.0, 35.0]),   # frequencies in Hz
    a=np.array([1.0, 0.5, 0.25])     # amplitudes
)
```

### Multiplicative processes

A multiplicative signal encodes amplitude modulation between frequency components. Two formulations are available:

* **Type 1**: `x(t) = sin(A) · sin(B) · ··· · sin(N)` — pure product of sinusoids
* **Type 2**: `x(t) = sin(A) · (1 + ε · sin(B))` — carrier modulated by a low-frequency envelope (requires exactly two frequencies with `w[0] > w[1]`)

```python theme={null}
from SPEC2VEC.utils.simple_synth_data_models import gen_multiplicative_synthetic_signal
import numpy as np

t, signal = gen_multiplicative_synthetic_signal(
    fs=100,
    T=10,
    w=np.array([20.0, 5.0]),   # w[0] must be > w[1] for type=2
    a=np.array([1.0, 0.3]),
    type=2
)
```

> [!NOTE]
>
> `gen_multiplicative_synthetic_signal` requires `w` and `a` to be `numpy` arrays (not plain lists) and `type` is a positional argument.

### Autoregressive processes

Autoregressive (AR) signals are generated from a linear filter driven by white noise, where the denominator polynomial `A(z)` determines the resonant frequencies and decay rates of the system. Use `ar_driven_noise_series()` from `noise_lib.py` for this purpose.

```python theme={null}
from SPEC2VEC.utils.noise_lib import ar_driven_noise_series

ts, times, freq_series, freqs, psd = ar_driven_noise_series(
    T=10,
    sampling_rate=100,
    P=1.0,
    a_k=[1, -2.2137, 2.9403, -2.1697, 0.9606]
)
```

The AR coefficients `a_k` must define a stable system (all roots of the characteristic polynomial inside the unit circle). The function also returns the theoretical PSD, which you can compare against the empirical spectrogram as a sanity check.

***


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.