Skip to content

API Reference

GTSOM

gtsom.GTSOM

GTSOM(
    rho_0,
    rho_f,
    tau=None,
    halflife_epochs=None,
    anneal="exponential",
    n_jobs=None,
    nbr_topo_alpha_0=1.0,
    nbr_topo_alpha_f=None,
    proto_topo="CONN_GD",
    compute_dr_metrics=False,
    nbr_influence_min=0.01,
    random_state=None,
)

General Topology Self-Organizing Map.

The constructor sets all learning parameters (schedules, parallelism, diagnostics). After construction, call :meth:from_grid or :meth:from_data to set the output topology and initialize prototypes, then call :meth:fit to train.

Parameters:

Name Type Description Default
rho_0 float

Initial neighborhood bandwidth.

required
rho_f float

Final (minimum) neighborhood bandwidth.

required
tau float

Exponential decay time constant in epochs. Mutually exclusive with halflife_epochs.

None
halflife_epochs float

Epoch at which each annealed parameter reaches the geometric midpoint between its initial and final values. Mutually exclusive with tau.

None
anneal exponential

Annealing schedule type. Currently only exponential decay is supported.

'exponential'
n_jobs int or None

Number of parallel threads for prototype updates. None or -1 uses all available CPU cores. Ignored with a warning if numba is not installed.

None
nbr_topo_alpha_0 float

Initial value of the topology-blending parameter, in [0, 1]. When 1.0, pure lattice-based neighborhood (classical SOM). When < 1.0, a blend of lattice and CONN-graph neighborhood is used. See :meth:_compute_neighborhood for the full blending rule.

1.0
nbr_topo_alpha_f float

Final value of the topology-blending parameter, in [0, 1]. Defaults to nbr_topo_alpha_0 for a flat (non-annealing) schedule.

None
compute_dr_metrics bool

Whether to compute dimensionality reduction quality metrics at each snapshot. When True, each entry in learn_history_ will contain a :class:~gtsom.dr_metrics.DRMetricsResult with co-ranking and CONN_WAFL metrics.

False
nbr_influence_min float

Neighbourhood kernel activation floor. Kernel weights below this value are zeroed. Shared across all architecture configurations built on this instance.

0.01
proto_topo (CONN_GD, STK_CADJ, STK_dense)

Input-space (prototype) topology used to compute the high-dimensional neighborhood signal when nbr_topo_alpha < 1.0. Has no effect when nbr_topo_alpha_0 == nbr_topo_alpha_f == 1.0.

'CONN_GD' CONN geodesic distances. The CONN matrix is treated as an unweighted graph; shortest-path hop counts are computed and fed through the standard exponential kernel. Purely topological — ignores Euclidean distances between prototypes. 'STK_CADJ' Self-tuning kernel, CADJ-constrained support. The kernel is evaluated only for prototype pairs where CADJ[i,j] > 0 (after padding via pad_CADJ to ensure every row has at least 3 neighbors). CADJ weights define sigma_i (local bandwidth); the kernel is K[i,j] = exp(-dist²(W[i],W[j]) / (sigma_i * sigma_j)) ** (1/rho). Cheaper than 'STK_dense' for large M; closer in spirit to 'CONN_GD' (topologically constrained). 'STK_dense' Self-tuning kernel, dense support. The kernel is evaluated for all M×M prototype pairs, with entries below nbr_influence_min zeroed after rho scaling. CADJ weights define sigma_i only; the sparsity pattern is unconstrained. Most similar to Neural Gas: purely Euclidean, locally adaptive bandwidth. Recommended default when proto_topo is active.

'CONN_GD'
random_state int or None

Seed for all random operations.

None
Notes

GTSOM does not perform any internal scaling of X. It is the caller's responsibility to whiten, standardize, or otherwise preprocess X before passing it to any method.

Raises:

Type Description
ValueError

If neither or both of tau and halflife_epochs are supplied, if anneal is not recognized, if either alpha parameter is outside [0, 1], if nbr_influence_min is not in (0, 1), or if proto_topo is not recognized.

Source code in src/gtsom/gtsom.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
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
344
345
346
347
348
349
350
351
352
353
354
355
def __init__(
    self,
    rho_0,
    rho_f,
    tau=None,
    halflife_epochs=None,
    anneal='exponential',
    n_jobs=None,
    nbr_topo_alpha_0=1.0,
    nbr_topo_alpha_f=None,
    proto_topo='CONN_GD',
    compute_dr_metrics=False,
    nbr_influence_min=0.01,
    random_state=None,
):
    # ------------------------------------------------------------------
    # Validate schedule parameters
    # ------------------------------------------------------------------
    if anneal not in ('exponential',):
        raise ValueError(
            f"anneal must be 'exponential', got {anneal!r}. "
            "Additional schedules may be added in future."
        )
    if tau is None and halflife_epochs is None:
        raise ValueError(
            "Exactly one of tau or halflife_epochs must be supplied."
        )
    if tau is not None and halflife_epochs is not None:
        raise ValueError(
            "Supply either tau or halflife_epochs, not both."
        )

    alpha_f = nbr_topo_alpha_f if nbr_topo_alpha_f is not None else nbr_topo_alpha_0
    if not (0.0 <= nbr_topo_alpha_0 <= 1.0):
        raise ValueError(
            f"nbr_topo_alpha_0 must be in [0, 1], got {nbr_topo_alpha_0}."
        )
    if not (0.0 <= alpha_f <= 1.0):
        raise ValueError(
            f"nbr_topo_alpha_f must be in [0, 1], got {alpha_f}."
        )
    if not (0.0 < nbr_influence_min < 1.0):
        raise ValueError(
            f"nbr_influence_min must be in (0, 1), got {nbr_influence_min}."
        )
    if proto_topo not in ('CONN_GD', 'STK_CADJ', 'STK_dense'):
        raise ValueError(
            f"proto_topo must be 'CONN_GD', 'STK_CADJ', or 'STK_dense', "
            f"got {proto_topo!r}."
        )

    # ------------------------------------------------------------------
    # Build annealing schedules
    # ------------------------------------------------------------------
    if tau is not None:
        self.rho_schedule   = ExponentialAnneal(
            initial=rho_0, final=rho_f, tau=tau
        )
        self.alpha_schedule = ExponentialAnneal(
            initial=nbr_topo_alpha_0, final=alpha_f, tau=tau
        )
    else:
        self.rho_schedule   = ExponentialAnneal.from_halflife(
            initial=rho_0, final=rho_f, halflife_epochs=halflife_epochs
        )
        self.alpha_schedule = ExponentialAnneal.from_halflife(
            initial=nbr_topo_alpha_0, final=alpha_f,
            halflife_epochs=halflife_epochs
        )

    # ------------------------------------------------------------------
    # Store learning configuration
    # ------------------------------------------------------------------
    self.nbr_influence_min = nbr_influence_min
    self.proto_topo         = proto_topo
    self.random_state       = random_state
    self.compute_dr_metrics = bool(compute_dr_metrics)

    # Resolve and store thread count
    if not PARALLEL and n_jobs is not None and n_jobs != 1:
        import warnings
        warnings.warn(
            f"n_jobs={n_jobs} ignored: numba is not installed. "
            "Install numba for parallel prototype updates.",
            UserWarning, stacklevel=2,
        )
    self.n_jobs = resolve_n_jobs(n_jobs)

    # ------------------------------------------------------------------
    # Architecture attributes — None until from_grid / from_data is called
    # ------------------------------------------------------------------
    self.W          = None   # prototype matrix (M, d)
    self.embed      = None   # Embedding instance
    self.recaller   = None   # VQRecaller instance
    self.kernel     = None   # NeighborKernel instance
    self._validator = None   # DataValidator instance
    self.prevBMU    = None   # (N,) previous-epoch BMU assignments
    self.W0         = None   # initial prototype matrix (never modified)
    self.coords0    = None   # initial embedding coords (never modified)
    self.nbr_W      = None   # neighborhood weight matrix (M, M)
    self.ctab       = None   # {str_label: hex_color} dict, or None if no labels

    # ------------------------------------------------------------------
    # Training state
    # ------------------------------------------------------------------
    self.age         = 0     # total epochs completed
    self.train_time  = 0.0   # cumulative wall-clock training time (s)

    # Learning history: list of snapshot dicts, one per recorded epoch.
    # learn_history_[0] is the post-architecture-init state (age=0),
    # populated by from_grid / from_data. Subsequent entries are
    # appended by fit() after each epoch.
    # Each dict contains:
    #   'age'        : int              — self.age at snapshot time
    #   'mqe'        : float            — global RMSE over all data
    #                                     (sqrt of mean squared L2 dist)
    #   'W_mqe'      : ndarray (M,)     — per-prototype RMSE, nan for empty RFs
    #   'delBMU'     : float            — fraction of data whose BMU changed
    #   'dr_metrics' : DRMetricsResult  — DR quality metrics, or None
    #   'coords'     : ndarray (M, 2)   — prototype output-space positions
    #   'adjacency'  : csr_matrix       — graph topology (M, M)
    #   'RFSize'     : ndarray (M,)     — receptive field sizes
    #   'WL'         : ndarray (M,) or None — winning label per prototype
    #   'color_by'   : str              — resolved color mode at snapshot time
    self.learn_history_ = []

M property

M

Number of prototypes (neurons).

d property

d

Dimensionality of the high-dimensional feature space.

from_grid

from_grid(
    X,
    shape,
    coord_init="hex",
    W_init="random",
    labels=None,
    ctab=None,
)

Set a regular grid output topology and initialize prototypes.

Wipes any existing architecture (W, embed, recaller, learn_history_, etc.) and builds a fresh grid-based configuration. All learning parameters (rho schedules, nbr_influence_min, etc.) are inherited from the values set in __init__ and are not changed.

Parameters:

Name Type Description Default
X (array - like, shape(N, d))

Training data. Used for prototype initialisation; not stored.

required
shape tuple of int

Grid dimensions, e.g. (10, 10) or (5, 10, 4). The length of the tuple sets the embedding dimension (2 or 3).

required
coord_init (hex, rect)

Grid layout. 'hex' uses a hexagonal arrangement (Delaunay adjacency); 'rect' uses an 8-connected rectangular grid.

'hex'
W_init (random, pca)

How to initialize prototype vectors W.

'random' Random sample of M rows from X. 'pca' Back-project grid neuron coordinates through the PCA of X, placing each prototype at the corresponding point in high-d feature space.

'random'
labels (array - like, shape(N))

Optional observation labels. If provided, prototype-level label summaries (WL, WL_Dist, WL_Purity) are computed during the initial recall and stored on self.recaller. Labels must also be supplied on every subsequent call to :meth:fit to keep per-epoch snapshot WL values current.

None
ctab dict or None

Optional {label: hex_color_string} color table, as returned by :func:~gtsom.vis_tools.parse_ctab. When provided it is stored as self.ctab and used for all label-colored plots. When None and labels are provided, a color table is generated automatically via :func:~gtsom.vis_tools.build_ctab. Ignored when labels is None.

None

Returns:

Name Type Description
self GTSOM

Returns self for optional method chaining.

Raises:

Type Description
ValueError

If shape is not a 2- or 3-tuple, coord_init or W_init are not recognized, or the grid has more neurons than data points.

Source code in src/gtsom/gtsom.py
385
386
387
388
389
390
391
392
393
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
426
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
def from_grid(
    self,
    X,
    shape,
    coord_init='hex',
    W_init='random',
    labels=None,
    ctab=None,
):
    """
    Set a regular grid output topology and initialize prototypes.

    Wipes any existing architecture (W, embed, recaller, learn_history_,
    etc.) and builds a fresh grid-based configuration. All learning
    parameters (rho schedules, nbr_influence_min, etc.) are inherited from the
    values set in ``__init__`` and are not changed.

    Parameters
    ----------
    X : array-like, shape (N, d)
        Training data. Used for prototype initialisation; not stored.
    shape : tuple of int
        Grid dimensions, e.g. ``(10, 10)`` or ``(5, 10, 4)``. The
        length of the tuple sets the embedding dimension (2 or 3).
    coord_init : {'hex', 'rect'}, default 'hex'
        Grid layout. ``'hex'`` uses a hexagonal arrangement (Delaunay
        adjacency); ``'rect'`` uses an 8-connected rectangular grid.
    W_init : {'random', 'pca'}, default 'random'
        How to initialize prototype vectors W.

        ``'random'``
            Random sample of M rows from X.
        ``'pca'``
            Back-project grid neuron coordinates through the PCA of X,
            placing each prototype at the corresponding point in high-d
            feature space.
    labels : array-like, shape (N,), default None
        Optional observation labels. If provided, prototype-level label
        summaries (WL, WL_Dist, WL_Purity) are computed during the
        initial recall and stored on ``self.recaller``. Labels must also
        be supplied on every subsequent call to :meth:`fit` to keep
        per-epoch snapshot ``WL`` values current.
    ctab : dict or None, default None
        Optional ``{label: hex_color_string}`` color table, as returned
        by :func:`~gtsom.vis_tools.parse_ctab`. When provided it is
        stored as ``self.ctab`` and used for all label-colored plots.
        When ``None`` and ``labels`` are provided, a color table is
        generated automatically via
        :func:`~gtsom.vis_tools.build_ctab`. Ignored when ``labels``
        is ``None``.

    Returns
    -------
    self : GTSOM
        Returns self for optional method chaining.

    Raises
    ------
    ValueError
        If ``shape`` is not a 2- or 3-tuple, ``coord_init`` or
        ``W_init`` are not recognized, or the grid has more neurons
        than data points.
    """
    if coord_init not in ('hex', 'rect'):
        raise ValueError(
            f"coord_init must be 'hex' or 'rect' for from_grid, "
            f"got {coord_init!r}"
        )
    if W_init not in ('random', 'pca'):
        raise ValueError(
            f"W_init must be 'random' or 'pca' for from_grid, "
            f"got {W_init!r}"
        )
    if len(shape) not in (2, 3):
        raise ValueError(
            f"shape must be a 2- or 3-tuple, got length {len(shape)}"
        )

    X = np.asarray(X)
    if X.ndim != 2:
        raise ValueError(f"X must be 2-D, got shape {X.shape}")
    rng = np.random.default_rng(self.random_state)

    # Build embedding — grid kind matches coord_init
    embed = Embedding.from_grid(shape, kind=coord_init)
    M = embed.coords.shape[0]

    if M > X.shape[0]:
        raise ValueError(
            f"Grid has {M} neurons but X has only {X.shape[0]} rows. "
            f"Reduce shape or provide more data."
        )

    # Initialise W
    if W_init == 'random':
        W = _init_W_random(X, M, rng)
    else:  # 'pca'
        W = _init_W_pca(X, embed, self.random_state)

    self._init_architecture(X, W, embed, labels, ctab)
    return self

from_data

from_data(
    X,
    M,
    coord_dim=2,
    coord_init="pca",
    W_init="kmeans",
    coord_topo="delaunay",
    labels=None,
    ctab=None,
)

Set a data-driven output topology and initialize prototypes.

Wipes any existing architecture (W, embed, recaller, learn_history_, etc.) and builds a fresh data-driven configuration. All learning parameters (rho schedules, nbr_influence_min, etc.) are inherited from the values set in __init__ and are not changed.

Prototype vectors are found via vector quantisation of X, projected to coord_dim dimensions to define neuron positions, and either a Delaunay triangulation or Gabriel graph of those positions defines the output topology.

Parameters:

Name Type Description Default
X (array - like, shape(N, d))

Training data.

required
M int

Number of prototypes (neurons). Must be >= 3 (required for Delaunay triangulation) and <= N.

required
coord_dim (2, 3)

Dimensionality of the output embedding.

2
coord_init (pca, le, random, random_proj)

Dimensionality reduction method for computing neuron coordinates from the initial prototype vectors.

'pca' Randomised PCA (fast, linear). The natural default when W_init='kmeans', since k-means centroids carry data structure that PCA can meaningfully summarise. 'le' Laplacian Eigenmaps via sklearn SpectralEmbedding (nonlinear, slower). Useful when the data manifold is curved. 'random' Sample M points uniformly at random from the unit hypercube in coord_dim dimensions. Produces a completely unstructured initial layout — the strongest possible "worst-case" starting state for illustrating how self-organising learning imposes order. Particularly effective for exposition when combined with W_init='random'. 'random_proj' Johnson-Lindenstrauss random projection: multiply W by a random Gaussian matrix scaled by 1 / sqrt(coord_dim). Preserves approximate pairwise distances in expectation at zero computational cost, giving a random but structurally grounded starting layout.

