Skip to content

Scattering transform API documentation

ScatteringTransform

ScatteringTransform(
    n_scales,
    n_layers,
    nlin=torch.abs,
    cached=False,
    output="graph",
    aggregation="mean",
    moments=(1, 2, 3, 4),
)

Bases: Module

ScatteringTransform base class. Inherits from PyTorch nn.Module.

This class implements the base logic to compute graph scattering transforms with a pooling and an arbitrary wavelet transform operators.

This is a base class, and implements only the logic to compute an arbitrary scattering transform. The method get_wavelets must be implemented by the subclass.

Scattering coefficients are ordered depth-major, then by parent path, then by scale.

Parameters:

Name Type Description Default
n_scales int

Number of scales to use in wavelet transform

required
n_layers int

Number of layers in the scattering transform

required
nlin Callable[[Tensor], Tensor]

Non-linearity used in the scattering transform. Defaults to torch.abs

abs
cached bool

If set to True, the filter bank is cached on first execution and reused while the same adjacency matrix is passed. A different adjacency, or one that requires grad, rebuilds it. Defaults to False

False
output Literal['graph', 'node']

"graph" pools each scattering path over the nodes, giving (batch, n_features, n_coefficients), the standard graph scattering transform. "node" skips pooling and returns the graph signal (batch, n_features, n_coefficients, n_nodes), used for node-level tasks). Defaults to "graph"

'graph'
aggregation Literal['mean', 'moments']

How "graph" output pools over nodes. "mean" averages each path, the standard graph scattering transform. "moments" averages |path| ** q for each q in moments, following Gao, Wolf & Hirn 2019, giving n_coefficients * len(moments) values per feature, coefficient-major, the so-called geometric scattering transform. Defaults to "mean"

'mean'
moments tuple[int, ...]

Moment orders used by aggregation="moments". Defaults to (1, 2, 3, 4)

(1, 2, 3, 4)
Source code in gsxform/scattering.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def __init__(
    self,
    n_scales: int,
    n_layers: int,
    nlin: Callable[[torch.Tensor], torch.Tensor] = torch.abs,
    cached: bool = False,
    output: Literal["graph", "node"] = "graph",
    aggregation: Literal["mean", "moments"] = "mean",
    moments: tuple[int, ...] = (1, 2, 3, 4),
) -> None:
    """Initialize scattering transform base class.

    This is a base class, and implements only the logic to compute
    an arbitrary scattering transform. The method `get_wavelets`
    must be implemented by the subclass.

    Scattering coefficients are ordered depth-major, then by parent path,
    then by scale.


    Parameters
    ----------
    n_scales: int
        Number of scales to use in wavelet transform
    n_layers: int
        Number of layers in the scattering transform
    nlin: Callable
        Non-linearity used in the scattering transform. Defaults to torch.abs
    cached: bool
        If set to True, the filter bank is cached on first execution and
        reused while the same adjacency matrix is passed. A different
        adjacency, or one that requires grad, rebuilds it. Defaults to False
    output: str
        "graph" pools each scattering path over the nodes, giving
        (batch, n_features, n_coefficients), the standard graph scattering transform.
        "node" skips pooling and returns the graph signal
        (batch, n_features, n_coefficients, n_nodes), used for node-level tasks).
        Defaults to "graph"
    aggregation: str
        How "graph" output pools over nodes. "mean" averages each path, the
        standard graph scattering transform.
        "moments" averages `|path| ** q` for each q in `moments`,
        following Gao, Wolf & Hirn 2019, giving n_coefficients *
        len(moments) values per feature, coefficient-major, the so-called
        geometric scattering transform. Defaults to "mean"
    moments: tuple[int, ...]
        Moment orders used by `aggregation="moments"`. Defaults to (1, 2, 3, 4)
    """
    super().__init__()

    if output not in ("graph", "node"):
        raise ValueError(f"output must be 'graph' or 'node', got {output!r}")
    if aggregation not in ("mean", "moments"):
        raise ValueError(
            f"aggregation must be 'mean' or 'moments', got {aggregation!r}"
        )

    # number of scales
    self.n_scales = n_scales
    # number of layers
    self.n_layers = n_layers

    self.nlin = nlin

    self.cached = cached

    self.output = output
    self.aggregation = aggregation
    self.moments = moments

    # derived from the graph and shaped by its size, so kept out of the
    # state dict; the adjacency is kept to detect when the graph changes
    self.register_buffer("_cached_adj", None, persistent=False)
    self.register_buffer("_cached_mask", None, persistent=False)
    self.register_buffer("_cached_psi", None, persistent=False)

