> ## 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.

# GISQAPipeline API Reference: Methods and Parameters

> Complete reference for GISQAPipeline: compute pointwise metrics, run pairwise spatial pipelines, build noise banks, and extract features from spectrograms.

`GISQAPipeline` is the primary interface for extracting spectral features from signals in Spec2Vec. It wraps both the pointwise (statistical, entropy, fractal) and pairwise (spatial zone) metric pipelines into a single, high-level object that you instantiate once and reuse across your entire analysis.

## Import

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

giq = GISQAPipeline()
```

***

## compute\_pointwise\_metrics\_from\_spec

Computes pointwise feature metrics for a batch of signals or spectrograms and returns the results as a tidy `DataFrame`. Each row corresponds to one input signal; each column is a named feature.

```python theme={null}
df = giq.compute_pointwise_metrics_from_spec(
    spec_names=['signal_a', 'signal_b'],
    spec_images=[array_a, array_b],
    is_hilbertize=1,
    is_normalize_stat=0,
    is_normalize_entropy=0,
    is_best_features=0,
    metrics_list=None
)
```

### Parameters

**spec\_names** `list[str]` *required*

Names or labels for each input signal. Must be the same length as `spec_images`. Each name becomes the identifying label for that signal's row in the output `DataFrame`.

**spec\_images** `list[np.ndarray]` *required*

List of input arrays. Each element can be either a 1D time-series array or a 2D spectrogram array (frequency × time). All arrays in the list may have different shapes.

**is\_hilbertize** `int` (default: 1)

Set to `1` to apply Hilbert curve (space-filling curve) flattening before feature extraction. This is required for 2D spectrogram inputs so that the image is reduced to a 1D sequence while preserving spatial locality. Set to `0` when passing raw 1D time-series arrays.

**is\_normalize\_stat** `int` (default: 1)

Set to `1` to normalize all statistical and textural features to the `[0, 1]` range using `MinMaxScaler`. Set to `0` to return raw feature values.

**is\_normalize\_entropy** `int` (default: 0)

Set to `1` to normalize entropy-based features to `[0, 1]`. Entropy features are often already bounded by their mathematical definition, so normalization is optional.

**is\_best\_features** `int` (default: 1)

Set to `1` to return only the top five most discriminating features: `detrended_fluctuation_antropy`, `fisher_shannon_ordpy`, `0_Lempel-Ziv complexity`, `svd_entropy_antropy`, and `approximate_entropy_antropy`. Set to `0` to return the full feature set (50+ features).

**metrics\_list** `list[str] or None` (default: None)

An explicit list of feature names to compute, for example:

```python theme={null}
['permutation_entropy_antropy', 'svd_entropy_antropy', 'detrended_fluctuation_antropy']
```

When `None`, all available features are computed (subject to `is_best_features`). Providing a subset substantially reduces runtime.

### Returns

**spec\_pointwise\_metrics\_df** `pd.DataFrame`

A `DataFrame` where rows are indexed by position (with a `label` column containing `spec_names`) and columns are feature names. Shape is `(len(spec_names), n_features)`.

## execute\_pairwise\_pipleine

Runs the full pairwise spatial feature extraction pipeline for a single spectrogram image against a noise reference bank. The pipeline performs histogram alignment, Gaussian Mixture Model (GMM) labeling, and Gray-Level Size Zone Matrix (GLSZM) spatial metric computation in two refinement stages.

> [!WARNING]
>
> This method requires a pre-built noise reference bank saved as an HDF5 file. Build one using `compute_imgbank_dict()` and save it with `h5py`

```python theme={null}
glszm_metrics, spec_details = giq.execute_pairwise_pipleine(
    t_plot=t_array,
    f_plot=f_array,
    spec_img=spectrogram_2d,
    noisebnk_path='path/to/noise_bank.h5',
    noisebnk_keys=['white_stft_w64_olap0.5', 'pink_stft_w64_olap0.5'],
    binary_keys=[],
    hist_bins=512,
    noise_cutoff=90,
    gmm_ncomp=5,
    gmm_mean_threshold=0.05,
    min_zone_size_thrshld=5,
    filename='event_001',
    save_path='./output_plots/',
    save_all_plots=True
)
```

### Parameters

**t\_plot** `np.ndarray` *required*

Time axis array for the spectrogram, as returned by `stft_basic_spectogram()` or `cwt_simple()`.

**f\_plot** `np.ndarray` *required*

Frequency axis array for the spectrogram.

**spec\_img** `np.ndarray` *required*

2D spectrogram array of shape `(n_freq, n_time)`.

**noisebnk\_path** `str` *required*

Filesystem path to the HDF5 noise reference bank (`.h5` file).

**noisebnk\_keys** `list` *required*

List of group keys inside the HDF5 file to use as reference noise templates. Each key corresponds to a noise type/configuration that was stored when the bank was built.

**binary\_keys** `list`

List of keys in the noise bank that correspond to binary mask entries (i.e., images with only two intensity levels). The binary images will be converted to a normal distribution to optimize the histogram alignment. This is only required if the noise-bank contains binary images.

**hist\_bins** `int` (default: 512)

Number of histogram bins used for distribution alignment between the target spectrogram and each noise reference template.

**noise\_cutoff** `int` (default: 90)

Percentile threshold for estimating the noise floor during histogram alignment. Pixels below this threshold in the realigned histogram are treated as noise.

**corr\_only** `bool` (default: False)

When `True`, performs only the correlation-based histogram alignment step and skips the exponential optimization. Useful for a fast first-pass inspection of the noise fit quality.

**gmm\_ncomp** `int` (default: 5)

Number of Gaussian components for GMM fitting. Controls the maximum number of distinct energy zones the pipeline attempts to identify in the spectrogram.

**gmm\_mean\_threshold** `float` (default: 0.05)

Minimum mean separation between adjacent GMM components. Components whose means are closer than this threshold are merged to prevent over-segmentation. Defaults to 0.05.

**gmm\_nbins** `int` (default: 256)

Number of bins used when constructing the histogram passed to GMM fitting.

**spec\_normalize** `str` (default: 'full')

Normalization strategy applied to the spectrogram before GMM fitting. Pass `'full'` to normalize across the entire image (recommended), or `'columns'` to normalize each column independently.

**min\_zone\_size\_thrshld** `int` (default: 5)

Minimum number of contiguous pixels required to form a valid size zone in the GLSZM computation. Zones smaller than this threshold are treated as speckle noise and filtered out in stage 2.

**filename** `str`

Label string written into the `label` column of the returned metrics `DataFrame` and used as the base filename for saved plots.

**save\_path** `str`

Directory path for saving intermediate visualization plots. Created automatically if it does not exist.

**save\_all\_plots** `bool` (default: True)

When `True`, saves diagnostic plots covering the original spectrogram, aligned distributions, GMM cuts, labeled spectrograms, size zone variance, and the noise-filtered result. When `False` the Feature generation process works faster.

**best\_neighbour\_key** `str or None` (default: None)

When provided, skips the automatic nearest-neighbour search and uses this key directly as the noise reference template. Useful when you already know the best-matching noise type for your signal class.

**optimization\_params** `dict`

Dictionary controlling the exponential optimization used during histogram alignment. Keys are `'type'`, `'start'`, `'end'`, and `'slope'`. Defaults to `{'type': 'exponential', 'start': 0.1, 'end': 100, 'slope': 10}`. One can play with these parameters while keeping the `save_all_plots=True` to understand what works best.

**scale\_percentile\_range** `tuple` (default: (1, 100))

Percentile range `(lower, upper)` used when scaling the spectrogram pixel values during noise filtering. Defaults to 1 and 100. Should only be updated if need to eliminate extr speckle noise in the 2D representation.

### Returns

**glszm\_metrics** `pd.DataFrame`

`DataFrame` containing stage-1 and stage-2 GLSZM spatial zone metrics. Stage-1 columns are suffixed `_stg1`; stage-2 (speckle-filtered) columns are suffixed `_stg2`. Also includes a `label` column.

**updated\_spec\_details** `dict`

Dictionary with keys `t_plot`, `f_plot`, `labeled_spec_image`, `arguments_dict`, `refined_labeled_spec_image`, and `spec_image_noise_cleaned`. Useful for downstream visualization or further analysis.

***

# The following functions are useful only when Spatial Metrics Computations are needed for a specific application.

## compute\_imgbank\_dict

Generates a dictionary of noise spectrogram banks from a list of noise type labels and corresponding noise arrays. You can pass the result directly to `compute_noisebnk_metrics()` or save it to HDF5 for Spatial feature extractions pipeline. For a full end to end pipeline please refer to [reference\_noisebankprep.ipynb](https://github.com/URseismology/Spec2Vec/blob/main/other_useful_notebooks/reference_noisebankprep.ipynb) file.

```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,
    save_path='noise_bank.h5'
)
```

### Parameters

**spec\_types** `list` *required*

List of spectrogram (or spatial structure) types to generate. Supported values include `'stft'`, `'cwt'`, `'perlin_noise'`, `'erdos_renyi_graph'`, `'Gaussian'`, `'Exponential'`, and `'pspy_fractal_noise'`. For standard geophysical workflows, use `['stft']` or `['cwt']`.

**noiselist** `list` *required*

List of colored noise color strings to generate spectrograms for. Supported values: `'white'`, `'pink'`, `'red'`, `'blue'`, `'violet'`, `'f3'`, `'f4'`. Ignored for non-time-series spec types.

**Fs** `int` *required*

Sampling frequency in Hz for noise time-series generation.

**time\_in\_sec** `int` *required*

Duration in seconds for each generated noise segment. Combined with `Fs` to set the total number of samples (`L = Fs × time_in_sec`).

**total\_realizations** `int` (default: 50)

Number of independent noise realizations to generate per noise type and spectrogram configuration. More realizations provide a more stable reference distribution.

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

Sampling period in seconds. When `None`, it is computed from `Fs`. Pass an explicit value only when your signal has a non-standard sampling period.

**save\_path** `str`

If provided, the generated bank is written to this HDF5 file path. The file can then be passed as `noisebnk_path` to `execute_pairwise_pipleine()`.

**interp\_size** `tuple or None` (default: None)

Target image dimensions `(height, width)` for interpolating all spectrograms to a common resolution. Useful when mixing STFT windows of different sizes.

**normalize\_range** `tuple` (default: (1e-8, 1))

Normalization range applied to each generated spectrogram image.

### Returns

**spec\_dict** `dict`

Dictionary mapping noise group names (e.g., `'white_stft_w64_olap0.5'`) to sub-dictionaries containing `'image'` (shape `[realizations, 1, H, W]`), `'hilbert_image'`, `'time_series'`, `'f'`, and `'t'` arrays.

***

## compute\_noisebnk\_metrics

Extracts pointwise feature metrics for every entry in a noise reference bank. You can provide either a path to an existing HDF5 bank or the in-memory dictionary returned by `compute_imgbank_dict()`. The result is a `DataFrame` in the same format as `compute_pointwise_metrics_from_spec()`, suitable for use as a reference distribution in downstream pointwise feature-difference analysis.

```python theme={null}
noise_metrics_df = giq.compute_noisebnk_metrics(
    noise_bnk_path='noise_bank.h5',
    img_bank_dict={},
    max_realizations=100,
    is_hilbertize=1,
    is_normalize_stat=1,
    is_normalize_entropy=0,
    is_best_features=0,
    metrics_list=None
)
```

### Parameters

**noise\_bnk\_path** `str`

Path to an HDF5 noise bank file. If provided, the file is opened and iterated over. Takes priority over `img_bank_dict` when both are supplied.

**img\_bank\_dict** `dict` (default: \{})

In-memory bank dictionary as returned by `compute_imgbank_dict()`. Used when `noise_bnk_path` is empty.

**max\_realizations** `int` (default: 100)

Maximum number of noise realizations to process per noise group. Useful for controlling runtime during exploratory analysis.

**is\_hilbertize** `int` (default: 1)

Apply Hilbert curve flattening to each noise image before feature extraction.

**is\_normalize\_stat** `int` (default: 1)

Normalize statistical features to `[0, 1]`.

**is\_normalize\_entropy** `int` (default: 0)

Normalize entropy-based features to `[0, 1]`.

**is\_best\_features** `int` (default: 0)

Return only the top 5 discriminating features. Set to `0` to compute the full feature set for comprehensive noise characterization.

**metrics\_list** `list[str] or None` (default: None)

Specific feature names to compute. Pass `None` for all features.

**save\_path** `str`

If provided, the resulting `DataFrame` is saved to this CSV path after each noise group completes, acting as a checkpoint.

**verbose** `int` (default: 0)

Set to `1` to print a progress message to stdout after each noise group finishes processing.

### Returns

**spec\_pointwise\_metrics\_df** `pd.DataFrame`

Feature `DataFrame` for all noise bank entries. The `label` column contains the noise group key (e.g., `'white_stft_w64_olap0.5'`). Use this as the reference distribution for `execute_pointwise_featurediff_pipeline()`.


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