'pca'
W_init (kmeans, random)

How to find initial prototype vectors.

'kmeans' FAISS k-means via VQFitter (requires vqlp). 'random' Random sample of M rows from X.

'kmeans'
coord_topo (delaunay, gabriel)

Graph used to define the output-space topology from the projected prototype coordinates.

'delaunay' Delaunay triangulation. Denser connectivity. 'gabriel' Gabriel graph (subgraph of Delaunay). Sparser connectivity that more closely reflects local proximity structure.

'delaunay'
labels (array - like, shape(N))

Optional observation labels. If provided, prototype-level label summaries (WL, WL_Dist, WL_Purity) are computed during the initial recall and stored on self.recaller. Labels must also be supplied on every subsequent call to :meth:fit to keep per-epoch snapshot WL values current.

None
ctab dict or None

Optional {label: hex_color_string} color table, as returned by :func:~gtsom.vis_tools.parse_ctab. When provided it is stored as self.ctab and used for all label-colored plots. When None and labels are provided, a color table is generated automatically via :func:~gtsom.vis_tools.build_ctab. Ignored when labels is None.

None

Returns:

Name Type Description
self GTSOM

Returns self for optional method chaining.

Raises:

Type Description
ValueError

If coord_dim is not 2 or 3, or if any of coord_init, W_init, or coord_topo are not recognized, or M is out of range.

ImportError

If W_init='kmeans' and vqlp is not installed.

Source code in src/gtsom/gtsom.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
def from_data(
    self,
    X,
    M,
    coord_dim=2,
    coord_init='pca',
    W_init='kmeans',
    coord_topo='delaunay',
    labels=None,
    ctab=None,
):
    """
    Set a data-driven output topology and initialize prototypes.

    Wipes any existing architecture (W, embed, recaller, learn_history_,
    etc.) and builds a fresh data-driven configuration. All learning
    parameters (rho schedules, nbr_influence_min, etc.) are inherited from the
    values set in ``__init__`` and are not changed.

    Prototype vectors are found via vector quantisation of X, projected
    to ``coord_dim`` dimensions to define neuron positions, and either
    a Delaunay triangulation or Gabriel graph of those positions defines
    the output topology.

    Parameters
    ----------
    X : array-like, shape (N, d)
        Training data.
    M : int
        Number of prototypes (neurons). Must be >= 3 (required for
        Delaunay triangulation) and <= N.
    coord_dim : {2, 3}, default 2
        Dimensionality of the output embedding.
    coord_init : {'pca', 'le', 'random', 'random_proj'}, default 'pca'
        Dimensionality reduction method for computing neuron coordinates
        from the initial prototype vectors.

        ``'pca'``
            Randomised PCA (fast, linear). The natural default when
            ``W_init='kmeans'``, since k-means centroids carry data
            structure that PCA can meaningfully summarise.
        ``'le'``
            Laplacian Eigenmaps via sklearn SpectralEmbedding
            (nonlinear, slower). Useful when the data manifold is
            curved.
        ``'random'``
            Sample ``M`` points uniformly at random from the unit
            hypercube in ``coord_dim`` dimensions. Produces a
            completely unstructured initial layout — the strongest
            possible "worst-case" starting state for illustrating
            how self-organising learning imposes order. Particularly
            effective for exposition when combined with
            ``W_init='random'``.
        ``'random_proj'``
            Johnson-Lindenstrauss random projection: multiply ``W``
            by a random Gaussian matrix scaled by
            ``1 / sqrt(coord_dim)``. Preserves approximate pairwise
            distances in expectation at zero computational cost,
            giving a random but structurally grounded starting layout.
    W_init : {'kmeans', 'random'}, default 'kmeans'
        How to find initial prototype vectors.

        ``'kmeans'``
            FAISS k-means via VQFitter (requires vqlp).
        ``'random'``
            Random sample of M rows from X.
    coord_topo : {'delaunay', 'gabriel'}, default 'delaunay'
        Graph used to define the output-space topology from the
        projected prototype coordinates.

        ``'delaunay'``
            Delaunay triangulation. Denser connectivity.
        ``'gabriel'``
            Gabriel graph (subgraph of Delaunay). Sparser connectivity
            that more closely reflects local proximity structure.
    labels : array-like, shape (N,), default None
        Optional observation labels. If provided, prototype-level label
        summaries (WL, WL_Dist, WL_Purity) are computed during the
        initial recall and stored on ``self.recaller``. Labels must also
        be supplied on every subsequent call to :meth:`fit` to keep
        per-epoch snapshot ``WL`` values current.
    ctab : dict or None, default None
        Optional ``{label: hex_color_string}`` color table, as returned
        by :func:`~gtsom.vis_tools.parse_ctab`. When provided it is
        stored as ``self.ctab`` and used for all label-colored plots.
        When ``None`` and ``labels`` are provided, a color table is
        generated automatically via
        :func:`~gtsom.vis_tools.build_ctab`. Ignored when ``labels``
        is ``None``.

    Returns
    -------
    self : GTSOM
        Returns self for optional method chaining.

    Raises
    ------
    ValueError
        If ``coord_dim`` is not 2 or 3, or if any of ``coord_init``,
        ``W_init``, or ``coord_topo`` are not recognized, or M is out
        of range.
    ImportError
        If ``W_init='kmeans'`` and vqlp is not installed.
    """
    if coord_dim not in (2, 3):
        raise ValueError(f"coord_dim must be 2 or 3, got {coord_dim!r}")
    if coord_init not in ('pca', 'le', 'random', 'random_proj'):
        raise ValueError(
            f"coord_init must be 'pca', 'le', 'random', or 'random_proj' "
            f"for from_data, got {coord_init!r}"
        )
    if coord_topo not in ('delaunay', 'gabriel'):
        raise ValueError(
            f"coord_topo must be 'delaunay' or 'gabriel', "
            f"got {coord_topo!r}"
        )
    if W_init not in ('kmeans', 'random'):
        raise ValueError(
            f"W_init must be 'kmeans' or 'random' for from_data, "
            f"got {W_init!r}"
        )
    if M > X.shape[0]:
        raise ValueError(
            f"M={M} exceeds number of data points N={X.shape[0]}."
        )
    if M < 3:
        raise ValueError(
            f"M must be at least 3 for Delaunay triangulation, got {M}."
        )

    X = np.asarray(X)
    rng = np.random.default_rng(self.random_state)

    # Step 1: initialize prototype vectors in high-d
    if W_init == 'kmeans':
        W = _init_W_kmeans(X, M, self.random_state)
    else:  # 'random'
        W = _init_W_random(X, M, rng)

    # Step 2: project W to coord_dim to define neuron positions
    if coord_init == 'pca':
        coords = reduce_coords_pca(W, coord_dim, self.random_state)
    elif coord_init == 'le':
        coords = reduce_coords_le(W, coord_dim, self.random_state)
    elif coord_init == 'random':
        coords = reduce_coords_random(M, coord_dim, self.random_state)
    else:  # 'random_proj'
        coords = reduce_coords_random_proj(W, coord_dim, self.random_state)

    # Step 3: build embedding from projected coords using chosen topology
    if coord_topo == 'delaunay':
        embed = Embedding.from_delaunay(coords)
    else:  # 'gabriel'
        embed = Embedding.from_gabriel(coords)

    self._init_architecture(X, W, embed, labels, ctab)
    return self

fit

fit(X, n_epochs, labels=None, verbose=True, plot_every=5)

Fit the GTSOM to data X using batch SOM learning.

:meth:from_grid or :meth:from_data must be called before :meth:fit. The rho annealing schedule advances based on self.age, so successive calls to :meth:fit continue from where the previous call left off.

Parameters:

Name Type Description Default
X (array - like, shape(N, d))

Training data. Should be the same dataset passed to :meth:from_grid or :meth:from_data.

required
n_epochs int

Number of training epochs to run in this call.

required
labels (array - like, shape(N))

Observation labels. If labels were provided at :meth:from_grid or :meth:from_data time, the same labels must be supplied here on every call so that per-epoch snapshot WL values remain current and consistent with self.ctab. A :class:~gtsom.utils.DataValidator warning is issued if labels are omitted or differ from those supplied at initialization. If no labels were provided at initialization, this parameter should be None.

None
verbose bool

If True, print a formatted table of training metrics after each epoch.

True
plot_every int

Display a SOM plot every this many epochs during training. Set to 0 to disable in-training plotting.

5

Raises:

Type Description
RuntimeError

If :meth:from_grid or :meth:from_data has not been called.

Notes

GTSOM does not perform any internal scaling of X.

Source code in src/gtsom/gtsom.py
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
def fit(self, X, n_epochs, labels=None, verbose=True, plot_every=5):
    """
    Fit the GTSOM to data X using batch SOM learning.

    :meth:`from_grid` or :meth:`from_data` must be called before
    :meth:`fit`. The rho annealing schedule advances based on
    ``self.age``, so successive calls to :meth:`fit` continue from
    where the previous call left off.

    Parameters
    ----------
    X : array-like, shape (N, d)
        Training data. Should be the same dataset passed to
        :meth:`from_grid` or :meth:`from_data`.
    n_epochs : int
        Number of training epochs to run in this call.
    labels : array-like, shape (N,), default None
        Observation labels. If labels were provided at
        :meth:`from_grid` or :meth:`from_data` time, the same labels
        must be supplied here on every call so that per-epoch snapshot
        ``WL`` values remain current and consistent with ``self.ctab``.
        A :class:`~gtsom.utils.DataValidator` warning is issued if
        labels are omitted or differ from those supplied at
        initialization. If no labels were provided at initialization,
        this parameter should be ``None``.
    verbose : bool, default True
        If True, print a formatted table of training metrics after
        each epoch.
    plot_every : int, default 5
        Display a SOM plot every this many epochs during training.
        Set to 0 to disable in-training plotting.

    Raises
    ------
    RuntimeError
        If :meth:`from_grid` or :meth:`from_data` has not been called.

    Notes
    -----
    GTSOM does not perform any internal scaling of X.
    """
    if self.W is None:
        raise RuntimeError(
            "Architecture not initialized. "
            "Call from_grid() or from_data() before fit()."
        )

    X = np.asarray(X)
    if self._validator is not None:
        self._validator.check(X, labels=labels, context="fit")

    _HDR = f"{'Epoch':>7}   {'rho':>6}   {'alpha':>6}   {'MQE':>8}   {'delBMU':>7}"
    _SEP = f"{'-----':>7}   {'------':>6}   {'------':>6}   {'--------':>8}   {'-------':>7}"

    if verbose:
        print(_HDR)
        print(_SEP)

    # Apply thread count for this fit() call; restore afterward
    if PARALLEL:
        from numba import set_num_threads, get_num_threads
        _prev_threads = get_num_threads()
        set_num_threads(self.n_jobs)

    _t0 = time.perf_counter()
    for local_epoch in range(n_epochs):
        rho   = self.rho_schedule(self.age)
        alpha = self.alpha_schedule(self.age)
        self._compute_neighborhood(rho, alpha)
        self._update_prototypes(X)
        self._recall(X, labels=labels)
        self.age += 1
        include_fig = plot_every > 0 and (self.age % plot_every == 0)
        self._snapshot(include_fig=include_fig)
        if verbose:
            snap = self.learn_history_[-1]
            print(
                f"{self.age:>7d}   {rho:>6.4f}   {alpha:>6.4f}   "
                f"{snap['mqe']:>8.4f}   {snap['delBMU']:>7.4f}"
            )
            if (local_epoch + 1) % 10 == 0:
                print(_SEP)

    if verbose:
        print(_SEP)

    self.train_time += time.perf_counter() - _t0

    if PARALLEL:
        set_num_threads(_prev_threads)

transform

transform(X)

Map data points to output coordinates via BMU lookup.

Parameters:

Name Type Description Default
X (array - like, shape(N, d))
required

Returns:

Name Type Description
coords (ndarray, shape(N, dim))

Raises:

Type Description
RuntimeError

If the model has not been fitted yet.

Source code in src/gtsom/gtsom.py
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
def transform(self, X):
    """
    Map data points to output coordinates via BMU lookup.

    Parameters
    ----------
    X : array-like, shape (N, d)

    Returns
    -------
    coords : np.ndarray, shape (N, embed.dim)

    Raises
    ------
    RuntimeError
        If the model has not been fitted yet.
    """
    if self.W is None:
        raise RuntimeError(
            "Architecture not initialized. "
            "Call from_grid() or from_data() before transform()."
        )
    if self.age == 0:
        raise RuntimeError(
            "transform() called before fit(). "
            "Call fit() first to train the model."
        )
    X = np.asarray(X)
    self.recaller.recall(X=X, W=self.W)
    return self.embed.coords[self.recaller.BMU[:, 0]]

fit_transform

fit_transform(X, n_epochs, **fit_kwargs)

Fit the GTSOM and return output coordinates.

Equivalent to calling :meth:fit followed by :meth:transform. n_epochs must be supplied explicitly; it is passed through to :meth:fit along with any additional keyword arguments. Example::

coords = som.fit_transform(X, n_epochs=100, labels=y, verbose=False)

Parameters:

Name Type Description Default
X (array - like, shape(N, d))
required
n_epochs int

Number of training epochs. Passed to :meth:fit.

required
**fit_kwargs

Additional keyword arguments forwarded to :meth:fit (e.g. labels, verbose, plot_every).

{}

Returns:

Name Type Description
coords (ndarray, shape(N, dim))
Source code in src/gtsom/gtsom.py
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
def fit_transform(self, X, n_epochs, **fit_kwargs):
    """
    Fit the GTSOM and return output coordinates.

    Equivalent to calling :meth:`fit` followed by :meth:`transform`.
    ``n_epochs`` must be supplied explicitly; it is passed through to
    :meth:`fit` along with any additional keyword arguments. Example::

        coords = som.fit_transform(X, n_epochs=100, labels=y, verbose=False)

    Parameters
    ----------
    X : array-like, shape (N, d)
    n_epochs : int
        Number of training epochs. Passed to :meth:`fit`.
    **fit_kwargs
        Additional keyword arguments forwarded to :meth:`fit`
        (e.g. ``labels``, ``verbose``, ``plot_every``).

    Returns
    -------
    coords : np.ndarray, shape (N, embed.dim)
    """
    self.fit(X, n_epochs=n_epochs, **fit_kwargs)
    return self.transform(X)

plot

plot(
    color_by="auto",
    cmap="viridis",
    rf_size_log_threshold=10,
    legend_pos="right",
    title="GTSOM",
    subtitle=None,
    xlab="SOM$_1$",
    ylab="SOM$_2$",
)

Plot the SOM in output (lattice) space using plotnine.

Delegates to :func:~gtsom.vis_tools.vis_embedding_discrete when labels are available, and to :func:~gtsom.vis_tools.vis_embedding_continuous otherwise (coloring by MQE). Neurons are drawn at their embed.coords positions, connected by edges from embed.adjacency. Point size is mapped to receptive field size (RFSize), with the size transform (linear or log10) chosen automatically based on the distribution of RFSize values. If DR metrics have been computed for the current snapshot, they are formatted and shown as a plot caption.

Returns a plotnine.ggplot object — nothing is displayed automatically. Call .save(path) to write to disk, or evaluate the object in a notebook to display it inline.

Parameters:

Name Type Description Default
color_by (auto, mqe, rfsize, labels)

Quantity used to color neurons.

'auto' Use 'labels' if recaller.WL is available, otherwise fall back to 'mqe'. 'mqe' Per-prototype mean quantization error. Continuous scale. 'rfsize' Receptive field size. Continuous scale. 'labels' Winning label per prototype. Discrete scale. Raises ValueError if recaller.WL is None.

'auto'
cmap str

Colormap name for continuous quantities ('mqe', 'rfsize'). Any matplotlib-compatible string is accepted (e.g. 'plasma', 'magma'). Ignored for label plots.

'viridis'
rf_size_log_threshold float

Controls whether RFSize is mapped to point size on a linear or log10 scale. If max(RFSize) / median(RFSize) exceeds this threshold, point_size_wts_trans='log10' is passed to the vis_tools function; otherwise 'identity' is used. Set to inf to always use linear scaling.