forward

forward(x, W_adj, mask=None)

Forward pass of a generic scattering transform.

Parameters:

Name Type Description Default
x Tensor

input batch of graph signals

required
W_adj Tensor

Batch of weighted adjacency matrices

required
mask Tensor | None

Padding mask, boolean tensor shaped (batch, n_nodes) Padded entries of x and W_adj are ignored. Defaults to None

None

Returns:

Name Type Description
phi Tensor

scattering representation of the input batch

Source code in gsxform/scattering.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
def forward(
    self,
    x: torch.Tensor,
    W_adj: torch.Tensor,
    mask: torch.Tensor | None = None,
) -> torch.Tensor:
    """Forward pass of a generic scattering transform.

    Parameters
    ----------
    x: torch.Tensor
        input batch of graph signals
    W_adj: torch.Tensor
        Batch of weighted adjacency matrices
    mask: torch.Tensor, optional
        Padding mask, boolean tensor shaped (batch, n_nodes)
        Padded entries of `x` and `W_adj` are ignored. Defaults to None

    Returns
    -------
    phi: torch.Tensor
        scattering representation of the input batch

    """
    batch_size, _, n_nodes = x.shape

    if mask is not None:
        assert mask.shape == (batch_size, n_nodes), (
            f"mask must be shaped {(batch_size, n_nodes)}, got {tuple(mask.shape)}"
        )
        assert mask.dtype == torch.bool, f"mask must be bool, got {mask.dtype}"
        # isolate padded nodes and silence their signal, so padding cannot
        # leak into the real nodes whatever the caller filled it with
        W_adj = W_adj * (mask[:, :, None] & mask[:, None, :])
        x = x.masked_fill(~mask[:, None, :], 0)

    psi = self._get_wavelets_cached(W_adj, mask)

    assert psi.shape[0] == batch_size, (
        f"batch size of x ({batch_size}) must match W_adj ({psi.shape[0]})"
    )
    assert psi.shape[-1] == n_nodes, (
        f"node count of x ({n_nodes}) must match W_adj ({psi.shape[-1]})"
    )

    if mask is None:
        mask = torch.ones(batch_size, n_nodes, dtype=torch.bool, device=x.device)

    # apply scattering transform
    U = self._propagate(x, psi)

    # special case for node outputs, which are not pooled (hence no lowpass operator)
    # directly returns the node
    if self.output == "node":
        # padding can pick up rounding-level values from the filter bank
        return U.masked_fill(~mask[:, None, None, :], 0)

    lowpass = self.get_lowpass(mask, x.dtype)

    # standard scattering transform, which pools over the nodes with a
    # lowpass filter
    if self.aggregation == "mean":
        phi: torch.Tensor = einsum(U, lowpass, "b f c n, b n -> b f c")
        return phi

    # moment aggregation, which pools over the nodes with a lowpass filter, then raised to the qth
    # power for a 'geometric' scattering transform
    moments = torch.stack(
        [
            einsum(U.abs() ** q, lowpass, "b f c n, b n -> b f c")
            for q in self.moments
        ],
        dim=-1,
    )
    return rearrange(moments, "b f c q -> b f (c q)")

get_lowpass

get_lowpass(mask, dtype)

Compute lowpass filtering/pooling operator.

This should roughly resemble an average, it alters the output scaling factor. For instance averaging with the norm of the degree vector scales towards zero, this implementation offers a more natural scaling.

Parameters:

Name Type Description Default
mask Tensor

Boolean tensor shaped (batch, n_nodes), true on real nodes

required
dtype dtype

Floating point type of the operator

required

Returns:

Name Type Description
lowpass Tensor

average pooling operator over each graph's real nodes