10
legend_pos str

Legend / colorbar position. One of 'right', 'bottom', or 'none'.

'right'
title str or None

Main title line.

'GTSOM'
subtitle str or None

Subtitle line. If None, auto-generates 'Epoch {self.age}'.

None
xlab str

Label for the horizontal axis.

'SOM$_1$'
ylab str

Label for the vertical axis.

'SOM$_2$'

Returns:

Type Description
ggplot

Raises:

Type Description
RuntimeError

If :meth:from_grid or :meth:from_data has not been called.

NotImplementedError

If embed.dim != 2.

ValueError

If color_by='labels' but no labels have been provided.

Source code in src/gtsom/gtsom.py
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
def plot(
    self,
    color_by='auto',
    cmap='viridis',
    rf_size_log_threshold=10,
    legend_pos='right',
    title='GTSOM',
    subtitle=None,
    xlab=r'SOM$_1$',
    ylab=r'SOM$_2$',
):
    """
    Plot the SOM in output (lattice) space using plotnine.

    Delegates to :func:`~gtsom.vis_tools.vis_embedding_discrete` when
    labels are available, and to
    :func:`~gtsom.vis_tools.vis_embedding_continuous` otherwise (coloring
    by MQE). Neurons are drawn at their ``embed.coords`` positions,
    connected by edges from ``embed.adjacency``. Point size is mapped to
    receptive field size (RFSize), with the size transform (linear or
    log10) chosen automatically based on the distribution of RFSize values.
    If DR metrics have been computed for the current snapshot, they are
    formatted and shown as a plot caption.

    Returns a ``plotnine.ggplot`` object — nothing is displayed
    automatically. Call ``.save(path)`` to write to disk, or evaluate
    the object in a notebook to display it inline.

    Parameters
    ----------
    color_by : {'auto', 'mqe', 'rfsize', 'labels'}, default 'auto'
        Quantity used to color neurons.

        ``'auto'``
            Use ``'labels'`` if ``recaller.WL`` is available,
            otherwise fall back to ``'mqe'``.
        ``'mqe'``
            Per-prototype mean quantization error. Continuous scale.
        ``'rfsize'``
            Receptive field size. Continuous scale.
        ``'labels'``
            Winning label per prototype. Discrete scale. Raises
            ``ValueError`` if ``recaller.WL`` is None.
    cmap : str, default 'viridis'
        Colormap name for continuous quantities ('mqe', 'rfsize').
        Any matplotlib-compatible string is accepted (e.g. 'plasma',
        'magma'). Ignored for label plots.
    rf_size_log_threshold : float, default 10
        Controls whether RFSize is mapped to point size on a linear
        or log10 scale. If ``max(RFSize) / median(RFSize)`` exceeds
        this threshold, ``point_size_wts_trans='log10'`` is passed to
        the vis_tools function; otherwise ``'identity'`` is used. Set
        to ``inf`` to always use linear scaling.
    legend_pos : str, default 'right'
        Legend / colorbar position. One of ``'right'``, ``'bottom'``,
        or ``'none'``.
    title : str or None, default 'GTSOM'
        Main title line.
    subtitle : str or None, default None
        Subtitle line. If None, auto-generates ``'Epoch {self.age}'``.
    xlab : str, default 'SOM$_1$'
        Label for the horizontal axis.
    ylab : str, default 'SOM$_2$'
        Label for the vertical axis.

    Returns
    -------
    plotnine.ggplot

    Raises
    ------
    RuntimeError
        If :meth:`from_grid` or :meth:`from_data` has not been called.
    NotImplementedError
        If ``embed.dim != 2``.
    ValueError
        If ``color_by='labels'`` but no labels have been provided.
    """
    if self.W is None:
        raise RuntimeError(
            "Architecture not initialized. "
            "Call from_grid() or from_data() before plot()."
        )

    from .vis_tools import vis_embedding_discrete, vis_embedding_continuous

    if self.embed.dim != 2:
        raise NotImplementedError(
            f"plot() only supports 2-D embeddings; "
            f"embed.dim={self.embed.dim}."
        )

    # Resolve 'auto' color_by
    if color_by == 'auto':
        color_by = 'labels' if self.recaller.WL is not None else 'mqe'

    if color_by not in ('mqe', 'rfsize', 'labels'):
        raise ValueError(
            f"color_by must be 'auto', 'mqe', 'rfsize', or 'labels', "
            f"got {color_by!r}."
        )
    if color_by == 'labels' and self.recaller.WL is None:
        raise ValueError(
            "color_by='labels' requires labels to have been provided "
            "at construction or during fit(). recaller.WL is currently None."
        )

    # ------------------------------------------------------------------
    # RFSize → point_size_wts and transform
    # ------------------------------------------------------------------
    rf       = self.recaller.RFSize.astype(float)
    use_log  = (rf.max() / (np.median(rf) + 1e-8)) > rf_size_log_threshold
    rf_trans = 'log10' if use_log else 'identity'
    rf_norm  = (rf - rf.min()) / (rf.max() - rf.min() + 1e-8)

    # ------------------------------------------------------------------
    # Point size: scale down with M so points don't overlap at large M
    # ------------------------------------------------------------------
    point_size = max(2.0, 20.0 / np.sqrt(self.M))

    # ------------------------------------------------------------------
    # Subtitle and caption
    # ------------------------------------------------------------------
    sub     = subtitle if subtitle is not None else f'Epoch {self.age}'
    caption = None
    snap    = self.learn_history_[-1] if self.learn_history_ else None
    if snap is not None and snap.get('dr_metrics') is not None:
        dm = snap['dr_metrics']
        lines = []
        qnn_parts = []
        for name in ('Q_local', 'Q_global', 'Q_AUC', 'LCMC_AUC', 'Trust_AUC'):
            val = getattr(dm, name)
            if val is not None:
                qnn_parts.append(f'{name}={val:.3f}')
        if qnn_parts:
            lines.append('  '.join(qnn_parts))
        wafl = getattr(dm, 'CONN_WAFL', None)
        se   = getattr(dm, 'CONN_WAFL_SE', None)
        if wafl is not None:
            wafl_str = f'CONN_WAFL={wafl:.3f}'
            if se is not None:
                wafl_str += f' \u00b1 {se:.3f}'
            lines.append(wafl_str)
        if lines:
            caption = '\n'.join(lines)

    # ------------------------------------------------------------------
    # Shared kwargs for both vis functions
    # ------------------------------------------------------------------
    shared = dict(
        x                    = self.embed.coords[:, 0],
        y                    = self.embed.coords[:, 1],
        point_size           = point_size,
        point_size_wts       = rf_norm,
        point_size_wts_trans = rf_trans,
        graph                = self.embed.adjacency,
        edge_size            = 0.3,
        edge_color           = '#BBBBBB',
        xlab                 = xlab,
        ylab                 = ylab,
        title                = title,
        subtitle             = sub,
        caption              = caption,
        legend_pos           = legend_pos,
    )

    # ------------------------------------------------------------------
    # Dispatch to discrete or continuous
    # ------------------------------------------------------------------
    if color_by == 'labels':
        return vis_embedding_discrete(
            z            = self.recaller.WL,
            ctab         = self.ctab,
            legend_title = 'Label',
            **shared,
        )
    else:
        z = (
            self.learn_history_[-1]['W_mqe']
            if color_by == 'mqe'
            else rf
        )
        legend_title = 'MQE' if color_by == 'mqe' else 'RF Size'
        return vis_embedding_continuous(
            z            = z,
            cmap         = cmap,
            legend_title = legend_title,
            **shared,
        )

get_snapshot_fig

get_snapshot_fig(
    index,
    cmap="viridis",
    rf_size_log_threshold=10,
    legend_pos="right",
    title="GTSOM",
    subtitle=None,
    xlab="SOM$_1$",
    ylab="SOM$_2$",
)

Reconstruct a live, modifiable plotnine figure from a historical snapshot stored in self.learn_history_.

Unlike :meth:plot, which generates a figure from the current live GTSOM state, this method rebuilds a figure from the coordinates, adjacency, and color data that were recorded at a specific training epoch. The returned object is a fully live plotnine.ggplot that supports the + operator for theme overrides, relabeling, etc.

Parameters:

Name Type Description Default
index int

Index into learn_history_. 0 is the initialization snapshot (age 0). Negative indices work as usual (-1 gives the final snapshot).

required
cmap str

Colormap for continuous quantities (color_by='mqe' or 'rfsize'). Ignored for label plots.

'viridis'
rf_size_log_threshold float

Controls the point-size transform for receptive field sizes. See :meth:plot for full details.

10
legend_pos str

Legend position: 'right', 'bottom', or 'none'.

'right'
title str or None

Main title line.

'GTSOM'
subtitle str or None

Subtitle. If None, auto-generates 'Epoch {age}' from the snapshot's recorded age.

None
xlab str

Horizontal axis label.

'SOM$_1$'
ylab str

Vertical axis label.

'SOM$_2$'

Returns:

Type Description
ggplot

A live, modifiable figure. Supports + theme(...), + labs(...), etc.

Raises:

Type Description
IndexError

If index is out of range for learn_history_.

RuntimeError

If :meth:from_grid or :meth:from_data has not been called.

NotImplementedError

If the snapshot embedding is not 2-D.

Source code in src/gtsom/gtsom.py
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
def get_snapshot_fig(
    self,
    index,
    cmap='viridis',
    rf_size_log_threshold=10,
    legend_pos='right',
    title='GTSOM',
    subtitle=None,
    xlab=r'SOM$_1$',
    ylab=r'SOM$_2$',
):
    """
    Reconstruct a live, modifiable plotnine figure from a historical
    snapshot stored in ``self.learn_history_``.

    Unlike :meth:`plot`, which generates a figure from the current live
    GTSOM state, this method rebuilds a figure from the coordinates,
    adjacency, and color data that were recorded at a specific training
    epoch. The returned object is a fully live ``plotnine.ggplot`` that
    supports the ``+`` operator for theme overrides, relabeling, etc.

    Parameters
    ----------
    index : int
        Index into ``learn_history_``. ``0`` is the initialization
        snapshot (age 0). Negative indices work as usual (``-1`` gives
        the final snapshot).
    cmap : str, default 'viridis'
        Colormap for continuous quantities (``color_by='mqe'`` or
        ``'rfsize'``). Ignored for label plots.
    rf_size_log_threshold : float, default 10
        Controls the point-size transform for receptive field sizes.
        See :meth:`plot` for full details.
    legend_pos : str, default 'right'
        Legend position: ``'right'``, ``'bottom'``, or ``'none'``.
    title : str or None, default 'GTSOM'
        Main title line.
    subtitle : str or None, default None
        Subtitle. If None, auto-generates ``'Epoch {age}'`` from the
        snapshot's recorded age.
    xlab : str, default 'SOM$_1$'
        Horizontal axis label.
    ylab : str, default 'SOM$_2$'
        Vertical axis label.

    Returns
    -------
    plotnine.ggplot
        A live, modifiable figure. Supports ``+ theme(...)``,
        ``+ labs(...)``, etc.

    Raises
    ------
    IndexError
        If ``index`` is out of range for ``learn_history_``.
    RuntimeError
        If :meth:`from_grid` or :meth:`from_data` has not been called.
    NotImplementedError
        If the snapshot embedding is not 2-D.
    """
    if self.W is None:
        raise RuntimeError(
            "Architecture not initialized. "
            "Call from_grid() or from_data() before get_snapshot_fig()."
        )

    from .vis_tools import vis_embedding_discrete, vis_embedding_continuous

    snap = self.learn_history_[index]   # raises IndexError if out of range

    coords    = snap['coords']          # (M, 2)
    adjacency = snap['adjacency']       # sparse CSR
    RFSize    = snap['RFSize']          # (M,)
    WL        = snap['WL']             # (M,) or None
    color_by  = snap['color_by']        # 'labels' or 'mqe'
    W_mqe     = snap['W_mqe']           # (M,)
    age       = snap['age']
    dm        = snap.get('dr_metrics')  # DRMetricsResult or None

    if coords.shape[1] != 2:
        raise NotImplementedError(
            f"get_snapshot_fig() only supports 2-D embeddings; "
            f"snapshot coords have shape {coords.shape}."
        )

    # --- Point size weights (same logic as plot()) ---
    rf      = RFSize.astype(float)
    use_log = (rf.max() / (np.median(rf) + 1e-8)) > rf_size_log_threshold
    rf_trans = 'log10' if use_log else 'identity'
    rf_norm  = (rf - rf.min()) / (rf.max() - rf.min() + 1e-8)

    # --- Point size scaled by M (same formula as plot()) ---
    M = coords.shape[0]
    point_size = max(2.0, 20.0 / np.sqrt(M))

    # --- Subtitle and caption ---
    sub = subtitle if subtitle is not None else f'Epoch {age}'
    caption = None
    if dm is not None:
        lines = []
        qnn_parts = []
        for name in ('Q_local', 'Q_global', 'Q_AUC', 'LCMC_AUC', 'Trust_AUC'):
            val = getattr(dm, name, None)
            if val is not None:
                qnn_parts.append(f'{name}={val:.3f}')
        if qnn_parts:
            lines.append('  '.join(qnn_parts))
        wafl = getattr(dm, 'CONN_WAFL', None)
        se   = getattr(dm, 'CONN_WAFL_SE', None)
        if wafl is not None:
            wafl_str = f'CONN_WAFL={wafl:.3f}'
            if se is not None:
                wafl_str += f' \u00b1 {se:.3f}'
            lines.append(wafl_str)
        if lines:
            caption = '\n'.join(lines)

    # --- Shared vis_tools kwargs ---
    shared = dict(
        x                    = coords[:, 0],
        y                    = coords[:, 1],
        point_size           = point_size,
        point_size_wts       = rf_norm,
        point_size_wts_trans = rf_trans,
        graph                = adjacency,
        edge_size            = 0.3,
        edge_color           = '#BBBBBB',
        xlab                 = xlab,
        ylab                 = ylab,
        title                = title,
        subtitle             = sub,
        caption              = caption,
        legend_pos           = legend_pos,
    )

    # --- Dispatch ---
    if color_by == 'labels':
        return vis_embedding_discrete(
            z            = WL,
            ctab         = self.ctab,
            legend_title = 'Label',
            **shared,
        )
    else:
        z            = W_mqe if color_by == 'mqe' else rf
        legend_title = 'MQE' if color_by == 'mqe' else 'RF Size'
        return vis_embedding_continuous(
            z            = z,
            cmap         = cmap,
            legend_title = legend_title,
            **shared,
        )

update_embedding

update_embedding(coords)

Replace the output-space embedding coordinates and refresh the neighborhood weight matrix atomically.

Calls self.embed.update_coords(coords) to validate the new positions, rebuild adjacency, and recompute geodesic distances. Then immediately recomputes self.nbr_W from the updated topology using the current annealing bandwidth self.rho_schedule(self.age), so that the next :meth:fit call starts with a consistent neighborhood structure.

Parameters:

Name Type Description Default
coords (array - like, shape(M, dim))

New low-dimensional prototype positions.

required

Returns:

Name Type Description
self GTSOM

Raises:

Type Description
RuntimeError

If :meth:from_grid or :meth:from_data has not been called.

ValueError

Propagated from :meth:Embedding.update_coords if the shape of coords does not match the current embedding shape.

Source code in src/gtsom/gtsom.py
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
def update_embedding(self, coords):
    """
    Replace the output-space embedding coordinates and refresh the
    neighborhood weight matrix atomically.

    Calls ``self.embed.update_coords(coords)`` to validate the new
    positions, rebuild adjacency, and recompute geodesic distances.
    Then immediately recomputes ``self.nbr_W`` from the updated
    topology using the current annealing bandwidth
    ``self.rho_schedule(self.age)``, so that the next :meth:`fit`
    call starts with a consistent neighborhood structure.

    Parameters
    ----------
    coords : array-like, shape (M, dim)
        New low-dimensional prototype positions.

    Returns
    -------
    self : GTSOM

    Raises
    ------
    RuntimeError
        If :meth:`from_grid` or :meth:`from_data` has not been called.
    ValueError
        Propagated from :meth:`Embedding.update_coords` if the shape
        of ``coords`` does not match the current embedding shape.
    """
    if self.W is None:
        raise RuntimeError(
            "Architecture not initialized. "
            "Call from_grid() or from_data() before update_embedding()."
        )
    self.embed.update_coords(coords)
    self._compute_neighborhood(
        self.rho_schedule(self.age),
        self.alpha_schedule(self.age),
    )
    return self

save

save(path)

Save this GTSOM to an HDF5 file.

Serializes all learning parameters, architecture state (W, Embedding, VQRecaller), training history (learn_history_), and the color table (ctab). The file can be reloaded with :meth:load to resume training, run :meth:transform, or reproduce any historical plot via :meth:get_snapshot_fig — no retraining required.

Parameters:

Name Type Description Default
path str

Destination file path. Created or overwritten.

required
See Also

GTSOM.load : Reconstruct a GTSOM from a saved file.

Examples:

>>> som.fit(X, n_epochs=100)
>>> som.save("som.h5")
>>> som2 = GTSOM.load("som.h5")
>>> som2.plot()
>>> som2.fit(X, n_epochs=50)   # resume training
Source code in src/gtsom/gtsom.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
def save(self, path):
    """
    Save this GTSOM to an HDF5 file.

    Serializes all learning parameters, architecture state (W, Embedding,
    VQRecaller), training history (``learn_history_``), and the color
    table (``ctab``).  The file can be reloaded with :meth:`load` to
    resume training, run :meth:`transform`, or reproduce any historical
    plot via :meth:`get_snapshot_fig` — no retraining required.

    Parameters
    ----------
    path : str
        Destination file path.  Created or overwritten.

    See Also
    --------
    GTSOM.load : Reconstruct a GTSOM from a saved file.

    Examples
    --------
    >>> som.fit(X, n_epochs=100)
    >>> som.save("som.h5")
    >>> som2 = GTSOM.load("som.h5")
    >>> som2.plot()
    >>> som2.fit(X, n_epochs=50)   # resume training
    """
    from .io import GTSOMio
    GTSOMio(self).save(path)

load classmethod

load(path)

Load a GTSOM from an HDF5 file created by :meth:save.

Parameters:

Name Type Description Default
path str

Path to an HDF5 file previously created by :meth:save.

required

Returns:

Type Description
GTSOM

Fully reconstructed instance, ready for :meth:transform, :meth:plot, :meth:get_snapshot_fig, or :meth:fit.

See Also

GTSOM.save : Save a GTSOM to an HDF5 file.

Examples:

>>> som = GTSOM.load("som.h5")
>>> som.age
100
>>> som.plot()
>>> som.fit(X, n_epochs=50)
Source code in src/gtsom/gtsom.py
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
@classmethod
def load(cls, path):
    """
    Load a GTSOM from an HDF5 file created by :meth:`save`.

    Parameters
    ----------
    path : str
        Path to an HDF5 file previously created by :meth:`save`.

    Returns
    -------
    GTSOM
        Fully reconstructed instance, ready for :meth:`transform`,
        :meth:`plot`, :meth:`get_snapshot_fig`, or :meth:`fit`.

    See Also
    --------
    GTSOM.save : Save a GTSOM to an HDF5 file.

    Examples
    --------
    >>> som = GTSOM.load("som.h5")
    >>> som.age
    100
    >>> som.plot()
    >>> som.fit(X, n_epochs=50)
    """
    from .io import GTSOMio
    return GTSOMio.load(path)

Utilities

gtsom.utils.ExponentialAnneal

ExponentialAnneal(initial, final, tau)

Exponential annealing schedule for a scalar parameter.

Computes the annealed value at a given age (epoch count) as::

value(age) = initial * (final / initial) ** (age / tau)

The result is clipped at final once the schedule reaches it, ensuring the final value is respected exactly regardless of how many epochs have elapsed.

Supports both decreasing schedules (final < initial, e.g. annealing a neighborhood bandwidth from broad to narrow) and increasing schedules (final > initial, e.g. shifting neighborhood influence from lattice-dominated toward CONN-dominated over training). The direction is inferred automatically from the relationship between initial and final; the formula and clipping behavior adapt accordingly.

initial and final may be zero. If either is zero it is replaced internally by a small positive floor (_ANNEAL_EPS = 1e-8) before the formula is applied, keeping the exponential well-defined. The reported self.initial / self.final always reflect the values as supplied by the caller; only the internal computation is clipped. The resulting schedule is a true exponential in value space — not in a translated space — so the curve shape is never distorted by the zero-handling.

Intended for use with any parameter that requires monotonic change during training — neighborhood bandwidth (rho), topology-blending weight (nbr_topo_alpha), learning rate, etc.

Parameters:

Name Type Description Default
initial float

Starting value of the parameter (at age=0). Must be >= 0.

required
final float

Target value of the parameter. Must be >= 0. If final < initial, the schedule decays; if final > initial, the schedule increases; if final == initial, the schedule is flat and returns initial at every age.

required
tau float

Time constant in epochs. Controls how quickly the parameter moves from initial toward final. Smaller values change faster. Computed internally from halflife_epochs when that convenience constructor is used instead.

required

Examples:

Decreasing schedule (decay):

>>> schedule = ExponentialAnneal(initial=5.0, final=0.3, tau=20)
>>> schedule(0)
5.0
>>> schedule(10)   # half a tau — midway through the decay
1.2247...
>>> schedule(20)   # one full tau — reaches final exactly
0.3
>>> schedule(1000)  # beyond tau — clipped at final
0.3

Decreasing to zero:

>>> schedule = ExponentialAnneal(initial=1.0, final=0.0, tau=20)
>>> schedule(0)
1.0
>>> schedule(1000)  # clipped at final
0.0

Increasing schedule (ramp):

>>> schedule = ExponentialAnneal(initial=0.0, final=1.0, tau=20)
>>> schedule(0)
0.0
>>> schedule(1000)  # clipped at final
1.0

Construction from a half-life epoch count:

>>> schedule = ExponentialAnneal.from_halflife(initial=5.0, final=0.3,
...                                             halflife_epochs=50)
>>> round(schedule(50), 6)  # geometric midpoint of 5.0 and 0.3
1.2247...
>>> round(schedule(100), 6)  # clipped at final
0.3
Source code in src/gtsom/utils.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
def __init__(self, initial, final, tau):
    if initial < 0:
        raise ValueError(f"initial must be >= 0, got {initial}")
    if final < 0:
        raise ValueError(f"final must be >= 0, got {final}")
    if tau <= 0:
        raise ValueError(f"tau must be positive, got {tau}")

    self.initial = float(initial)
    self.final   = float(final)
    self.tau     = float(tau)

    # Internal clipped values: replace zero with _ANNEAL_EPS so that
    # the ratio (sf/si) and log(sf/si) are always well-defined.
    # Unlike the old additive-shift approach, this does not distort
    # the curve shape for non-zero parameters.
    self._si = max(self.initial, _ANNEAL_EPS)
    self._sf = max(self.final,   _ANNEAL_EPS)

    # Detect flat schedule (initial == final)
    self._flat = self.initial == self.final
    if self._flat:
        self._increasing = False
    else:
        self._increasing = self.final > self.initial

from_halflife classmethod

from_halflife(initial, final, halflife_epochs)

Construct a schedule where halflife_epochs is the geometric half-life.

halflife_epochs is the epoch at which the parameter reaches the geometric mean of initial and final::

value(halflife_epochs) = sqrt(initial * final)

This is a half-life in log space (the schedule is linear in log space, and the geometric mean is the arithmetic midpoint of log(initial) and log(final)), not in linear space.

.. note:: Geometric vs arithmetic midpoint

The geometric midpoint ``sqrt(initial * final)`` is always
closer to ``final`` than the arithmetic midpoint
``(initial + final) / 2`` when ``initial != final``. For
example, with ``initial=10, final=0.1``:

- Arithmetic midpoint: 5.05  (barely moved from initial)
- Geometric midpoint:  1.0   (already close to final)

This means the schedule will feel "fast then slow" in linear
space — the parameter drops quickly early on and then settles
gradually. If you expect to be "halfway there" in the ordinary
(arithmetic) sense at ``halflife_epochs``, you will find the
parameter has already moved further than that.

.. note:: Relationship to tau and total training epochs

``tau = 2 * halflife_epochs``, and the schedule is clipped at
``final`` at age ``2 * halflife_epochs``. This means:

- Setting ``halflife_epochs ≈ n_epochs / 4`` places the
  geometric midpoint at the first quarter of training, giving
  a steep initial drop followed by a long flat tail — the
  classic exponential shape.
- Setting ``halflife_epochs ≈ n_epochs / 2`` places the
  geometric midpoint at the halfway point, so the schedule is
  still actively decaying at the end of training and the curve
  looks nearly linear over the training window.

As a rule of thumb, set ``halflife_epochs`` to roughly a
quarter of your total training epochs to get a visually
exponential decay with a clear knee and flat tail.

Parameters:

Name Type Description Default
initial float

Starting value at age=0.

required
final float

Floor value; clipped at this value from age 2 * halflife_epochs onward.

required
halflife_epochs float

The epoch at which the parameter reaches the geometric mean sqrt(initial * final). Must be positive.

required

Returns:

Type Description
ExponentialAnneal

Examples:

>>> s = ExponentialAnneal.from_halflife(initial=3.0, final=0.3,
...                                      halflife_epochs=50)
>>> round(s(0), 4)
3.0
>>> round(s(50), 4)   # geometric midpoint sqrt(3.0 * 0.3) ≈ 0.9487
0.9487
>>> round(s(100), 4)  # clipped at final
0.3

With halflife_epochs = n_epochs / 4 for a classic exponential shape:

>>> s = ExponentialAnneal.from_halflife(initial=10.0, final=0.1,
...                                      halflife_epochs=25)
>>> round(s(25), 4)   # geometric midpoint sqrt(10 * 0.1) = 1.0
1.0
>>> round(s(50), 4)   # clipped at final well before end of training
0.1
Source code in src/gtsom/utils.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
@classmethod
def from_halflife(cls, initial, final, halflife_epochs):
    """
    Construct a schedule where ``halflife_epochs`` is the geometric half-life.

    ``halflife_epochs`` is the epoch at which the parameter reaches the
    **geometric mean** of ``initial`` and ``final``::

        value(halflife_epochs) = sqrt(initial * final)

    This is a half-life in **log space** (the schedule is linear in
    log space, and the geometric mean is the arithmetic midpoint of
    ``log(initial)`` and ``log(final)``), not in linear space.

    .. note:: **Geometric vs arithmetic midpoint**

        The geometric midpoint ``sqrt(initial * final)`` is always
        closer to ``final`` than the arithmetic midpoint
        ``(initial + final) / 2`` when ``initial != final``. For
        example, with ``initial=10, final=0.1``:

        - Arithmetic midpoint: 5.05  (barely moved from initial)
        - Geometric midpoint:  1.0   (already close to final)

        This means the schedule will feel "fast then slow" in linear
        space — the parameter drops quickly early on and then settles
        gradually. If you expect to be "halfway there" in the ordinary
        (arithmetic) sense at ``halflife_epochs``, you will find the
        parameter has already moved further than that.

    .. note:: **Relationship to tau and total training epochs**

        ``tau = 2 * halflife_epochs``, and the schedule is clipped at
        ``final`` at age ``2 * halflife_epochs``. This means:

        - Setting ``halflife_epochs ≈ n_epochs / 4`` places the
          geometric midpoint at the first quarter of training, giving
          a steep initial drop followed by a long flat tail — the
          classic exponential shape.
        - Setting ``halflife_epochs ≈ n_epochs / 2`` places the
          geometric midpoint at the halfway point, so the schedule is
          still actively decaying at the end of training and the curve
          looks nearly linear over the training window.

        As a rule of thumb, set ``halflife_epochs`` to roughly a
        quarter of your total training epochs to get a visually
        exponential decay with a clear knee and flat tail.

    Parameters
    ----------
    initial : float
        Starting value at age=0.
    final : float
        Floor value; clipped at this value from age
        ``2 * halflife_epochs`` onward.
    halflife_epochs : float
        The epoch at which the parameter reaches the geometric mean
        ``sqrt(initial * final)``. Must be positive.

    Returns
    -------
    ExponentialAnneal

    Examples
    --------
    >>> s = ExponentialAnneal.from_halflife(initial=3.0, final=0.3,
    ...                                      halflife_epochs=50)
    >>> round(s(0), 4)
    3.0
    >>> round(s(50), 4)   # geometric midpoint sqrt(3.0 * 0.3) ≈ 0.9487
    0.9487
    >>> round(s(100), 4)  # clipped at final
    0.3

    With halflife_epochs = n_epochs / 4 for a classic exponential shape:

    >>> s = ExponentialAnneal.from_halflife(initial=10.0, final=0.1,
    ...                                      halflife_epochs=25)
    >>> round(s(25), 4)   # geometric midpoint sqrt(10 * 0.1) = 1.0
    1.0
    >>> round(s(50), 4)   # clipped at final well before end of training
    0.1
    """
    if halflife_epochs <= 0:
        raise ValueError(
            f"halflife_epochs must be positive, got {halflife_epochs}"
        )
    # tau such that age=halflife_epochs gives the geometric midpoint:
    # initial * (final/initial)^(halflife_epochs/tau) = sqrt(initial*final)
    # => (final/initial)^(halflife_epochs/tau) = sqrt(final/initial)
    # => halflife_epochs/tau = 0.5
    # => tau = 2 * halflife_epochs
    tau = 2.0 * halflife_epochs
    return cls(initial=initial, final=final, tau=tau)

__call__

__call__(age)

Return the annealed parameter value at the given age.

Parameters:

Name Type Description Default
age int or float

Current epoch count (0-based).

required

Returns:

Type Description
float
Source code in src/gtsom/utils.py
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
def __call__(self, age):
    """
    Return the annealed parameter value at the given age.

    Parameters
    ----------
    age : int or float
        Current epoch count (0-based).

    Returns
    -------
    float
    """
    if self._flat:
        return self.final
    raw = self._si * (self._sf / self._si) ** (age / self.tau)
    if self._increasing:
        return float(min(raw, self.final))
    else:
        return float(max(raw, self.final))

values

values(n_epochs)

Return the annealed values for epochs 0 through n_epochs - 1.

Useful for inspecting or plotting the planned schedule before training begins.

Parameters:

Name Type Description Default
n_epochs int
required

Returns:

Type Description
(ndarray, shape(n_epochs))
Source code in src/gtsom/utils.py
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
def values(self, n_epochs):
    """
    Return the annealed values for epochs 0 through n_epochs - 1.

    Useful for inspecting or plotting the planned schedule before
    training begins.

    Parameters
    ----------
    n_epochs : int

    Returns
    -------
    np.ndarray, shape (n_epochs,)
    """
    if self._flat:
        return np.full(n_epochs, self.final)
    ages = np.arange(n_epochs, dtype=float)
    raw  = self._si * (self._sf / self._si) ** (ages / self.tau)
    if self._increasing:
        return np.minimum(raw, self.final).astype(float)
    else:
        return np.maximum(raw, self.final).astype(float)

to_dict

to_dict()

Return a plain dict representation of this schedule.

Returns:

Type Description
dict with keys: initial (float), final (float), tau (float)
Source code in src/gtsom/utils.py
697
698
699
700
701
702
703
704
705
706
707
708
709
def to_dict(self):
    """
    Return a plain dict representation of this schedule.

    Returns
    -------
    dict with keys: initial (float), final (float), tau (float)
    """
    return {
        "initial": self.initial,
        "final":   self.final,
        "tau":     self.tau,
    }

from_dict classmethod

from_dict(d)

Reconstruct an ExponentialAnneal from a dict produced by :meth:to_dict.

Parameters:

Name Type Description Default
d dict

As returned by :meth:to_dict.

required

Returns:

Type Description
ExponentialAnneal
Source code in src/gtsom/utils.py
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
@classmethod
def from_dict(cls, d):
    """
    Reconstruct an ExponentialAnneal from a dict produced by
    :meth:`to_dict`.

    Parameters
    ----------
    d : dict
        As returned by :meth:`to_dict`.

    Returns
    -------
    ExponentialAnneal
    """
    return cls(initial=d["initial"], final=d["final"], tau=d["tau"])

gtsom.utils.DataValidator

DataValidator(X, labels=None)

Validates a data matrix X (and optionally observation labels) and stores lightweight fingerprints for consistency checking across subsequent calls.