Source code in gsxform/scattering.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
def get_lowpass(self, mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
    """Compute lowpass filtering/pooling operator.

    This should roughly resemble an average, it alters the output
    scaling factor. For instance averaging with the norm
    of the degree vector scales towards zero, this implementation
    offers a more natural scaling.

    Parameters
    ----------
    mask: torch.Tensor
        Boolean tensor shaped (batch, n_nodes), true on real nodes
    dtype: torch.dtype
        Floating point type of the operator

    Returns
    -------
    lowpass: torch.Tensor
        average pooling operator over each graph's real nodes
    """
    weights = mask.to(dtype)
    lowpass = weights / weights.sum(dim=-1, keepdim=True)

    return lowpass

get_wavelets

get_wavelets(W_adj, mask=None)

Compute the wavelet operator.

Subclasses are required to implement this method.

Parameters:

Name Type Description Default
W_adj Tensor

Batch of weighted adjacency matrices. Padded nodes have no edges.

required
mask Tensor | None

Boolean tensor shaped (batch, n_nodes), true on real nodes. None when every graph fills all n_nodes.

None
Source code in gsxform/scattering.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def get_wavelets(
    self, W_adj: torch.Tensor, mask: torch.Tensor | None = None
) -> torch.Tensor:
    """Compute the wavelet operator.

    Subclasses are required to implement this method.

    Parameters
    ----------
    W_adj: torch.Tensor
        Batch of weighted adjacency matrices. Padded nodes have no edges.
    mask: torch.Tensor, optional
        Boolean tensor shaped (batch, n_nodes), true on real nodes. None
        when every graph fills all `n_nodes`.
    """
    raise NotImplementedError

path_index

path_index()

List the scale path behind each scattering coefficient.

Returns:

Type Description
list[tuple[int, ...]]

One tuple of scale indices per coefficient, in output order: () for the input itself, (j1,) for the first layer, (j1, j2) for the second, and so on

Source code in gsxform/scattering.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def path_index(self) -> list[tuple[int, ...]]:
    """List the scale path behind each scattering coefficient.

    Returns
    -------
    list[tuple[int, ...]]
        One tuple of scale indices per coefficient, in output order: `()`
        for the input itself, `(j1,)` for the first layer, `(j1, j2)` for
        the second, and so on
    """
    paths: list[tuple[int, ...]] = [()]
    layer: list[tuple[int, ...]] = [()]
    for _ in range(1, self.n_layers):
        layer = [path + (jj,) for path in layer for jj in range(self.n_scales)]
        paths.extend(layer)
    return paths

reset_parameters

reset_parameters()

Clear the cached filter bank.

Source code in gsxform/scattering.py
192
193
194
195
196
def reset_parameters(self) -> None:
    """Clear the cached filter bank."""
    self._cached_adj = None
    self._cached_mask = None
    self._cached_psi = None

Diffusion

Diffusion(
    n_scales,
    n_layers,
    nlin=torch.abs,
    cached=False,
    output="graph",
    aggregation="mean",
    moments=(1, 2, 3, 4),
)

Bases: ScatteringTransform

Diffusion scattering transform.

Subclass of ScatteringTransform, implements get_wavelets method. Diffusion scattering transform algorithm based on description in Gama et. al 2018.

Parameters:

Name Type Description Default
n_scales int

Number of scales to use in wavelet transform

required
n_layers int

Number of layers in the scattering transform

required
nlin Callable[[Tensor], Tensor]

Non-linearity used in the scattering transform. Defaults to torch.abs

abs
cached bool

Cache the filter bank while the adjacency is unchanged. Defaults to False

False
output Literal['graph', 'node']

"graph" or "node", see ScatteringTransform. Defaults to "graph"

'graph'
aggregation Literal['mean', 'moments']

"mean" or "moments", see ScatteringTransform. Defaults to "mean"

'mean'
moments tuple[int, ...]

Moment orders for aggregation="moments". Defaults to (1, 2, 3, 4)

(1, 2, 3, 4)
Source code in gsxform/scattering.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
def __init__(
    self,
    n_scales: int,
    n_layers: int,
    nlin: Callable[[torch.Tensor], torch.Tensor] = torch.abs,
    cached: bool = False,
    output: Literal["graph", "node"] = "graph",
    aggregation: Literal["mean", "moments"] = "mean",
    moments: tuple[int, ...] = (1, 2, 3, 4),
) -> None:
    """Initialize diffusion scattering transform.

    Parameters
    ----------
    n_scales: int
        Number of scales to use in wavelet transform
    n_layers: int
        Number of layers in the scattering transform
    nlin: Callable[torch.Tensor]
        Non-linearity used in the scattering transform. Defaults to torch.abs
    cached: bool
        Cache the filter bank while the adjacency is unchanged. Defaults to
        False
    output: str
        "graph" or "node", see `ScatteringTransform`. Defaults to "graph"
    aggregation: str
        "mean" or "moments", see `ScatteringTransform`. Defaults to "mean"
    moments: tuple[int, ...]
        Moment orders for `aggregation="moments"`. Defaults to (1, 2, 3, 4)

    """
    super().__init__(n_scales, n_layers, nlin, cached, output, aggregation, moments)

get_wavelets

get_wavelets(W_adj, mask=None)

Subclass method used to get wavelet filter bank.

This method returns diffusion wavelets

Parameters:

Name Type Description Default
W_adj Tensor

Batch of weighted adjacency matrices

required
mask Tensor | None

Unused because T` is block diagonal

None

Returns:

Name Type Description
psi Tensor

diffusion wavelet operator

Source code in gsxform/scattering.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
def get_wavelets(
    self, W_adj: torch.Tensor, mask: torch.Tensor | None = None
) -> torch.Tensor:
    """Subclass method used to get wavelet filter bank.

    This method returns diffusion wavelets

    Parameters
    ----------
    W_adj: torch.Tensor
        Batch of weighted adjacency matrices
    mask: torch.Tensor, optional
        Unused because T` is block diagonal

    Returns
    -------
    psi: torch.Tensor
        diffusion wavelet operator

    """
    # compute diffusion matrix
    T = lazy_diffusion(W_adj)
    # compute wavelet operator
    psi = diffusion_wavelets(T, self.n_scales)

    return psi

TightHann

TightHann(
    n_scales,
    n_layers,
    nlin=torch.abs,
    use_warp=True,
    cached=False,
    output="graph",
    aggregation="mean",
    moments=(1, 2, 3, 4),
)

Bases: ScatteringTransform

TightHann scattering transform.

Subclass of ScatteringTransform, implements get_wavelets methods. Also additionally implements functions used to compute spectrum-adaptive wavelets.

Parameters:

Name Type Description Default
n_scales int

Number of scales to use in wavelet transform

required
n_layers int

Number of layers in the scattering transform

required
nlin Callable[[Tensor], Tensor]

Non-linearity used in the scattering transform. Defaults to torch.abs

abs
use_warp bool

Use warping function. Defaults to True

True
cached bool

Cache the filter bank while the adjacency is unchanged. Defaults to False

False
output Literal['graph', 'node']

"graph" or "node", see ScatteringTransform. Defaults to "graph"

'graph'
aggregation Literal['mean', 'moments']

"mean" or "moments", see ScatteringTransform. Defaults to "mean"

'mean'
moments tuple[int, ...]

Moment orders for aggregation="moments". Defaults to (1, 2, 3, 4)

(1, 2, 3, 4)
Source code in gsxform/scattering.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
def __init__(
    self,
    n_scales: int,
    n_layers: int,
    nlin: Callable[[torch.Tensor], torch.Tensor] = torch.abs,
    use_warp: bool = True,
    cached: bool = False,
    output: Literal["graph", "node"] = "graph",
    aggregation: Literal["mean", "moments"] = "mean",
    moments: tuple[int, ...] = (1, 2, 3, 4),
) -> None:
    """Initialize tight Hann scattering transform.

    Parameters
    ----------
    n_scales: int
        Number of scales to use in wavelet transform
    n_layers: int
        Number of layers in the scattering transform
    nlin: Callable[torch.Tensor]
        Non-linearity used in the scattering transform. Defaults to torch.abs
    use_warp: bool
        Use warping function. Defaults to True
    cached: bool
        Cache the filter bank while the adjacency is unchanged. Defaults to
        False
    output: str
        "graph" or "node", see `ScatteringTransform`. Defaults to "graph"
    aggregation: str
        "mean" or "moments", see `ScatteringTransform`. Defaults to "mean"
    moments: tuple[int, ...]
        Moment orders for `aggregation="moments"`. Defaults to (1, 2, 3, 4)

    """
    super().__init__(n_scales, n_layers, nlin, cached, output, aggregation, moments)
    self.use_warp = use_warp

get_kernel

get_kernel(E, mask=None)

Compute TightHann kernel adaptively.

Parameters:

Name Type Description Default
E Tensor

Eigenvalues of each graph's Laplacian, shaped (batch, n_nodes)

required
mask Tensor | None

Boolean tensor shaped (batch, n_nodes), true on real nodes

None

Returns:

Type Description
TightHannKernel

Kernel adapted to each graph's spectrum

Source code in gsxform/scattering.py
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
def get_kernel(
    self, E: torch.Tensor, mask: torch.Tensor | None = None
) -> TightHannKernel:
    """Compute TightHann kernel adaptively.

    Parameters
    ----------
    E: torch.Tensor
        Eigenvalues of each graph's Laplacian, shaped (batch, n_nodes)
    mask: torch.Tensor, optional
        Boolean tensor shaped (batch, n_nodes), true on real nodes

    Returns
    -------
    TightHannKernel
        Kernel adapted to each graph's spectrum
    """
    # sort within each graph
    spectra, _ = torch.sort(E, dim=-1)
    return TightHannKernel(
        self.n_scales, spectra[:, -1], self.warp_func(spectra, mask)
    )

get_wavelets

get_wavelets(W_adj, mask=None)

Subclass method used to get wavelet filter bank.

This method returns tight Hann wavelets

Parameters:

Name Type Description Default
W_adj Tensor

Batch of weighted adjacency matrices

required
mask Tensor | None

Padding mask, boolean tensor shaped (batch, n_nodes)

None

Returns:

Name Type Description
psi Tensor

tight Hann wavelet operator

Source code in gsxform/scattering.py
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
def get_wavelets(
    self, W_adj: torch.Tensor, mask: torch.Tensor | None = None
) -> torch.Tensor:
    """Subclass method used to get wavelet filter bank.

    This method returns tight Hann wavelets

    Parameters
    ----------
    W_adj: torch.Tensor
        Batch of weighted adjacency matrices
    mask: torch.Tensor, optional
        Padding mask, boolean tensor shaped (batch, n_nodes)

    Returns
    -------
    psi: torch.Tensor
        tight Hann wavelet operator

    """
    E, V = compute_spectra(W_adj)
    psi = tighthann_wavelets(
        W_adj, self.n_scales, self.get_kernel(E, mask), spectra=(E, V)
    )

    return psi

warp_func

warp_func(spectra, mask=None)

Compute the spectrum-adaptive warping function.

Parameters:

Name Type Description Default
spectra Tensor

Eigenvalues of each graph's Laplacian, sorted ascending, shaped (batch, n_nodes)

required
mask Tensor | None

Boolean tensor shaped (batch, n_nodes), true on real nodes

None

Returns:

Type Description
Callable[[Tensor], Tensor]

Per-graph piecewise linear approximation of the spectral CDF

Source code in gsxform/scattering.py
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
def warp_func(
    self, spectra: torch.Tensor, mask: torch.Tensor | None = None
) -> Callable[[torch.Tensor], torch.Tensor]:
    """Compute the spectrum-adaptive warping function.

    Parameters
    ----------
    spectra: torch.Tensor
        Eigenvalues of each graph's Laplacian, sorted ascending, shaped
        (batch, n_nodes)
    mask: torch.Tensor, optional
        Boolean tensor shaped (batch, n_nodes), true on real nodes

    Returns
    -------
    Callable[[torch.Tensor], torch.Tensor]
        Per-graph piecewise linear approximation of the spectral CDF
    """
    if mask is None:
        xp, fp = self._warp_points(spectra)
    else:
        # padded nodes add an extra eigenvalue at zero, needs to be removed
        # for CDF to be correct
        n_eigs = spectra.shape[-1]
        points = [
            self._warp_points(spec[n_eigs - int(n_real) :].unsqueeze(0))
            for spec, n_real in zip(spectra, mask.sum(dim=-1), strict=True)
        ]
        width = max(xp_i.shape[-1] for xp_i, _ in points)

        # left-pad by repeating the first point
        xp = torch.cat([_left_pad(xp_i, width) for xp_i, _ in points], dim=0)
        fp = torch.cat([_left_pad(fp_i, width) for _, fp_i in points], dim=0)

    # switched from lambda to partial so the kernel stays picklable
    return partial(_interp, xp=xp.contiguous(), fp=fp.contiguous())