Construction validates X (must be 2-D) and records its fingerprint, along with an optional label fingerprint derived from labels. The :meth:check method warns whenever a later (X, labels) pair does not match what was seen at construction.

Parameters:

Name Type Description Default
X array - like

Data matrix to validate and fingerprint.

required
labels array - like or None

Observation labels. If provided, a label fingerprint is stored as a {str_label: count} dict so that label-universe and per-class-count mismatches can be detected at :meth:check time.

None

Raises:

Type Description
ValueError

If X is not 2-D after conversion to ndarray.

Examples:

>>> import numpy as np
>>> validator = DataValidator(np.ones((100, 5)))
>>> validator.shape
(100, 5)
>>> validator.check(np.ones((100, 5)))              # silent — matches
>>> validator.check(np.ones((200, 5)), context="fit")  # warns: X mismatch

With labels:

>>> y = np.array([0, 0, 1, 1, 2, 2])
>>> validator = DataValidator(np.ones((6, 3)), labels=y)
>>> validator.check(np.ones((6, 3)), labels=y)      # silent — matches
>>> validator.check(np.ones((6, 3)), labels=None, context="fit")  # warns: labels missing
Source code in src/gtsom/utils.py
62
63
64
65
66
67
68
69
70
71
72
73
74
def __init__(self, X, labels=None):
    X = np.asarray(X)
    if X.ndim != 2:
        raise ValueError(f"X must be 2-D, got shape {X.shape}")
    self._fingerprint = (
        X.shape,
        X.dtype,
        float(X.mean()),
        float(X.std()),
        float(X.min()),
        float(X.max()),
    )
    self._label_fingerprint = self._build_label_fingerprint(labels)

shape property

shape

Shape (N, d) of the validated dataset.

dtype property

dtype

dtype of the validated dataset.

has_labels property

has_labels

True if labels were provided at construction.

check

check(X, labels=None, context='')

Warn if X or labels do not match the stored fingerprints.

Four distinct warning cases are handled:

  1. X mismatch — the incoming X has a different shape, dtype, or summary statistics from the dataset seen at construction.
  2. Labels missing at check time — labels were provided at construction but labels=None here; recaller.WL will be stale after this call.
  3. Label universe / count mismatch — both construction and this call provided labels, but the set of unique values or their per-class counts differ; ctab and snapshot WL may be inconsistent.
  4. Labels provided only at check time — labels were not provided at construction; re-initialize the SOM with labels to enable label coloring.

Parameters:

Name Type Description Default
X array - like

Incoming data matrix to check.

required
labels array - like or None

Incoming observation labels to check.

None
context str

Caller name included in warning messages for traceability (e.g. "fit").

''
Source code in src/gtsom/utils.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def check(self, X, labels=None, context=""):
    """
    Warn if X or labels do not match the stored fingerprints.

    Four distinct warning cases are handled:

    1. **X mismatch** — the incoming ``X`` has a different shape, dtype,
       or summary statistics from the dataset seen at construction.
    2. **Labels missing at check time** — labels were provided at
       construction but ``labels=None`` here; ``recaller.WL`` will be
       stale after this call.
    3. **Label universe / count mismatch** — both construction and this
       call provided labels, but the set of unique values or their per-class
       counts differ; ``ctab`` and snapshot ``WL`` may be inconsistent.
    4. **Labels provided only at check time** — labels were not provided at
       construction; re-initialize the SOM with labels to enable label
       coloring.

    Parameters
    ----------
    X : array-like
        Incoming data matrix to check.
    labels : array-like or None, optional
        Incoming observation labels to check.
    context : str, optional
        Caller name included in warning messages for traceability
        (e.g. ``"fit"``).
    """
    prefix = f"{context}: " if context else ""

    # --- Case 1: X fingerprint ---
    X = np.asarray(X)
    current_fp = (
        X.shape,
        X.dtype,
        float(X.mean()),
        float(X.std()),
        float(X.min()),
        float(X.max()),
    )
    if current_fp != self._fingerprint:
        fp = self._fingerprint
        warnings.warn(
            f"{prefix}X does not match the dataset used at initialization. "
            f"Expected shape={fp[0]}, dtype={fp[1]}, "
            f"mean={fp[2]:.4g}, std={fp[3]:.4g}, "
            f"min={fp[4]:.4g}, max={fp[5]:.4g}. "
            f"Got shape={current_fp[0]}, dtype={current_fp[1]}, "
            f"mean={current_fp[2]:.4g}, std={current_fp[3]:.4g}, "
            f"min={current_fp[4]:.4g}, max={current_fp[5]:.4g}.",
            UserWarning,
            stacklevel=3,
        )

    # --- Cases 2 / 3 / 4: label fingerprint ---
    init_had_labels  = self._label_fingerprint is not None
    check_has_labels = labels is not None

    if init_had_labels and not check_has_labels:
        # Case 2
        warnings.warn(
            f"{prefix}Labels were provided at initialization but not passed "
            f"here. recaller.WL will not be updated and will reflect "
            f"prototype–label assignments from the previous epoch.",
            UserWarning,
            stacklevel=3,
        )
    elif init_had_labels and check_has_labels:
        # Case 3: compare fingerprints
        current_lf = self._build_label_fingerprint(labels)
        if current_lf != self._label_fingerprint:
            warnings.warn(
                f"{prefix}Labels passed here differ from those provided at "
                f"initialization (different label universe or per-class "
                f"counts). ctab and snapshot WL values may be inconsistent. "
                f"Expected label counts: {self._label_fingerprint}. "
                f"Got: {current_lf}.",
                UserWarning,
                stacklevel=3,
            )
    elif not init_had_labels and check_has_labels:
        # Case 4
        warnings.warn(
            f"{prefix}Labels were not provided at initialization. "
            f"Re-initialize the SOM via from_grid() or from_data() with "
            f"labels= to enable label coloring and consistent snapshot WL.",
            UserWarning,
            stacklevel=3,
        )

to_dict

to_dict()

Return a plain dict representation of this validator's fingerprints.

The training data X is not stored — only the summary statistics needed to detect mismatches in subsequent :meth:check calls. The dtype is stored as a string and cast back to np.dtype on load.

Returns:

Type Description
dict with keys:

shape list of int dtype str mean float std float min float max float has_labels bool label_keys np.ndarray of object (str labels) or None label_counts np.ndarray of int64 or None

Source code in src/gtsom/utils.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def to_dict(self):
    """
    Return a plain dict representation of this validator's fingerprints.

    The training data ``X`` is not stored — only the summary statistics
    needed to detect mismatches in subsequent :meth:`check` calls.
    The dtype is stored as a string and cast back to ``np.dtype`` on load.

    Returns
    -------
    dict with keys:
        shape   list of int
        dtype   str
        mean    float
        std     float
        min     float
        max     float
        has_labels  bool
        label_keys    np.ndarray of object (str labels) or None
        label_counts  np.ndarray of int64 or None
    """
    fp = self._fingerprint
    d = {
        "shape": list(fp[0]),
        "dtype": str(fp[1]),
        "mean":  float(fp[2]),
        "std":   float(fp[3]),
        "min":   float(fp[4]),
        "max":   float(fp[5]),
        "has_labels": self._label_fingerprint is not None,
    }
    if self._label_fingerprint is not None:
        keys   = list(self._label_fingerprint.keys())
        counts = list(self._label_fingerprint.values())
        d["label_keys"]   = np.array(keys,   dtype=object)
        d["label_counts"] = np.array(counts, dtype=np.int64)
    else:
        d["label_keys"]   = None
        d["label_counts"] = None
    return d

from_dict classmethod

from_dict(d)

Reconstruct a DataValidator from a dict produced by :meth:to_dict.

Bypasses __init__ so that the stored fingerprint is restored exactly without requiring the original data X.

Parameters:

Name Type Description Default
d dict

As returned by :meth:to_dict.

required

Returns:

Type Description
DataValidator
Source code in src/gtsom/utils.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
@classmethod
def from_dict(cls, d):
    """
    Reconstruct a DataValidator from a dict produced by :meth:`to_dict`.

    Bypasses ``__init__`` so that the stored fingerprint is restored
    exactly without requiring the original data ``X``.

    Parameters
    ----------
    d : dict
        As returned by :meth:`to_dict`.

    Returns
    -------
    DataValidator
    """
    obj = cls.__new__(cls)
    obj._fingerprint = (
        tuple(int(x) for x in d["shape"]),
        np.dtype(d["dtype"]),
        float(d["mean"]),
        float(d["std"]),
        float(d["min"]),
        float(d["max"]),
    )
    if d.get("has_labels") and d.get("label_keys") is not None:
        keys   = [str(k) for k in d["label_keys"]]
        counts = [int(c) for c in d["label_counts"]]
        obj._label_fingerprint = dict(zip(keys, counts))
    else:
        obj._label_fingerprint = None
    return obj

Embedding

gtsom.embedding.Embedding

Embedding(
    coords, adj_metric, dist_metric="geodesic", _shape=None
)

Low-dimensional embedding of SOM prototype positions, including graph topology and pairwise distances.

Stores the output-space coordinates of M prototypes, a sparse adjacency matrix defining their topological connections, and a dense pairwise distance matrix derived from that adjacency.

Attributes:

Name Type Description
coords (ndarray, shape(M, dim))

Low-dimensional positions of the prototypes. Mutable — can be updated externally (e.g. by a tSNE/UMAP step), followed by a call to compute_topo() to rebuild adjacency and distances.

dim int

Dimensionality of the embedding space (2 or 3). Inferred from coords.

adjacency (csr_matrix, shape(M, M))

Sparse symmetric adjacency matrix. Entry (i, j) = 1 if prototypes i and j are graph neighbors, 0 otherwise. Populated by compute_topo().

adj_metric str

Algorithm used to construct the adjacency. One of: 'delaunay', 'gabriel', 'grid_rect', 'grid_hex'.

dist np.ndarray, shape (M, M), dtype float32

Dense pairwise distance matrix. Populated by compute_topo().

dist_metric str

Distance type used to populate dist. Currently supported: 'geodesic' (unweighted hop-count shortest path).

M int(property)

Number of prototypes.

Base constructor. Stores coords and metric specs, then calls compute_topo() to build adjacency and dist.

Prefer the classmethods (from_delaunay, from_gabriel, from_grid) over calling this directly.

Parameters:

Name Type Description Default
coords (array - like, shape(M, dim))

Low-dimensional prototype positions. dim must be 2 or 3.

required
adj_metric str

Algorithm to use for adjacency construction.

required
dist_metric str

Distance type for computing dist.

'geodesic'
_shape tuple of int

Grid shape — stored internally by from_grid() so that compute_topo() can reconstruct exact grid adjacency.

None
Source code in src/gtsom/embedding.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def __init__(self, coords, adj_metric, dist_metric="geodesic", _shape=None):
    """
    Base constructor. Stores coords and metric specs, then calls
    compute_topo() to build adjacency and dist.

    Prefer the classmethods (from_delaunay, from_gabriel, from_grid)
    over calling this directly.

    Parameters
    ----------
    coords : array-like, shape (M, dim)
        Low-dimensional prototype positions. dim must be 2 or 3.
    adj_metric : str
        Algorithm to use for adjacency construction.
    dist_metric : str, default 'geodesic'
        Distance type for computing dist.
    _shape : tuple of int, optional
        Grid shape — stored internally by from_grid() so that
        compute_topo() can reconstruct exact grid adjacency.
    """
    self.coords = np.asarray(coords, dtype=float)
    self.adj_metric = adj_metric
    self.dist_metric = dist_metric
    self._shape = _shape  # only set for grid embeddings
    self.adjacency = None
    self.dist = None
    self._validate()
    self.compute_topo()

M property

M

Number of prototypes.

dim property

dim

Dimensionality of the embedding space (2 or 3).

compute_topo

compute_topo()

Recompute adjacency from current coords (using adj_metric), then recompute dist (using dist_metric).

Call this after updating coords externally (e.g. after a tSNE/UMAP coordinate update step). For grid-based embeddings this is called once at construction and rarely thereafter.

Returns:

Name Type Description
self Embedding

Returns self for method chaining.

Source code in src/gtsom/embedding.py
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
def compute_topo(self):
    """
    Recompute adjacency from current coords (using adj_metric), then
    recompute dist (using dist_metric).

    Call this after updating coords externally (e.g. after a tSNE/UMAP
    coordinate update step). For grid-based embeddings this is called
    once at construction and rarely thereafter.

    Returns
    -------
    self : Embedding
        Returns self for method chaining.
    """
    if self.adj_metric in ("delaunay", "grid_hex"):
        # Delaunay correctly recovers hex grid 6-connectivity and
        # handles arbitrary/random coord layouts.
        self.adjacency = _delaunay_adjacency(self.coords)
    elif self.adj_metric == "grid_rect":
        # Delaunay on a regular grid is ambiguous for square cells:
        # it picks one diagonal per square, missing the other half.
        # Use an explicit 8-connected grid adjacency instead.
        if self._shape is None:
            raise RuntimeError(
                "grid_rect adjacency requires _shape to be set. "
                "Use Embedding.from_grid() to construct rect grid embeddings."
            )
        self.adjacency = _rect_grid_adjacency(self._shape)
    elif self.adj_metric == "gabriel":
        self.adjacency = _gabriel_adjacency(self.coords)

    self.dist = self._compute_dist()
    return self

update_coords

update_coords(coords)

Replace the embedding coordinates and atomically rebuild topology.

Sets self.coords to the provided array and immediately calls self.compute_topo() to rebuild self.adjacency and self.dist from the new positions. Callers do not need to trigger compute_topo() manually after changing coords.

Parameters:

Name Type Description Default
coords (array - like, shape(M, dim))

New low-dimensional prototype positions. Must match the current shape (M, dim) exactly — neither the number of prototypes nor the embedding dimensionality may change.

required

Returns:

Name Type Description
self Embedding

Returns self for method chaining.

Raises:

Type Description
ValueError

If the shape of coords does not match the current self.coords shape (M, dim).

Source code in src/gtsom/embedding.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def update_coords(self, coords):
    """
    Replace the embedding coordinates and atomically rebuild topology.

    Sets ``self.coords`` to the provided array and immediately calls
    ``self.compute_topo()`` to rebuild ``self.adjacency`` and
    ``self.dist`` from the new positions. Callers do not need to
    trigger ``compute_topo()`` manually after changing coords.

    Parameters
    ----------
    coords : array-like, shape (M, dim)
        New low-dimensional prototype positions. Must match the current
        shape ``(M, dim)`` exactly — neither the number of prototypes
        nor the embedding dimensionality may change.

    Returns
    -------
    self : Embedding
        Returns self for method chaining.

    Raises
    ------
    ValueError
        If the shape of ``coords`` does not match the current
        ``self.coords`` shape ``(M, dim)``.
    """
    coords = np.asarray(coords, dtype=float)
    expected = self.coords.shape
    if coords.shape != expected:
        raise ValueError(
            f"coords shape mismatch: expected {expected}, got {coords.shape}. "
            f"The number of prototypes (M={expected[0]}) and embedding "
            f"dimensionality (dim={expected[1]}) must not change."
        )
    self.coords = coords
    self.compute_topo()
    return self

from_delaunay classmethod

from_delaunay(coords, dist_metric='geodesic')

Construct an Embedding from the Delaunay triangulation of coords.

Parameters:

Name Type Description Default
coords (array - like, shape(M, dim))

Low-dimensional prototype positions. dim must be 2 or 3.

required
dist_metric str

Distance type for computing dist.

'geodesic'

Returns:

Type Description
Embedding
Source code in src/gtsom/embedding.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
@classmethod
def from_delaunay(cls, coords, dist_metric="geodesic"):
    """
    Construct an Embedding from the Delaunay triangulation of coords.

    Parameters
    ----------
    coords : array-like, shape (M, dim)
        Low-dimensional prototype positions. dim must be 2 or 3.
    dist_metric : str, default 'geodesic'
        Distance type for computing dist.

    Returns
    -------
    Embedding
    """
    return cls(coords, adj_metric="delaunay", dist_metric=dist_metric)

from_gabriel classmethod

from_gabriel(coords, dist_metric='geodesic')

Construct an Embedding from the Gabriel graph of coords.

The Gabriel graph is a subgraph of the Delaunay triangulation: edge (i, j) is retained only if no other point lies within the open ball whose diameter is the segment from coords[i] to coords[j]. This produces a sparser topology than Delaunay, more closely reflecting local proximity structure, while remaining guaranteed to be connected for any finite point set in general position.

Parameters:

Name Type Description Default
coords (array - like, shape(M, dim))

Low-dimensional prototype positions. dim must be 2 or 3.

required
dist_metric str

Distance type for computing dist.

'geodesic'

Returns:

Type Description
Embedding
Source code in src/gtsom/embedding.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
@classmethod
def from_gabriel(cls, coords, dist_metric="geodesic"):
    """
    Construct an Embedding from the Gabriel graph of coords.

    The Gabriel graph is a subgraph of the Delaunay triangulation:
    edge (i, j) is retained only if no other point lies within the
    open ball whose diameter is the segment from coords[i] to coords[j].
    This produces a sparser topology than Delaunay, more closely
    reflecting local proximity structure, while remaining guaranteed
    to be connected for any finite point set in general position.

    Parameters
    ----------
    coords : array-like, shape (M, dim)
        Low-dimensional prototype positions. dim must be 2 or 3.
    dist_metric : str, default 'geodesic'
        Distance type for computing dist.

    Returns
    -------
    Embedding
    """
    return cls(coords, adj_metric="gabriel", dist_metric=dist_metric)

from_grid classmethod

from_grid(shape, kind='hex', dist_metric='geodesic')

Construct an Embedding from a regular grid.

Coordinates are generated analytically from the grid shape and type. For hexagonal grids, adjacency is derived via Delaunay triangulation (which correctly recovers 6-connectivity in 2D and richer inter-layer connectivity in 3D). For rectangular grids, an explicit 8-connected adjacency is constructed directly to avoid the diagonal ambiguity of Delaunay on regular square grids.

Parameters:

Name Type Description Default
shape tuple of int

Grid dimensions. (nrows, ncols) for 2D grids, or (nrows, ncols, ndepth) for 3D grids.

required
kind str

Grid type: 'hex' for hexagonal, 'rect' for rectangular.

'hex'
dist_metric str

Distance type for computing dist.

'geodesic'

Returns:

Type Description
Embedding
Source code in src/gtsom/embedding.py
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
@classmethod
def from_grid(cls, shape, kind="hex", dist_metric="geodesic"):
    """
    Construct an Embedding from a regular grid.

    Coordinates are generated analytically from the grid shape and
    type. For hexagonal grids, adjacency is derived via Delaunay
    triangulation (which correctly recovers 6-connectivity in 2D and
    richer inter-layer connectivity in 3D). For rectangular grids,
    an explicit 8-connected adjacency is constructed directly to
    avoid the diagonal ambiguity of Delaunay on regular square grids.

    Parameters
    ----------
    shape : tuple of int
        Grid dimensions. (nrows, ncols) for 2D grids, or
        (nrows, ncols, ndepth) for 3D grids.
    kind : str, default 'hex'
        Grid type: 'hex' for hexagonal, 'rect' for rectangular.
    dist_metric : str, default 'geodesic'
        Distance type for computing dist.

    Returns
    -------
    Embedding
    """
    if kind == "hex":
        coords = _hex_grid_coords(shape)
        return cls(
            coords, adj_metric="grid_hex",
            dist_metric=dist_metric, _shape=shape,
        )
    elif kind == "rect":
        coords = _rect_grid_coords(shape)
        return cls(
            coords, adj_metric="grid_rect",
            dist_metric=dist_metric, _shape=shape,
        )
    else:
        raise ValueError(f"kind must be 'hex' or 'rect', got '{kind}'")

to_dict

to_dict()

Return a plain dict representation of this Embedding.

All values are Python/numpy primitives (arrays, sparse matrices, scalars, or None) — no HDF5 types. Intended for use with :class:~gtsom.io.GTSOMio, which handles the HDF5 encoding.

Returns:

Type Description
dict with keys:

coords np.ndarray (M, dim) adj_metric str dist_metric str _shape list of int or None adjacency scipy.sparse.csr_matrix or None dist np.ndarray (M, M) or None

Source code in src/gtsom/embedding.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def to_dict(self):
    """
    Return a plain dict representation of this Embedding.

    All values are Python/numpy primitives (arrays, sparse matrices,
    scalars, or None) — no HDF5 types.  Intended for use with
    :class:`~gtsom.io.GTSOMio`, which handles the HDF5 encoding.

    Returns
    -------
    dict with keys:
        coords      np.ndarray  (M, dim)
        adj_metric  str
        dist_metric str
        _shape      list of int or None
        adjacency   scipy.sparse.csr_matrix or None
        dist        np.ndarray (M, M) or None
    """
    return {
        "coords":      self.coords,
        "adj_metric":  self.adj_metric,
        "dist_metric": self.dist_metric,
        "_shape":      list(self._shape) if self._shape is not None else None,
        "adjacency":   self.adjacency,
        "dist":        self.dist,
    }

from_dict classmethod

from_dict(d)

Reconstruct an Embedding from a dict produced by :meth:to_dict.

Bypasses __init__ (and therefore compute_topo()) so that the exact saved adjacency and distance matrix are restored rather than being recomputed from coords.

Parameters:

Name Type Description Default
d dict

As returned by :meth:to_dict.

required

Returns:

Type Description
Embedding
Source code in src/gtsom/embedding.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
@classmethod
def from_dict(cls, d):
    """
    Reconstruct an Embedding from a dict produced by :meth:`to_dict`.

    Bypasses ``__init__`` (and therefore ``compute_topo()``) so that the
    exact saved adjacency and distance matrix are restored rather than
    being recomputed from coords.

    Parameters
    ----------
    d : dict
        As returned by :meth:`to_dict`.

    Returns
    -------
    Embedding
    """
    obj = cls.__new__(cls)
    obj.coords      = d["coords"]
    obj.adj_metric  = d["adj_metric"]
    obj.dist_metric = d["dist_metric"]
    _shape          = d.get("_shape")
    obj._shape      = tuple(_shape) if _shape is not None else None
    obj.adjacency   = d.get("adjacency")
    obj.dist        = d.get("dist")
    return obj

NeighborKernel

gtsom.kernel.NeighborKernel

NeighborKernel(kind='exp', h_min=0.01)

Computes sparse neighborhood activation weights for SOM prototype updates.

At each learning step, the kernel takes the pairwise distance matrix between prototypes (from Embedding.dist) and a per-prototype bandwidth vector rho, and returns a sparse matrix of neighborhood influence weights.

The kernel function is set at construction and applied uniformly via compute(). Per-prototype rho values allow spatially adaptive bandwidths, though in practice a single global rho (broadcast to length M) is typical.

Parameters:

Name Type Description Default
kind str

Kernel function to use. Currently supported: 'exp' (exponential decay). Future options: 'gaussian'.

'exp'
h_min float

Minimum activation threshold. Weights below this value are set to zero and excluded from the sparse output. Controls the sparsity of nbr_w — lower h_min means broader (denser) neighborhoods.

0.01

Attributes:

Name Type Description
kind str

Kernel function identifier.

h_min float

Activation threshold.

Examples:

>>> kernel = NeighborKernel(kind='exp', h_min=0.01)
>>> nbr_w = kernel.compute(embedding.dist, rho=3.0)
>>> nbr_w.shape
(M, M)
Source code in src/gtsom/kernel.py
47
48
49
50
51
52
53
54
55
56
57
58
def __init__(self, kind="exp", h_min=0.01):
    if kind not in self.SUPPORTED_KINDS:
        raise ValueError(
            f"kind '{kind}' not supported. "
            f"Choose from {self.SUPPORTED_KINDS}."
        )
    if not (0.0 < h_min < 1.0):
        raise ValueError(
            f"h_min must be in (0, 1), got {h_min}."
        )
    self.kind = kind
    self.h_min = h_min

compute

compute(dist, rho)

Compute sparse neighborhood activation weights.

For each prototype i, computes the activation weight for every other prototype j using the kernel function applied to dist[i, j] and rho[i]. Weights below h_min are zeroed out, and the result is returned as a sparse CSR matrix.

Row i of the returned matrix contains the nonzero activation weights of prototype i's neighborhood. The nonzero column indices give the active neighbor prototypes, making a separate nbr_idx array unnecessary.

Parameters:

Name Type Description Default
dist (ndarray, shape(M, M))

Pairwise prototype distance matrix (from Embedding.dist).

required
rho float or array-like of shape (M,)

Neighborhood bandwidth. A scalar is broadcast to all M prototypes. An array allows per-prototype bandwidths.

required

Returns:

Name Type Description
nbr_w (csr_matrix, shape(M, M))

Sparse matrix of neighborhood activation weights. nbr_w[i] gives the activation weights for prototype i's active neighbors. Self-activation (diagonal) is included.

Source code in src/gtsom/kernel.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def compute(self, dist, rho):
    """
    Compute sparse neighborhood activation weights.

    For each prototype i, computes the activation weight for every
    other prototype j using the kernel function applied to dist[i, j]
    and rho[i]. Weights below h_min are zeroed out, and the result
    is returned as a sparse CSR matrix.

    Row i of the returned matrix contains the nonzero activation
    weights of prototype i's neighborhood. The nonzero column indices
    give the active neighbor prototypes, making a separate nbr_idx
    array unnecessary.

    Parameters
    ----------
    dist : np.ndarray, shape (M, M)
        Pairwise prototype distance matrix (from Embedding.dist).
    rho : float or array-like of shape (M,)
        Neighborhood bandwidth. A scalar is broadcast to all M
        prototypes. An array allows per-prototype bandwidths.

    Returns
    -------
    nbr_w : scipy.sparse.csr_matrix, shape (M, M)
        Sparse matrix of neighborhood activation weights.
        nbr_w[i] gives the activation weights for prototype i's
        active neighbors. Self-activation (diagonal) is included.
    """
    M = dist.shape[0]
    rho = self._broadcast_rho(rho, M)

    if self.kind == "exp":
        W = self._exp_kernel(dist, rho)

    W[W < self.h_min] = 0.0
    return csr_matrix(W)

Visualization

gtsom.vis_tools.vis_embedding_discrete

vis_embedding_discrete(
    x,
    y,
    z=None,
    ctab=None,
    point_size=2,
    point_color="black",
    point_size_wts=None,
    point_size_wts_trans="identity",
    point_shape="o",
    graph=None,
    edge_size=0.25,
    edge_color="antiquewhite3",
    xrev=False,
    yrev=False,
    xlim=None,
    ylim=None,
    xlab="x",
    ylab="y",
    title=None,
    subtitle=None,
    caption=None,
    legend_pos="none",
    legend_title=None,
    legend_nlines=1,
    legend_key_size=5,
    text_color="black",
    show_grid=True,
    seed=None,
)

Scatter / embedding plot with a discrete (categorical) color scale.

Parameters:

Name Type Description Default
x array - like

Point coordinates.

required
y array - like

Point coordinates.

required
z array - like or None

Categorical labels for each point. If None, all points are drawn in point_color with no legend.

None
ctab dict or None

Label->hex-color mapping (as returned by parse_ctab or build_ctab). If z is provided but ctab is None, colors are generated automatically via build_ctab.

None
point_size float

Maximum point size. The actual size is scaled by point_size_wts in the range [point_size * 0.1, point_size].

2
point_color str

Fallback color when both z and ctab are None.

'black'
point_size_wts array - like or None

Per-point size weights. If None all points get the same size.

None
point_size_wts_trans str

Scale transformation applied to size weights (e.g. "identity", "sqrt", "log10").

'identity'
point_shape str

Matplotlib marker string (e.g. "o", "s", "^").

'o'
graph array - like(N, N) or None

Adjacency matrix. When provided, edges are drawn before points.

None
edge_size float

Line width for graph edges.

0.25
edge_color str

Color for graph edges.

'antiquewhite3'
xrev bool

Reverse the x or y axis.

False
yrev bool

Reverse the x or y axis.

False
xlim tuple or None

Axis limits (min, max).

None
ylim tuple or None

Axis limits (min, max).

None
xlab str

Axis labels.

'x'
ylab str

Axis labels.

'x'
title str or None

Plot annotations.

None
subtitle str or None

Plot annotations.

None
caption str or None

Plot annotations.

None
legend_pos str

"none", "right", or "bottom".

'none'
legend_title str or None

Legend title.

None
legend_nlines int

Number of columns (right legend) or rows (bottom legend).

1
legend_key_size float

Override size of legend color keys.

5
text_color str

Color for all text elements (passed to theme_minimal_bold).

'black'
show_grid bool

If False, panel grid lines are removed.

True
seed int or None

Random seed for build_ctab when auto-generating colors (only used when ctab is None and n_labels > 10).

None

Returns:

Type Description
ggplot
Source code in src/gtsom/vis_tools.py
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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
426
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
453
454
455
456
457
458
459
460
461
462
463
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def vis_embedding_discrete(
    x, y,
    z=None, ctab=None,
    point_size=2, point_color="black",
    point_size_wts=None, point_size_wts_trans="identity",
    point_shape="o",
    graph=None, edge_size=0.25, edge_color="antiquewhite3",
    xrev=False, yrev=False, xlim=None, ylim=None,
    xlab="x", ylab="y",
    title=None, subtitle=None, caption=None,
    legend_pos="none", legend_title=None,
    legend_nlines=1, legend_key_size=5,
    text_color="black", show_grid=True,
    seed=None,
):
    """
    Scatter / embedding plot with a discrete (categorical) color scale.

    Parameters
    ----------
    x, y : array-like
        Point coordinates.
    z : array-like or None
        Categorical labels for each point. If None, all points are
        drawn in ``point_color`` with no legend.
    ctab : dict or None
        Label->hex-color mapping (as returned by ``parse_ctab`` or
        ``build_ctab``). If z is provided but ctab is None, colors are
        generated automatically via ``build_ctab``.
    point_size : float
        Maximum point size. The actual size is scaled by ``point_size_wts``
        in the range [point_size * 0.1, point_size].
    point_color : str
        Fallback color when both z and ctab are None.
    point_size_wts : array-like or None
        Per-point size weights. If None all points get the same size.
    point_size_wts_trans : str
        Scale transformation applied to size weights (e.g. "identity",
        "sqrt", "log10").
    point_shape : str
        Matplotlib marker string (e.g. "o", "s", "^").
    graph : array-like (N, N) or None
        Adjacency matrix. When provided, edges are drawn before points.
    edge_size : float
        Line width for graph edges.
    edge_color : str
        Color for graph edges.
    xrev, yrev : bool
        Reverse the x or y axis.
    xlim, ylim : tuple or None
        Axis limits (min, max).
    xlab, ylab : str
        Axis labels.
    title, subtitle, caption : str or None
        Plot annotations.
    legend_pos : str
        "none", "right", or "bottom".
    legend_title : str or None
        Legend title.
    legend_nlines : int
        Number of columns (right legend) or rows (bottom legend).
    legend_key_size : float
        Override size of legend color keys.
    text_color : str
        Color for all text elements (passed to ``theme_minimal_bold``).
    show_grid : bool
        If False, panel grid lines are removed.
    seed : int or None
        Random seed for ``build_ctab`` when auto-generating colors
        (only used when ctab is None and n_labels > 10).

    Returns
    -------
    plotnine.ggplot
    """
    x = np.asarray(x)
    y = np.asarray(y)
    if len(x) != len(y):
        raise ValueError("x and y must have the same length.")

    # ---- resolve z / ctab ------------------------------------------------
    if z is None and ctab is None:
        # No labels: single color, no legend
        z = np.ones(len(x), dtype=int)
        ctab = parse_ctab([1], [point_color])
        legend_pos = "none"
    elif z is not None and ctab is None:
        # Labels given but no color table: auto-generate one (ignoring None)
        ctab = build_ctab(z, seed=seed)
    elif z is not None and ctab is not None:
        # Both given: normalize ctab keys to str, coerce z to str, then
        # validate. This guarantees factor levels and dict keys are the same
        # type, preventing plotnine from falling back to using labels as color
        # specs (e.g. '6' being parsed as matplotlib grayscale).
        ctab = {str(k): v for k, v in ctab.items()}
        z = np.array([str(v) if not _is_missing(v) else v
                      for v in np.asarray(z, dtype=object)])
        missing = set(v for v in z if not _is_missing(v)) - set(ctab.keys())
        if missing:
            raise ValueError(f"z contains labels not found in ctab: {missing}")

    # Normalize ctab keys to str in all branches (build_ctab already does
    # this internally, but a user-supplied ctab may have integer keys).
    ctab = {str(k): v for k, v in ctab.items()}

    z = np.asarray(z, dtype=object)

    # ---- mask out None/NaN points ----------------------------------------
    # Points with no label are excluded from both the point layer and any
    # graph edges, matching R/ggplot2 behavior of silently dropping NA rows.
    valid = np.array([not _is_missing(v) for v in z])
    x_plot    = x[valid]
    y_plot    = y[valid]
    z_plot    = np.array([str(v) for v in z[valid]])
    valid_idx = np.where(valid)[0]

    # Sanity check: Categorical categories and ctab keys must be identical
    # sets so plotnine's factor->color lookup never fails silently.
    assert set(z_plot).issubset(set(ctab.keys())), (
        "Internal error: z_plot contains labels not in ctab after coercion. "
        "Please file a bug report."
    )

    # ---- build plot -------------------------------------------------------
    g = ggplot()

    if graph is not None:
        # Subset graph to valid points only
        try:
            import scipy.sparse as sp
            if sp.issparse(graph):
                graph_sub = graph[np.ix_(valid_idx, valid_idx)]
            else:
                graph_sub = np.asarray(graph)[np.ix_(valid_idx, valid_idx)]
        except ImportError:
            graph_sub = np.asarray(graph)[np.ix_(valid_idx, valid_idx)]
        seg = _build_graph_layer(x_plot, y_plot, graph_sub, edge_size, edge_color)
        if seg is not None:
            g = g + seg

    n_plot = len(x_plot)
    size_wts = (
        np.ones(len(x)) if point_size_wts is None else np.asarray(point_size_wts)
    )
    if len(size_wts) != len(x):
        raise ValueError("point_size_wts must have the same length as x.")
    size_wts_plot = size_wts[valid]

    plot_df = pd.DataFrame({
        "x":    x_plot,
        "y":    y_plot,
        "z":    pd.Categorical(z_plot, categories=list(ctab.keys())),
        "size": size_wts_plot,
    })

    g = g + geom_point(
        data=plot_df,
        mapping=aes(x="x", y="y", color="z", size="size"),
        shape=point_shape,
    )
    # Pass values as a list (not dict) in the same order as breaks.
    # plotnine's dict lookup fails when factor levels are numpy.str_ and
    # dict keys are plain str, even though they print identically.
    _breaks = list(ctab.keys())
    g = g + scale_color_manual(
        name=legend_title,
        values=[ctab[k] for k in _breaks],
        breaks=_breaks,
    )
    g = _apply_size_scale(g, point_size, point_size_wts_trans)

    # ---- axes, labels ----------------------------------------------------
    g = _apply_axis_scales(g, xrev, yrev, xlim, ylim, xlab, ylab)
    g = g + labs(title=title, subtitle=subtitle, caption=caption)

    # ---- legend guides (before theme) ------------------------------------
    if legend_pos == "right":
        g = g + guides(
            color=guide_legend(
                title=legend_title,
                nrow=None, ncol=legend_nlines,
                byrow=False,
                override_aes={"shape": "s", "size": legend_key_size},
            )
        )
    elif legend_pos == "bottom":
        g = g + guides(
            color=guide_legend(
                title=legend_title,
                nrow=legend_nlines, ncol=None,
                byrow=False,
                override_aes={"shape": "s", "size": legend_key_size},
            )
        )

    # ---- single consolidated theme call ----------------------------------
    # All theme elements in one call so nothing overrides the bold settings.
    legend_kwargs = {}
    if legend_pos == "none":
        legend_kwargs["legend_position"] = "none"
    elif legend_pos == "right":
        legend_kwargs["legend_position"] = "right"
        legend_kwargs["legend_direction"] = "vertical"
    elif legend_pos == "bottom":
        legend_kwargs["legend_position"] = "bottom"
        legend_kwargs["legend_direction"] = "horizontal"

    grid_kwargs = {}
    if not show_grid:
        grid_kwargs["panel_grid_major"] = element_blank()
        grid_kwargs["panel_grid_minor"] = element_blank()

    g = g + theme_minimal_bold(text_color=text_color, **legend_kwargs, **grid_kwargs)

    return g

gtsom.vis_tools.vis_embedding_continuous

vis_embedding_continuous(
    x,
    y,
    z,
    cmap="viridis",
    point_size=2,
    point_size_wts=None,
    point_size_wts_trans="identity",
    point_shape="o",
    graph=None,
    edge_size=0.25,
    edge_color="antiquewhite3",
    xrev=False,
    yrev=False,
    xlim=None,
    ylim=None,
    xlab="x",
    ylab="y",
    title=None,
    subtitle=None,
    caption=None,
    legend_pos="none",
    legend_title=None,
    text_color="black",
    show_grid=True,
)

Scatter / embedding plot with a continuous color scale.

Parameters:

Name Type Description Default
x array - like

Point coordinates.

required
y array - like

Point coordinates.

required
z array - like

Continuous values mapped to color.

required
cmap str

Colormap name (any matplotlib-compatible string, e.g. "viridis", "plasma", "magma").

'viridis'
point_size float

Maximum point size.

2
point_size_wts array - like or None

Per-point size weights. If None all points get the same size.

None
point_size_wts_trans str

Scale transformation for size weights.

'identity'
point_shape str

Matplotlib marker string.

'o'
graph array - like(N, N) or None

Adjacency matrix for optional edge layer.

None
edge_size float

Line width for graph edges.

0.25
edge_color str

Color for graph edges.

'antiquewhite3'
xrev bool

Reverse x or y axis.

False
yrev bool

Reverse x or y axis.

False
xlim tuple or None

Axis limits.

None
ylim tuple or None

Axis limits.

None
xlab str

Axis labels.

'x'
ylab str

Axis labels.

'x'
title str or None

Plot annotations.

None
subtitle str or None

Plot annotations.

None
caption str or None

Plot annotations.

None
legend_pos str

"none", "right", or "bottom".

'none'
legend_title str or None

Colorbar title.

None
text_color str

Color for all text elements.

'black'
show_grid bool

If False, panel grid lines are removed.

True

Returns:

Type Description
ggplot
Source code in src/gtsom/vis_tools.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
def vis_embedding_continuous(
    x, y, z,
    cmap="viridis",
    point_size=2,
    point_size_wts=None, point_size_wts_trans="identity",
    point_shape="o",
    graph=None, edge_size=0.25, edge_color="antiquewhite3",
    xrev=False, yrev=False, xlim=None, ylim=None,
    xlab="x", ylab="y",
    title=None, subtitle=None, caption=None,
    legend_pos="none", legend_title=None,
    text_color="black", show_grid=True,
):
    """
    Scatter / embedding plot with a continuous color scale.

    Parameters
    ----------
    x, y : array-like
        Point coordinates.
    z : array-like
        Continuous values mapped to color.
    cmap : str
        Colormap name (any matplotlib-compatible string, e.g. "viridis",
        "plasma", "magma").
    point_size : float
        Maximum point size.
    point_size_wts : array-like or None
        Per-point size weights. If None all points get the same size.
    point_size_wts_trans : str
        Scale transformation for size weights.
    point_shape : str
        Matplotlib marker string.
    graph : array-like (N, N) or None
        Adjacency matrix for optional edge layer.
    edge_size : float
        Line width for graph edges.
    edge_color : str
        Color for graph edges.
    xrev, yrev : bool
        Reverse x or y axis.
    xlim, ylim : tuple or None
        Axis limits.
    xlab, ylab : str
        Axis labels.
    title, subtitle, caption : str or None
        Plot annotations.
    legend_pos : str
        "none", "right", or "bottom".
    legend_title : str or None
        Colorbar title.
    text_color : str
        Color for all text elements.
    show_grid : bool
        If False, panel grid lines are removed.

    Returns
    -------
    plotnine.ggplot
    """
    x = np.asarray(x)
    y = np.asarray(y)
    z = np.asarray(z, dtype=float)
    if not (len(x) == len(y) == len(z)):
        raise ValueError("x, y, and z must all have the same length.")

    # ---- build plot -------------------------------------------------------
    g = ggplot()

    # ---- mask out NaN points ---------------------------------------------
    valid = ~np.isnan(z)
    x_plot        = x[valid]
    y_plot        = y[valid]
    z_plot        = z[valid]
    valid_idx     = np.where(valid)[0]

    if graph is not None:
        try:
            import scipy.sparse as sp
            if sp.issparse(graph):
                graph_plot = graph[np.ix_(valid_idx, valid_idx)]
            else:
                graph_plot = np.asarray(graph)[np.ix_(valid_idx, valid_idx)]
        except ImportError:
            graph_plot = np.asarray(graph)[np.ix_(valid_idx, valid_idx)]
        seg = _build_graph_layer(x_plot, y_plot, graph_plot, edge_size, edge_color)
        if seg is not None:
            g = g + seg

    size_wts = (
        np.ones(len(x)) if point_size_wts is None else np.asarray(point_size_wts)
    )
    if len(size_wts) != len(x):
        raise ValueError("point_size_wts must have the same length as x.")
    size_wts_plot = size_wts[valid]

    plot_df = pd.DataFrame({
        "x":    x_plot,
        "y":    y_plot,
        "z":    z_plot,
        "size": size_wts_plot,
    })

    g = g + geom_point(
        data=plot_df,
        mapping=aes(x="x", y="y", color="z", size="size"),
        shape=point_shape,
    )
    g = g + scale_color_continuous(cmap_name=cmap, name=legend_title)
    g = _apply_size_scale(g, point_size, point_size_wts_trans)

    # ---- axes, labels ----------------------------------------------------
    g = _apply_axis_scales(g, xrev, yrev, xlim, ylim, xlab, ylab)
    g = g + labs(title=title, subtitle=subtitle, caption=caption)

    # ---- legend guides (before theme) ------------------------------------
    if legend_pos == "right":
        g = g + guides(color=guide_colorbar(title=legend_title))
    elif legend_pos == "bottom":
        g = g + guides(color=guide_colorbar(title=legend_title))

    # ---- single consolidated theme call ----------------------------------
    legend_kwargs = {}
    if legend_pos == "none":
        legend_kwargs["legend_position"] = "none"
    elif legend_pos == "right":
        legend_kwargs["legend_position"] = "right"
        legend_kwargs["legend_direction"] = "vertical"
    elif legend_pos == "bottom":
        legend_kwargs["legend_position"] = "bottom"
        legend_kwargs["legend_direction"] = "horizontal"

    grid_kwargs = {}
    if not show_grid:
        grid_kwargs["panel_grid_major"] = element_blank()
        grid_kwargs["panel_grid_minor"] = element_blank()

    g = g + theme_minimal_bold(text_color=text_color, **legend_kwargs, **grid_kwargs)

    return g

gtsom.vis_tools.build_ctab

build_ctab(labels, seed=None)

Automatically generate a label->color mapping for a set of category labels.

Uses matplotlib's Tab10 palette for the first 10 labels (perceptually well-tuned for categorical data), then extends with distinctipy for any additional labels, ensuring new colors are visually distinct from the Tab10 colors already assigned.

Labels are sorted before color assignment so that the mapping is deterministic and stable across calls with the same label set.

Parameters:

Name Type Description Default
labels array - like

Category labels. Duplicates are ignored; labels are sorted before color assignment.

required
seed int or None

Random seed passed to distinctipy for reproducibility when more than 10 labels are present. If None, results may vary between calls.

None

Returns:

Type Description
dict

{label: hex_color_string}

Raises:

Type Description
ImportError

If more than 10 labels are provided and distinctipy is not installed.

Notes

distinctipy is an optional dependency. Install with: pip install distinctipy

Source code in src/gtsom/vis_tools.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def build_ctab(labels, seed=None):
    """
    Automatically generate a label->color mapping for a set of category labels.

    Uses matplotlib's Tab10 palette for the first 10 labels (perceptually
    well-tuned for categorical data), then extends with distinctipy for any
    additional labels, ensuring new colors are visually distinct from the
    Tab10 colors already assigned.

    Labels are sorted before color assignment so that the mapping is
    deterministic and stable across calls with the same label set.

    Parameters
    ----------
    labels : array-like
        Category labels. Duplicates are ignored; labels are sorted before
        color assignment.
    seed : int or None
        Random seed passed to distinctipy for reproducibility when more
        than 10 labels are present. If None, results may vary between calls.

    Returns
    -------
    dict
        {label: hex_color_string}

    Raises
    ------
    ImportError
        If more than 10 labels are provided and distinctipy is not installed.

    Notes
    -----
    distinctipy is an optional dependency. Install with:
        pip install distinctipy
    """
    # Strip None/NaN before sorting — sorted() can't compare None to str
    sorted_labels = sorted(set(str(l) for l in labels if not _is_missing(l)))
    n = len(sorted_labels)
    if n == 0:
        raise ValueError("labels contains only None/NaN values.")

    # Pull Tab10 colors as (r, g, b) tuples in [0, 1]
    tab10 = plt.get_cmap("tab10")
    tab10_rgb = [tab10(i)[:3] for i in range(10)]   # list of (r,g,b)

    if n <= 10:
        chosen_rgb = tab10_rgb[:n]
    else:
        try:
            import distinctipy
        except ImportError:
            raise ImportError(
                "More than 10 labels requires distinctipy. "
                "Install with: pip install distinctipy"
            )
        n_extra = n - 10
        extra_rgb = distinctipy.get_colors(
            n_colors=n_extra,
            exclude_colors=tab10_rgb,
            rng=seed,
        )
        chosen_rgb = tab10_rgb + list(extra_rgb)

    hex_colors = [
        "#{:02X}{:02X}{:02X}".format(int(r * 255), int(g * 255), int(b * 255))
        for r, g, b in chosen_rgb
    ]
    return dict(zip(sorted_labels, hex_colors))

gtsom.vis_tools.parse_ctab

parse_ctab(labels, colors)

Build a label->color mapping dict, accepting colors as hex strings or as an RGB array.

Parameters:

Name Type Description Default
labels array - like

Category labels.

required
colors array - like

Either a list of hex strings (e.g. ["#FF0000", "#00FF00"]) or an (N, 3) array of RGB values. RGB values are auto-detected as uint8 (0-255) if any value exceeds 1, otherwise treated as float (0-1).

required

Returns:

Type Description
dict

{label: hex_color_string}

Raises:

Type Description
ValueError

If inputs are inconsistent or malformed.

Source code in src/gtsom/vis_tools.py
 95
 96
 97
 98
 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
def parse_ctab(labels, colors):
    """
    Build a label->color mapping dict, accepting colors as hex strings
    or as an RGB array.

    Parameters
    ----------
    labels : array-like
        Category labels.
    colors : array-like
        Either a list of hex strings (e.g. ["#FF0000", "#00FF00"]) or
        an (N, 3) array of RGB values. RGB values are auto-detected as
        uint8 (0-255) if any value exceeds 1, otherwise treated as
        float (0-1).

    Returns
    -------
    dict
        {label: hex_color_string}

    Raises
    ------
    ValueError
        If inputs are inconsistent or malformed.
    """
    labels = list(labels)
    n = len(labels)

    # Strip None/NaN from labels before any processing so that callers
    # don't have to pre-filter. None keys in the dict would cause silent
    # mismatches downstream.
    labels = [str(l) for l in labels if not _is_missing(l)]
    n = len(labels)
    if n == 0:
        raise ValueError("labels contains only None/NaN values.")

    # --- colors is a list / 1-D array: must be hex strings ----------------
    if isinstance(colors, (list, tuple)) or (
        isinstance(colors, np.ndarray) and colors.ndim == 1
    ):
        colors = list(colors)
        if not all(isinstance(c, str) for c in colors):
            raise ValueError("If colors is 1-D, it must contain hex strings.")
        if len(colors) < n:
            raise ValueError("len(colors) must be >= len(labels).")
        return dict(zip(labels, colors[:n]))

    # --- colors is a 2-D array: treat as RGB ------------------------------
    colors = np.asarray(colors)
    if colors.ndim != 2 or colors.shape[1] != 3:
        raise ValueError("If colors is 2-D, it must have shape (N, 3) for RGB.")
    if colors.shape[0] < n:
        raise ValueError("colors must have at least as many rows as labels.")

    colors = colors[:n].astype(float)
    if colors.max() > 1.0:
        colors = colors / 255.0
    colors = np.clip(colors, 0, 1)

    hex_colors = [
        "#{:02X}{:02X}{:02X}".format(int(r * 255), int(g * 255), int(b * 255))
        for r, g, b in colors
    ]
    return dict(zip(labels, hex_colors))

gtsom.vis_tools.theme_minimal_bold

theme_minimal_bold(text_color='black', **kwargs)

Plotnine equivalent of theme_minimal_bold() from R/VisTools.

Parameters:

Name Type Description Default
text_color str

Color applied to all axis text, titles, and legend labels.

'black'
**kwargs

Additional theme() keyword arguments forwarded verbatim, allowing the caller to override or extend any theme element.

{}

Returns:

Type Description
theme

A composable theme object; add it to any ggplot with +.

Source code in src/gtsom/vis_tools.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def theme_minimal_bold(text_color="black", **kwargs):
    """
    Plotnine equivalent of theme_minimal_bold() from R/VisTools.

    Parameters
    ----------
    text_color : str
        Color applied to all axis text, titles, and legend labels.
    **kwargs
        Additional theme() keyword arguments forwarded verbatim,
        allowing the caller to override or extend any theme element.

    Returns
    -------
    plotnine.theme
        A composable theme object; add it to any ggplot with +.
    """
    return (
        theme_minimal() +
        theme(
            text         = element_text(family="DejaVu Sans", color=text_color),  # base for all text
            axis_title   = element_text(weight="bold"),
            plot_title   = element_text(ha="left", weight="bold"),
            axis_line    = element_line(color=text_color),
            legend_title = element_text(weight="bold"),
            panel_border      = element_blank(),
            plot_background   = element_rect(fill="white", color=None),
            panel_background  = element_rect(fill="white", color=None),
            **kwargs,
        )
    )

DRMetrics

gtsom.dr_metrics.compute_dr_metrics

compute_dr_metrics(
    X,
    Y,
    embed_geodesic_dist=None,
    CONN=None,
    compute_coranking=True,
)

Compute dimensionality reduction quality metrics for a (high-d, low-d) pair.

Evaluates how faithfully the low-dimensional embedding Y preserves the structure of the high-dimensional point set X. Designed for use with SOM prototype vectors and their 2-D output-space coordinates, but applicable to any matched (high-d, low-d) pair.

Two families of metrics are available:

Co-ranking family (requires pyDRMetrics): measures of neighborhood preservation at local scales, global scales, and across all scales, plus a chance-corrected summary (LCMC_AUC) and a trustworthiness summary (Trust_AUC). Set compute_coranking=False to skip if pyDRMetrics is not installed.

CONN_WAFL (requires embed_geodesic_dist and CONN): a CONN-weighted measure of embedding folding — how many embedding hops are needed, on average, to span each high-d CONN neighborhood. Requires only numpy/scipy.

Parameters:

Name Type Description Default
X (array - like, shape(M, d))

High-dimensional coordinates (e.g. SOM prototype vectors W).

required
Y (array - like, shape(M, dim))

Low-dimensional coordinates (e.g. SOM embedding coords Embedding.coords).

required
embed_geodesic_dist (ndarray, shape(M, M))

Pairwise geodesic hop-count distances in the embedding graph. Required for CONN_WAFL. In GTSOM, this is Embedding.dist.

None
CONN scipy.sparse matrix, shape (M, M)

Prototype co-adjacency matrix. Required for CONN_WAFL. In GTSOM, this is VQRecaller.CONN.

None
compute_coranking bool

Whether to compute co-ranking family metrics via pyDRMetrics. Set to False if pyDRMetrics is not installed or if only CONN_WAFL is needed.

True

Returns:

Type Description
DRMetricsResult

Dataclass with the following fields. Fields that were not computed are None.

================ ========== ============= ======================= Field Range Better Requires ================ ========== ============= ======================= Q_local [0, 1] higher pyDRMetrics Q_global [0, 1] higher pyDRMetrics Q_AUC [0, 1] higher pyDRMetrics LCMC_AUC [0, 1] higher pyDRMetrics Trust_AUC [0, 1] higher pyDRMetrics CONN_WAFL [1, ∞) lower (→ 1) embed_geodesic_dist + CONN CONN_WAFL_SE [0, ∞) lower embed_geodesic_dist + CONN ================ ========== ============= =======================

See :class:DRMetricsResult for full descriptions of each field.

Raises:

Type Description
ImportError

If compute_coranking=True and pyDRMetrics is not installed.

ValueError

If CONN is provided without embed_geodesic_dist, or vice versa. If X and Y have different numbers of rows.

Examples:

Full metrics (requires pyDRMetrics and a CONN matrix):

>>> result = compute_dr_metrics(X=W, Y=coords, embed_geodesic_dist=embed.dist,
...                             CONN=recaller.CONN)
>>> result.LCMC_AUC
0.812...
>>> result.CONN_WAFL
1.043...

Co-ranking only (no CONN needed):

>>> result = compute_dr_metrics(X=W, Y=coords)
>>> result.Q_local
0.734...
>>> result.Trust_AUC
0.891...

CONN_WAFL only (no pyDRMetrics needed):

>>> result = compute_dr_metrics(X=W, Y=coords, embed_geodesic_dist=embed.dist,
...                             CONN=recaller.CONN,
...                             compute_coranking=False)
>>> result.CONN_WAFL
1.043...
Notes

X and Y must have the same number of rows M (one row per point). No internal scaling is applied — pass pre-processed arrays if needed.

Source code in src/gtsom/dr_metrics.py
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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
426
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
453
454
455
456
457
458
def compute_dr_metrics(
    X,
    Y,
    embed_geodesic_dist=None,
    CONN=None,
    compute_coranking=True,
):
    """
    Compute dimensionality reduction quality metrics for a (high-d, low-d) pair.

    Evaluates how faithfully the low-dimensional embedding ``Y`` preserves the
    structure of the high-dimensional point set ``X``. Designed for use with
    SOM prototype vectors and their 2-D output-space coordinates, but
    applicable to any matched (high-d, low-d) pair.

    Two families of metrics are available:

    **Co-ranking family** (requires ``pyDRMetrics``): measures of neighborhood
    preservation at local scales, global scales, and across all scales, plus a
    chance-corrected summary (LCMC_AUC) and a trustworthiness summary
    (Trust_AUC). Set ``compute_coranking=False`` to skip if ``pyDRMetrics``
    is not installed.

    **CONN_WAFL** (requires ``embed_geodesic_dist`` and ``CONN``): a CONN-weighted measure of
    embedding folding — how many embedding hops are needed, on average, to
    span each high-d CONN neighborhood. Requires only numpy/scipy.

    Parameters
    ----------
    X : array-like, shape (M, d)
        High-dimensional coordinates (e.g. SOM prototype vectors ``W``).
    Y : array-like, shape (M, dim)
        Low-dimensional coordinates (e.g. SOM embedding coords
        ``Embedding.coords``).
    embed_geodesic_dist : np.ndarray, shape (M, M), optional
        Pairwise geodesic hop-count distances in the embedding graph.
        Required for CONN_WAFL. In GTSOM, this is ``Embedding.dist``.
    CONN : scipy.sparse matrix, shape (M, M), optional
        Prototype co-adjacency matrix. Required for CONN_WAFL. In GTSOM,
        this is ``VQRecaller.CONN``.
    compute_coranking : bool, default True
        Whether to compute co-ranking family metrics via ``pyDRMetrics``.
        Set to False if ``pyDRMetrics`` is not installed or if only
        CONN_WAFL is needed.

    Returns
    -------
    DRMetricsResult
        Dataclass with the following fields. Fields that were not computed
        are None.

        ================  ==========  =============  =======================
        Field             Range       Better         Requires
        ================  ==========  =============  =======================
        Q_local           [0, 1]      higher         pyDRMetrics
        Q_global          [0, 1]      higher         pyDRMetrics
        Q_AUC             [0, 1]      higher         pyDRMetrics
        LCMC_AUC          [0, 1]      higher         pyDRMetrics
        Trust_AUC         [0, 1]      higher         pyDRMetrics
        CONN_WAFL         [1, ∞)      lower (→ 1)   embed_geodesic_dist + CONN
        CONN_WAFL_SE      [0, ∞)      lower          embed_geodesic_dist + CONN
        ================  ==========  =============  =======================

        See :class:`DRMetricsResult` for full descriptions of each field.

    Raises
    ------
    ImportError
        If ``compute_coranking=True`` and ``pyDRMetrics`` is not installed.
    ValueError
        If ``CONN`` is provided without ``embed_geodesic_dist``, or vice versa.
        If ``X`` and ``Y`` have different numbers of rows.

    Examples
    --------
    Full metrics (requires pyDRMetrics and a CONN matrix):

    >>> result = compute_dr_metrics(X=W, Y=coords, embed_geodesic_dist=embed.dist,
    ...                             CONN=recaller.CONN)
    >>> result.LCMC_AUC
    0.812...
    >>> result.CONN_WAFL
    1.043...

    Co-ranking only (no CONN needed):

    >>> result = compute_dr_metrics(X=W, Y=coords)
    >>> result.Q_local
    0.734...
    >>> result.Trust_AUC
    0.891...

    CONN_WAFL only (no pyDRMetrics needed):

    >>> result = compute_dr_metrics(X=W, Y=coords, embed_geodesic_dist=embed.dist,
    ...                             CONN=recaller.CONN,
    ...                             compute_coranking=False)
    >>> result.CONN_WAFL
    1.043...

    Notes
    -----
    ``X`` and ``Y`` must have the same number of rows M (one row per point).
    No internal scaling is applied — pass pre-processed arrays if needed.
    """
    X = np.asarray(X, dtype=np.float64)
    Y = np.asarray(Y, dtype=np.float64)

    if X.shape[0] != Y.shape[0]:
        raise ValueError(
            f"X and Y must have the same number of rows. "
            f"Got X.shape={X.shape}, Y.shape={Y.shape}."
        )

    if (embed_geodesic_dist is None) != (CONN is None):
        raise ValueError(
            "embed_geodesic_dist and CONN must be supplied together — both or neither."
        )

    result = DRMetricsResult()

    # ------------------------------------------------------------------
    # Co-ranking family metrics
    # ------------------------------------------------------------------
    if compute_coranking:
        (
            result.Q_local,
            result.Q_global,
            result.Q_AUC,
            result.LCMC_AUC,
            result.Trust_AUC,
        ) = _compute_coranking_metrics(X, Y)

    # ------------------------------------------------------------------
    # CONN_WAFL
    # ------------------------------------------------------------------
    if embed_geodesic_dist is not None and CONN is not None:
        result.CONN_WAFL, result.CONN_WAFL_SE = _compute_conn_wafl(
            np.asarray(embed_geodesic_dist, dtype=np.float64), CONN
        )

    return result

gtsom.dr_metrics.DRMetricsResult dataclass

DRMetricsResult(
    Q_local: Optional[float] = None,
    Q_global: Optional[float] = None,
    Q_AUC: Optional[float] = None,
    LCMC_AUC: Optional[float] = None,
    Trust_AUC: Optional[float] = None,
    CONN_WAFL: Optional[float] = None,
    CONN_WAFL_SE: Optional[float] = None,
)

Container for dimensionality reduction quality metrics.

All values are floats. Fields that could not be computed (e.g. CONN_WAFL when no CONN was provided, or co-ranking metrics when pyDRMetrics is not installed) are stored as None.

The co-ranking metrics (Q_local through Trust_AUC) are derived from the co-ranking matrix of the (high-d, low-d) point pair. They measure how well the embedding preserves neighborhood structure at various scales. All co-ranking metrics are in [0, 1]; higher is better.

Attributes:

Name Type Description
Q_local float or None

Local neighborhood preservation, averaged over neighborhood sizes k ≤ kmax, where kmax is the scale at which LCMC is maximized (a data-driven split between local and global scales). Measures whether the nearest neighbors in high-d are also near neighbors in low-d. Higher is better.

Q_global float or None

Global neighborhood preservation, averaged over neighborhood sizes k > kmax. Measures whether points that are far apart in high-d are also far apart in low-d. Complements Q_local: an embedding can score well locally but fold or compress at larger scales (or vice versa). Higher is better.

Q_AUC float or None

Mean QNN over all neighborhood sizes k — the area under the QNN(k) curve (computed as a simple mean, mirroring pyDRMetrics). Summarises neighborhood preservation across all scales simultaneously. Higher is better.

LCMC_AUC float or None

Chance-corrected AUC of the Local Continuity Meta-Criterion (LCMC).

LCMC(k) = QNN(k) - k / (M - 1)

The subtracted term is the expected QNN under a random embedding, so LCMC(k) measures how much better than chance the embedding is at scale k. LCMC_AUC integrates LCMC over all k and normalizes by the theoretical maximum AUC (integral of 1 - k/K), giving a score in [0, 1] where 1 = perfect preservation and 0 = chance level. This is the most interpretable single scalar summary of embedding quality.

Trust_AUC float or None

Trustworthiness, averaged over all neighborhood sizes k. T(k) measures the absence of false neighbors introduced by the embedding: points that appear as k-nearest neighbors in low-d but are not k-nearest neighbors in high-d. T(k) = 1 is perfect (no false neighbors at scale k); T(k) < 1 indicates intrusions. T(k) is typically monotonically decreasing with k (intrusions become inevitable at large k), so no local/global split is applied — the mean over all k is the natural summary. Higher is better.

CONN_WAFL float or None

Weighted Average Folding Length, computed over the CONN prototype co-adjacency graph. Measures how many hops in the embedding (low-d geodesic distance) are needed, on average, to span each pair of prototypes that are neighbors in high-d according to CONN:

CONN_WAFL = Σ_{(i,j): CONN[i,j]>0} CONN[i,j] * embed_geodesic_dist[i,j]
          / Σ_{(i,j): CONN[i,j]>0} CONN[i,j]

where embed_geodesic_dist[i,j] is the geodesic hop-count distance between prototypes i and j in the embedding graph. CONN_WAFL = 1 is ideal (every high-d CONN-neighbor pair is also a direct embedding neighbor). Values > 1 indicate folding: high-d neighbors are separated in the embedding, requiring multiple hops to connect them. Only computed when embed_geodesic_dist and CONN are provided.

CONN_WAFL_SE float or None

Weighted standard error of the CONN_WAFL estimate. None when CONN_WAFL is None.

as_dict

as_dict()

Return metric values as a plain dict.

Source code in src/gtsom/dr_metrics.py
149
150
151
def as_dict(self):
    """Return metric values as a plain dict."""
    return {f.name: getattr(self, f.name) for f in fields(self)}

to_dict

to_dict()

Return a serialization-ready dict of this result.

None values are stored as float('nan') so that the dict contains only plain Python floats (no None), which HDF5 attrs can store directly. Reconstructed by :meth:from_dict.

Returns:

Type Description
dict mapping field name → float (nan where the field is None)
Source code in src/gtsom/dr_metrics.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def to_dict(self):
    """
    Return a serialization-ready dict of this result.

    ``None`` values are stored as ``float('nan')`` so that the dict
    contains only plain Python floats (no None), which HDF5 attrs
    can store directly.  Reconstructed by :meth:`from_dict`.

    Returns
    -------
    dict mapping field name → float (nan where the field is None)
    """
    return {
        f.name: float("nan") if getattr(self, f.name) is None
                else float(getattr(self, f.name))
        for f in fields(self)
    }

from_dict classmethod

from_dict(d)

Reconstruct a DRMetricsResult from a dict produced by :meth:to_dict.

nan values are converted back to None.

Parameters:

Name Type Description Default
d dict

As returned by :meth:to_dict.

required

Returns:

Type Description
DRMetricsResult
Source code in src/gtsom/dr_metrics.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
@classmethod
def from_dict(cls, d):
    """
    Reconstruct a DRMetricsResult from a dict produced by
    :meth:`to_dict`.

    ``nan`` values are converted back to ``None``.

    Parameters
    ----------
    d : dict
        As returned by :meth:`to_dict`.

    Returns
    -------
    DRMetricsResult
    """
    kwargs = {
        name: None if (val is None or (isinstance(val, float) and np.isnan(val)))
              else float(val)
        for name, val in d.items()
    }
    return cls(**kwargs)