Skip to content

API Reference

SOUMAP

soumap.SOUMAP

SOUMAP(
    M, som_params=None, umap_params=None, ctrl_params=None
)

Self-Organizing UMAP.

Parameters:

Name Type Description Default
M int

Number of prototypes.

required
som_params SOMParams

SOM learning parameters. Defaults to SOMParams().

None
umap_params UMAPParams

UMAP embedding parameters. Defaults to UMAPParams().

None
ctrl_params CtrlParams

Training control parameters. Defaults to CtrlParams().

None

Examples:

Default parameters:

>>> model = SOUMAP(M=100)
>>> model.fit(X)

Custom parameters:

>>> model = SOUMAP(
...     M=100,
...     som_params=SOMParams(rho_0=3.0, rho_f=0.3),
...     ctrl_params=CtrlParams(total_epochs=200, verbose=False),
... )
Source code in src/soumap/soumap.py
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
def __init__(
    self,
    M,
    som_params=None,
    umap_params=None,
    ctrl_params=None,
):
    self.M = M
    self.som_params  = som_params  or SOMParams()
    self.umap_params = umap_params or UMAPParams()
    self.ctrl_params = ctrl_params or CtrlParams()

    # --- annealing schedules ---
    # halflife = total_epochs / 2 so each parameter reaches its
    # final value at exactly total_epochs.
    # If initial == final, use a constant schedule (no annealing).
    # Note: rho and nbr_topo_alpha annealing are owned by GTSOM
    # via compile() — only UMAP-side parameters are scheduled here.
    halflife = self.ctrl_params.total_epochs / 2
    self._lrate_sched   = self._make_sched(
        self.umap_params.lrate_0,    self.umap_params.lrate_f,    halflife)
    self._mindist_sched = self._make_sched(
        self.umap_params.min_dist_0, self.umap_params.min_dist_f, halflife)
    self._spread_sched  = self._make_sched(
        self.umap_params.spread_0,   self.umap_params.spread_f,   halflife)

    # --- learned state ---
    self.FSIM            = None   # (M, M) csr  fuzzy similarity matrix
    self.PCADJ           = None   # (M, M) csr  padded CADJ
    self.PCADJ_nhbs      = None   # list[list]  neighbor indices per prototype
    self.PCADJ_nhbs_size = None   # (M,) int    neighbor counts per prototype
    self.age             = 0      # int          total SOM epochs completed

    # --- learning history ---
    self.learn_hist      = []     # list of dicts, one per UMAP update step

    # --- internal objects ---
    self.gtsom           = None   # GTSOM instance, set during build()
    self._is_fitted      = False

W property

W

Prototype matrix, shape (M, d). Authoritative copy lives in gtsom.

coords property

coords

Embedding coordinates, shape (M, 2). Authoritative copy lives in gtsom.embed.

save

save(path)

Save this SOUMAP instance to an HDF5 file.

Serializes all parameter containers (SOMParams, UMAPParams, CtrlParams), training state, similarity matrices (FSIM, PCADJ), SOUMAP learning history, and the full GTSOM instance. The file can be reloaded with :meth:load to resume training or inspect results without retraining.

Parameters:

Name Type Description Default
path str

Destination file path. Created or overwritten.

required

Examples:

>>> model.fit(X, labels=y)
>>> model.save("soumap.h5")
>>> model2 = SOUMAP.load("soumap.h5")
>>> model2.fit(X, labels=y)   # resume training
Source code in src/soumap/soumap.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def save(self, path):
    """
    Save this SOUMAP instance to an HDF5 file.

    Serializes all parameter containers (SOMParams, UMAPParams,
    CtrlParams), training state, similarity matrices (FSIM, PCADJ),
    SOUMAP learning history, and the full GTSOM instance. The file
    can be reloaded with :meth:`load` to resume training or inspect
    results without retraining.

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

    Examples
    --------
    >>> model.fit(X, labels=y)
    >>> model.save("soumap.h5")
    >>> model2 = SOUMAP.load("soumap.h5")
    >>> model2.fit(X, labels=y)   # resume training
    """
    from .io import SOUMAPio
    SOUMAPio(self).save(path)

load classmethod

load(path)

Load a SOUMAP 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
SOUMAP

Fully reconstructed instance, ready for :meth:transform, :meth:fit (to resume training), or result inspection.

Examples:

>>> model = SOUMAP.load("soumap.h5")
>>> model.age
200
>>> model.gtsom.plot(color_by='labels')
Source code in src/soumap/soumap.py
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
@classmethod
def load(cls, path):
    """
    Load a SOUMAP from an HDF5 file created by :meth:`save`.

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

    Returns
    -------
    SOUMAP
        Fully reconstructed instance, ready for :meth:`transform`,
        :meth:`fit` (to resume training), or result inspection.

    Examples
    --------
    >>> model = SOUMAP.load("soumap.h5")
    >>> model.age
    200
    >>> model.gtsom.plot(color_by='labels')
    """
    from .io import SOUMAPio
    return SOUMAPio.load(path)

fit

fit(X, labels=None)

Run the SOUMAP learning loop.

Alternates between SOM chunks (gtsom.fit) and UMAP embedding updates (build_FSIM + gtsom.update_embedding) for ctrl_params.total_epochs total SOM epochs.

build() must be called before fit(). tune_embed_scale() must be called before build() if parameter calibration is desired.

Parameters:

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

Observation labels passed through to GTSOM for prototype-level label summaries. Not used by the SOUMAP learning algorithm.

None

Returns:

Type Description
self

Raises:

Type Description
RuntimeError

If build() has not been called yet.

Source code in src/soumap/soumap.py
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 fit(self, X, labels=None):
    """
    Run the SOUMAP learning loop.

    Alternates between SOM chunks (gtsom.fit) and UMAP embedding
    updates (build_FSIM + gtsom.update_embedding) for
    ctrl_params.total_epochs total SOM epochs.

    build() must be called before fit(). tune_embed_scale() must
    be called before build() if parameter calibration is desired.

    Parameters
    ----------
    X : np.ndarray, shape (N, d)
    labels : array-like, shape (N,), optional
        Observation labels passed through to GTSOM for prototype-level
        label summaries. Not used by the SOUMAP learning algorithm.

    Returns
    -------
    self

    Raises
    ------
    RuntimeError
        If build() has not been called yet.
    """
    if not self._is_fitted:
        raise RuntimeError(
            "build() must be called before fit(). "
            "Call model.build(X, labels) to initialize the SOM architecture."
        )

    n_chunks = self.ctrl_params.total_epochs // self.umap_params.update_freq
    remainder = self.ctrl_params.total_epochs % self.umap_params.update_freq

    for chunk in range(n_chunks):

        # --- SOM step ---
        self.gtsom.fit(
            X,
            n_epochs=self.umap_params.update_freq,
            labels=labels,
            verbose=self.ctrl_params.verbose,
            plot_every=self.ctrl_params.plot_every,
        )
        self.age = self.gtsom.age

        # --- UMAP step ---
        self.PCADJ, self.PCADJ_nhbs, self.PCADJ_nhbs_size = pad_CADJ(
            self.gtsom.recaller.CADJ,
            self.gtsom.recaller.CADJ_nhbs,
            self.gtsom.recaller.CADJ_nhbs_size,
            self.W,
            min_nhbs=self.ctrl_params.min_nhbs,
            fill_val=self.ctrl_params.fill_val,
        )

        if self.ctrl_params.verbose:
            pcadj_row_nnz = np.diff(self.PCADJ.indptr)
            print(
                f"  PCADJ: min_nnz={pcadj_row_nnz.min()}, "
                f"max_nnz={pcadj_row_nnz.max()}, "
                f"mean_nnz={pcadj_row_nnz.mean():.1f}, "
                f"empty_rows={(pcadj_row_nnz == 0).sum()}, "
                f"below_min_nhbs={(pcadj_row_nnz < self.ctrl_params.min_nhbs).sum()}"
            )

        self.FSIM = build_FSIM(
            self.W,
            self.PCADJ,
            self.PCADJ_nhbs,
        )

        if self.ctrl_params.verbose:
            fsim_row_nnz = np.diff(self.FSIM.indptr)
            print(
                f"  FSIM:  min_nnz={fsim_row_nnz.min()}, "
                f"max_nnz={fsim_row_nnz.max()}, "
                f"mean_nnz={fsim_row_nnz.mean():.1f}, "
                f"val_range=[{self.FSIM.data.min():.3f}, {self.FSIM.data.max():.3f}]"
            )
        # note: umap-learn takes (spread, min_dist) — not (min_dist, spread)
        a, b = umap_.find_ab_params(
            self._cur_spread(), self._cur_min_dist()
        )
        if self.ctrl_params.verbose:
            print(
                f"  UMAP update  "
                f"age={self.age}  "
                f"rho={self._cur_rho():.4f}  "
                f"alpha={self._cur_alpha():.4f}  "
                f"lrate={self._cur_lrate():.4f}  "
                f"min_dist={self._cur_min_dist():.4f}"
            )

        if self.umap_params.use_standard_umap:
            # --- diagnostic path: standard UMAP on W ---
            # Bypasses FSIM entirely. UMAP builds its own kNN graph
            # from W in feature space (n_neighbors=15 by default).
            # Warm-started from current coords so the embedding
            # evolves incrementally rather than reinitializing.
            import umap as umap_pkg
            reducer = umap_pkg.UMAP(
                n_components=2,
                init=self.coords.astype(np.float32),
                random_state=self.ctrl_params.random_state,
                n_epochs=self.umap_params.n_epochs,
            )
            new_coords = reducer.fit_transform(self.W)
        else:
            # --- normal SOUMAP path: optimize FSIM-based layout ---
            new_coords = optimize_layout(
                FSIM=self.FSIM,
                coords_init=self.coords,
                a=a,
                b=b,
                lrate=self._cur_lrate(),
                n_epochs=self.umap_params.n_epochs,
                negative_sample_rate=self.umap_params.negative_sample_rate,
                gamma=self.umap_params.gamma,
                parallel=self.ctrl_params.n_jobs != 1,
                random_state=self.ctrl_params.random_state,
                age=self.age,
            )
        new_coords = scale_coords(new_coords, self.ctrl_params.embedding_range)
        self.gtsom.update_embedding(new_coords)

        self._log_hist(
            n_new_epochs=self.umap_params.update_freq,
            umap_fields={
                'rho'     : self._cur_rho(),
                'alpha'   : self._cur_alpha(),
                'lrate'   : self._cur_lrate(),
                'min_dist': self._cur_min_dist(),
                'spread'  : self._cur_spread(),
                'a'       : a,
                'b'       : b,
            }
        )

    # run any remaining epochs that don't fill a full chunk
    if remainder > 0:
        self.gtsom.fit(
            X,
            n_epochs=remainder,
            labels=labels,
            verbose=self.ctrl_params.verbose,
            plot_every=self.ctrl_params.plot_every,
        )
        self.age = self.gtsom.age
        self._log_hist(n_new_epochs=remainder, umap_fields=None)

    return self

transform

transform(X)

Map observations to output space via BMU lookup.

Each observation is assigned to its nearest prototype (BMU) and the embedding coordinates of that prototype are returned.

Parameters:

Name Type Description Default
X (ndarray, shape(N, d))
required

Returns:

Name Type Description
coords (ndarray, shape(N, 2))
Source code in src/soumap/soumap.py
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
def transform(self, X):
    """
    Map observations to output space via BMU lookup.

    Each observation is assigned to its nearest prototype (BMU) and
    the embedding coordinates of that prototype are returned.

    Parameters
    ----------
    X : np.ndarray, shape (N, d)

    Returns
    -------
    coords : np.ndarray, shape (N, 2)
    """
    return self.gtsom.transform(X)

fit_transform

fit_transform(X, labels=None)

Run the SOUMAP learning loop and return embedding coordinates for X.

Equivalent to fit(X, labels).transform(X). build() must be called before fit_transform().

Parameters:

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

Returns:

Name Type Description
coords (ndarray, shape(N, 2))
Source code in src/soumap/soumap.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
def fit_transform(self, X, labels=None):
    """
    Run the SOUMAP learning loop and return embedding coordinates for X.

    Equivalent to fit(X, labels).transform(X). build() must be called
    before fit_transform().

    Parameters
    ----------
    X : np.ndarray, shape (N, d)
    labels : array-like, shape (N,), optional

    Returns
    -------
    coords : np.ndarray, shape (N, 2)
    """
    return self.fit(X, labels=labels).transform(X)

tune_embed_scale

tune_embed_scale(
    rho0_scale=0.5, min_dist0_scale=0.5, min_distf_scale=0.5
)

Calibrate rho_0, min_dist, and spread from a uniform random null embedding.

Motivation

In a classical SOM with a fixed lattice, the output topology has a known, regular geometry — prototype spacing is uniform and predictable, so rho and min_dist can be set intuitively relative to the lattice step size (e.g. rho_0 = 2 lattice steps). In SOUMAP, the output topology is data-driven and changes during learning, so there is no fixed lattice to anchor parameter choices.

This method recovers an equivalent reference scale by simulating what the embedding geometry would look like for M completely unstructured (uniform random) prototypes within the embedding space. This null embedding serves as a maximum-entropy reference — the geometry you would expect in the complete absence of cluster structure. Parameters are then set as fractions of the key geometric quantities in this null embedding, giving them a scale-free, interpretable meaning analogous to the fixed-lattice SOM case.

Null embedding construction

M points are sampled uniformly at random within embedding_range in 2D. Three geometric summaries are computed:

null_max_geo_dist : float Maximum geodesic distance across all connected prototype pairs in the null Delaunay graph, measured in hop counts (number of Delaunay edges traversed). This matches the convention used by GTSOM, which applies rho to unweighted shortest-path distances in embed.dist. Setting rho_0 to half the null hop diameter (rho0_scale=0.5) matches the standard SOM initialization convention of covering roughly half the map with the initial neighbourhood.

null_mean_geo_dist : float Mean hop-count geodesic distance between connected prototype pairs. Computed alongside null_max_geo_dist but not used directly in calibration. Stored in the verbose output for reference.

null_mean_edge_len : float Mean Euclidean length of edges in the null Delaunay triangulation — the typical distance between directly adjacent prototypes in output space. This is the reference scale for min_dist, which is a Euclidean distance threshold in the embedding. Computed directly from edge lengths, independently of the geodesic computation.

Parameter calibration

rho_0 = null_max_geo_dist * rho0_scale min_dist_0 = null_mean_edge_len * min_dist0_scale min_dist_f = null_mean_edge_len * min_distf_scale

spread is set directly from embedding_range (not from the null geometry) because it parameterizes the x-axis scale of the curve fitted by find_ab_params, which must cover the full range of inter-prototype distances in the embedding:

spread = (embedding_range[1] - embedding_range[0]) / 3

The denominator 3 comes from find_ab_params internals: the curve is fitted over [0, spread * 3], so setting spread = diameter / 3 ensures the fitting domain spans [0, diameter] — the full range of possible distances between prototypes. This is independent of the null geometry and is therefore not a scale parameter.

rho_f is not calibrated here — it should remain close to 1.0 (the default). Reducing rho_f toward 0 causes SOM learning to degenerate toward k-means, as prototype updates become independent of their neighbours.

With default scale factors, min_dist_0 == min_dist_f so min_dist does not anneal. Annealing activates only if asymmetric scale factors are provided.

Theoretical alternatives (not yet implemented)

For a uniform distribution of M points in a 2D square of side length L = embedding_range[1] - embedding_range[0], the following closed-form approximations from stochastic geometry could replace the Monte Carlo sampling:

Mean Delaunay edge length (replaces null_mean_edge_len): E[edge_len] ≈ 0.9 * L / sqrt(M) Source: Miles (1970), random Delaunay tessellations.

Mean nearest-neighbour distance: E[d_nn] ≈ L / (2 * sqrt(M)) Source: Clark & Evans (1954).

These would make calibration fully deterministic and free of sampling variability, at the cost of a slight approximation error (typically < 5% for M >= 20). null_mean_geo_dist does not have an equally clean closed form and would still require Monte Carlo or a cruder approximation (null_mean_edge_len * O(sqrt(M))).

Parameters:

Name Type Description Default
rho0_scale float

rho_0 = null_max_geo_dist * rho0_scale. Controls how large the initial SOM neighbourhood is relative to the null lattice diameter. rho0_scale=0.5 covers half the null lattice, matching the standard SOM "half the map" initialization convention.

0.5
min_dist0_scale float

min_dist_0 = null_mean_edge_len * min_dist0_scale.

0.5
min_distf_scale float

min_dist_f = null_mean_edge_len * min_distf_scale. Equal to min_dist0_scale by default, so min_dist does not anneal.

0.5

Returns:

Type Description
self

Returns self to allow chaining: model.tune_embed_scale().build(X).fit(X)

Notes

Annealing schedules for rho, min_dist, and spread are rebuilt after calibration to reflect the new parameter values. Call this method before fit(), not after, to ensure the schedules are correct before training begins.

The Monte Carlo sample is seeded by ctrl_params.random_state for reproducibility. Two runs with the same random_state and M will produce identical calibrated values.

Source code in src/soumap/soumap.py
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
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
739
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
def tune_embed_scale(
    self,
    rho0_scale=0.5,
    min_dist0_scale=0.5,
    min_distf_scale=0.5,
):
    """
    Calibrate rho_0, min_dist, and spread from a uniform random null
    embedding.

    Motivation
    ----------
    In a classical SOM with a fixed lattice, the output topology has a
    known, regular geometry — prototype spacing is uniform and predictable,
    so rho and min_dist can be set intuitively relative to the lattice
    step size (e.g. rho_0 = 2 lattice steps). In SOUMAP, the output
    topology is data-driven and changes during learning, so there is no
    fixed lattice to anchor parameter choices.

    This method recovers an equivalent reference scale by simulating what
    the embedding geometry would look like for M completely unstructured
    (uniform random) prototypes within the embedding space. This null
    embedding serves as a maximum-entropy reference — the geometry you
    would expect in the complete absence of cluster structure. Parameters
    are then set as fractions of the key geometric quantities in this null
    embedding, giving them a scale-free, interpretable meaning analogous
    to the fixed-lattice SOM case.

    Null embedding construction
    ---------------------------
    M points are sampled uniformly at random within embedding_range in
    2D. Three geometric summaries are computed:

    null_max_geo_dist : float
        Maximum geodesic distance across all connected prototype pairs
        in the null Delaunay graph, measured in **hop counts** (number
        of Delaunay edges traversed). This matches the convention used
        by GTSOM, which applies rho to unweighted shortest-path
        distances in embed.dist. Setting rho_0 to half the null hop
        diameter (rho0_scale=0.5) matches the standard SOM
        initialization convention of covering roughly half the map
        with the initial neighbourhood.

    null_mean_geo_dist : float
        Mean hop-count geodesic distance between connected prototype
        pairs. Computed alongside null_max_geo_dist but not used
        directly in calibration. Stored in the verbose output for
        reference.

    null_mean_edge_len : float
        Mean Euclidean length of edges in the null Delaunay
        triangulation — the typical distance between directly adjacent
        prototypes in output space. This is the reference scale for
        min_dist, which is a Euclidean distance threshold in the
        embedding. Computed directly from edge lengths, independently
        of the geodesic computation.

    Parameter calibration
    ---------------------
    rho_0      = null_max_geo_dist  * rho0_scale
    min_dist_0 = null_mean_edge_len * min_dist0_scale
    min_dist_f = null_mean_edge_len * min_distf_scale

    spread is set directly from embedding_range (not from the null
    geometry) because it parameterizes the x-axis scale of the curve
    fitted by find_ab_params, which must cover the full range of
    inter-prototype distances in the embedding:

        spread = (embedding_range[1] - embedding_range[0]) / 3

    The denominator 3 comes from find_ab_params internals: the curve
    is fitted over [0, spread * 3], so setting spread = diameter / 3
    ensures the fitting domain spans [0, diameter] — the full range
    of possible distances between prototypes. This is independent of
    the null geometry and is therefore not a scale parameter.

    rho_f is not calibrated here — it should remain close to 1.0
    (the default). Reducing rho_f toward 0 causes SOM learning to
    degenerate toward k-means, as prototype updates become independent
    of their neighbours.

    With default scale factors, min_dist_0 == min_dist_f so min_dist
    does not anneal. Annealing activates only if asymmetric scale
    factors are provided.

    Theoretical alternatives (not yet implemented)
    ----------------------------------------------
    For a uniform distribution of M points in a 2D square of side
    length L = embedding_range[1] - embedding_range[0], the following
    closed-form approximations from stochastic geometry could replace
    the Monte Carlo sampling:

    Mean Delaunay edge length (replaces null_mean_edge_len):
        E[edge_len] ≈ 0.9 * L / sqrt(M)
        Source: Miles (1970), random Delaunay tessellations.

    Mean nearest-neighbour distance:
        E[d_nn] ≈ L / (2 * sqrt(M))
        Source: Clark & Evans (1954).

    These would make calibration fully deterministic and free of
    sampling variability, at the cost of a slight approximation error
    (typically < 5% for M >= 20). null_mean_geo_dist does not have
    an equally clean closed form and would still require Monte Carlo
    or a cruder approximation (null_mean_edge_len * O(sqrt(M))).

    Parameters
    ----------
    rho0_scale : float, default 0.5
        rho_0 = null_max_geo_dist * rho0_scale. Controls how large
        the initial SOM neighbourhood is relative to the null lattice
        diameter. rho0_scale=0.5 covers half the null lattice,
        matching the standard SOM "half the map" initialization
        convention.
    min_dist0_scale : float, default 0.5
        min_dist_0 = null_mean_edge_len * min_dist0_scale.
    min_distf_scale : float, default 0.5
        min_dist_f = null_mean_edge_len * min_distf_scale. Equal to
        min_dist0_scale by default, so min_dist does not anneal.

    Returns
    -------
    self
        Returns self to allow chaining:
        model.tune_embed_scale().build(X).fit(X)

    Notes
    -----
    Annealing schedules for rho, min_dist, and spread are rebuilt
    after calibration to reflect the new parameter values. Call this
    method before fit(), not after, to ensure the schedules are
    correct before training begins.

    The Monte Carlo sample is seeded by ctrl_params.random_state for
    reproducibility. Two runs with the same random_state and M will
    produce identical calibrated values.
    """
    from scipy.spatial import Delaunay
    from scipy.sparse import csr_matrix
    from scipy.sparse.csgraph import shortest_path

    if self.gtsom is not None:
        raise RuntimeError(
            "tune_embed_scale() must be called before build(). "
            "The GTSOM architecture has already been constructed with "
            "the current parameters."
        )

    rng = np.random.default_rng(self.ctrl_params.random_state)
    lo, hi = self.ctrl_params.embedding_range

    # --- sample M uniform random points in embedding_range ---
    null_coords = rng.uniform(lo, hi, size=(self.M, 2))

    # --- Delaunay triangulation of null embedding ---
    tri = Delaunay(null_coords)

    # Build sparse weighted adjacency from Delaunay simplices.
    # Edge weights are Euclidean distances between prototype pairs.
    edges = set()
    for simplex in tri.simplices:
        for i in range(3):
            for j in range(i + 1, 3):
                a, b = simplex[i], simplex[j]
                edges.add((min(a, b), max(a, b)))

    # Build binary adjacency matrix (edge weights = 1, not Euclidean).
    # Only hop-count geodesics are needed for rho calibration, since
    # GTSOM applies rho to unweighted shortest-path distances in embed.dist.
    rows, cols, data = [], [], []
    for a, b in edges:
        rows += [a, b]
        cols += [b, a]
        data += [1, 1]

    null_adj = csr_matrix((data, (rows, cols)), shape=(self.M, self.M))

    # Unweighted hop-count geodesics — matches GTSOM's embed.dist convention
    geo_dist = shortest_path(null_adj, method='D', directed=False, unweighted=True)

    # null_max_geo_dist: hop-count diameter of null lattice (used for rho_0)
    # null_mean_geo_dist: mean hop-count geodesic (for reference only)
    finite_geo_dists = geo_dist[(geo_dist > 0) & np.isfinite(geo_dist)]
    null_max_geo_dist  = float(finite_geo_dists.max())
    null_mean_geo_dist = float(finite_geo_dists.mean())

    # null_mean_edge_len: mean Euclidean edge length — computed directly
    # from the edge list, independent of shortest_path. Used for min_dist
    # calibration since min_dist is a Euclidean distance in output space.
    null_edges = np.array(list(edges))
    null_edge_lens = np.linalg.norm(
        null_coords[null_edges[:, 0]] - null_coords[null_edges[:, 1]], axis=1
    )
    null_mean_edge_len = float(null_edge_lens.mean())

    # --- calibrate parameters ---
    self.som_params.rho_0       = null_max_geo_dist  * rho0_scale
    self.umap_params.min_dist_0 = null_mean_edge_len * min_dist0_scale
    self.umap_params.min_dist_f = null_mean_edge_len * min_distf_scale

    # spread is derived from embedding_range, not the null geometry.
    # find_ab_params fits its curve over [0, spread * 3], so setting
    # spread = diameter / 3 ensures the domain covers [0, diameter].
    self.umap_params.spread_0 = (hi - lo) / 3
    self.umap_params.spread_f = (hi - lo) / 3

    # --- rebuild UMAP-side annealing schedules to reflect calibrated values ---
    # rho_0 is updated in som_params above and will be picked up by
    # GTSOM.__init__ when _initialize() runs inside fit(). No need to
    # rebuild a rho schedule here since SOUMAP no longer owns one.
    halflife = self.ctrl_params.total_epochs / 2
    self._mindist_sched = self._make_sched(
        self.umap_params.min_dist_0, self.umap_params.min_dist_f, halflife)
    self._spread_sched  = self._make_sched(
        self.umap_params.spread_0,   self.umap_params.spread_f,   halflife)

    if self.ctrl_params.verbose:
        print(
            f"tune_embed_scale: "
            f"null_max_geo_dist={null_max_geo_dist:.4f}, "
            f"null_mean_geo_dist={null_mean_geo_dist:.4f}, "
            f"null_mean_edge_len={null_mean_edge_len:.4f} | "
            f"rho_0={self.som_params.rho_0:.4f}, "
            f"min_dist_0={self.umap_params.min_dist_0:.4f}, "
            f"spread_0={self.umap_params.spread_0:.4f}"
        )

    return self

build

build(X, labels=None)

Construct the SOUMAP architecture from data.

This is the equivalent of GTSOM.from_data() — it constructs the GTSOM instance with the current parameter settings, initializes prototypes via k-means, reduces them to 2D, builds the initial output-space topology, runs the first recall, and takes the initial snapshot (including DR metrics if compute_dr_metrics=True).

Call order:

model = SOUMAP(M=..., som_params=..., umap_params=..., ctrl_params=...)
model.tune_embed_scale()   # optional — override rho_0, min_dist
model.build(X, labels=y)      # construct architecture
model.gtsom.plot(...)         # optional — inspect initial state
model.fit(X, labels=y)        # learning loop

FSIM and PCADJ are not computed here — they are computed at the start of the first UMAP step in fit(), ensuring they reflect the prototypes and recall state at that point.

Parameters:

Name Type Description Default
X (ndarray, shape(N, d))

Data matrix. Used to fit k-means prototypes and run initial recall.

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

Observation labels passed through to GTSOM for prototype-level label summaries and DR metric computation.

None

Raises:

Type Description
RuntimeError

If build() has already been called on this instance.

Source code in src/soumap/soumap.py
791
792
793
794
795
796
797
798
799
800
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
def build(self, X, labels=None):
    """
    Construct the SOUMAP architecture from data.

    This is the equivalent of GTSOM.from_data() — it constructs the
    GTSOM instance with the current parameter settings, initializes
    prototypes via k-means, reduces them to 2D, builds the initial
    output-space topology, runs the first recall, and takes the initial
    snapshot (including DR metrics if compute_dr_metrics=True).

    Call order:

        model = SOUMAP(M=..., som_params=..., umap_params=..., ctrl_params=...)
        model.tune_embed_scale()   # optional — override rho_0, min_dist
        model.build(X, labels=y)      # construct architecture
        model.gtsom.plot(...)         # optional — inspect initial state
        model.fit(X, labels=y)        # learning loop

    FSIM and PCADJ are not computed here — they are computed at the
    start of the first UMAP step in fit(), ensuring they reflect the
    prototypes and recall state at that point.

    Parameters
    ----------
    X : np.ndarray, shape (N, d)
        Data matrix. Used to fit k-means prototypes and run initial
        recall.
    labels : array-like, shape (N,), optional
        Observation labels passed through to GTSOM for prototype-level
        label summaries and DR metric computation.

    Raises
    ------
    RuntimeError
        If build() has already been called on this instance.
    """
    if self.gtsom is not None:
        raise RuntimeError(
            "build() has already been called. To reinitialize, "
            "create a new SOUMAP instance."
        )

    # Construct GTSOM with all learning parameters
    self.gtsom = GTSOM(
        rho_0=self.som_params.rho_0,
        rho_f=self.som_params.rho_f,
        halflife_epochs=self.ctrl_params.total_epochs / 2,
        nbr_topo_alpha_0=self.som_params.nbr_topo_alpha_0,
        nbr_topo_alpha_f=self.som_params.nbr_topo_alpha_f,
        proto_topo=self.som_params.proto_topo,
        compute_dr_metrics=self.som_params.compute_dr_metrics,
        random_state=self.ctrl_params.random_state,
        n_jobs=self.ctrl_params.n_jobs,
    )

    # Initialise topology and prototypes from data
    self.gtsom.from_data(
        X,
        M=self.M,
        coord_init=self.ctrl_params.coord_init,
        coord_topo=self.som_params.coord_topo,
        labels=labels,
    )

    # Scale initial coords (from PCA/LE) into embedding_range.
    # This anchors the coordinate system before any learning begins,
    # giving min_dist and spread an interpretable scale and ensuring
    # the first UMAP warm-start operates in a consistent regime.
    initial_coords = scale_coords(
        self.coords, self.ctrl_params.embedding_range
    )
    self.gtsom.update_embedding(initial_coords)

    self._is_fitted = True
    self.age = 0

    # Regenerate the initial snapshot figure with a SOUMAP-specific
    # title and the post-rescale coordinates. The figure GTSOM auto-
    # generated inside from_data() used its own default title and the
    # pre-rescale coordinates, so it does not accurately represent
    # the true initial state SOUMAP uses going forward.
    color_by = 'labels' if labels is not None else 'rfsize'
    init_fig = self.gtsom.plot(
        color_by=color_by,
        title='SOUMAP',
        subtitle='Initialization (age=0)',
    )
    self.gtsom.learn_history_[0]['fig'] = init_fig

    # Visualize initial state if plotting is enabled.
    if self.ctrl_params.plot_every > 0:
        # plotnine ggplot: draw to matplotlib and display non-blocking
        import matplotlib.pyplot as plt
        init_fig.draw()
        plt.show(block=False)
        plt.pause(0.1)

    return self

Parameter dataclasses

soumap.SOMParams dataclass

SOMParams(
    rho_0: float = 2.0,
    rho_f: float = 1.0,
    nbr_topo_alpha_0: float = 0.5,
    nbr_topo_alpha_f: float = 0.5,
    coord_topo: str = "delaunay",
    proto_topo: str = "CONN",
    compute_dr_metrics: bool = False,
)

Parameters governing SOM prototype learning.

Attributes:

Name Type Description
rho_0 float

Initial neighbourhood bandwidth.

rho_f float

Final neighbourhood bandwidth.

nbr_topo_alpha_0 float

Initial topology-blending weight passed to GTSOM. Controls the mix between Delaunay-lattice-based and CONN-based neighbourhood activations in the SOM update rule:

nbr_W = nbr_topo_alpha * H_lat + (1 - nbr_topo_alpha) * H_CONN

0.0 = pure CONN (Neural Gas style, data-space neighbours). 1.0 = pure lattice (classical SOM). 0.5 = equal blend (default).

nbr_topo_alpha_f float

Final topology-blending weight. Annealing from a low value (CONN-dominant) toward a high value (lattice-dominant) reflects the intuition that early learning should be guided by data-space topology (which is reliable from k-means initialization), while later refinement should respect the evolved embedding topology.

coord_topo str

Adjacency graph used to define the SOM output-space topology. Passed to GTSOM.from_data() as coord_topo.

'delaunay' (default) Delaunay triangulation. Always connected, denser edges, may include long edges across sparsely populated regions. 'gabriel' Gabriel graph (subgraph of Delaunay). Sparser, prunes long bridging edges, may be disconnected for non-uniform prototype distributions.

proto_topo str

Form of the high-dimensional (data-space) neighbourhood used when blending CONN topology into the SOM update rule (i.e. when nbr_topo_alpha < 1). Passed to GTSOM.init().

'CONN' (default) CONN graph geodesics. CONN is treated as an unweighted graph and shortest-path hop counts are fed through the standard exponential neighbourhood kernel. 'CONN_STK' CONN self-tuning kernel. CONN weights are used to compute a locally adaptive radius sigma_i for each prototype, then a Gaussian kernel is applied — no geodesic paths needed. More sensitive to local density variation in the prototype graph.

compute_dr_metrics bool

If True, compute DR quality metrics (trustworthiness, continuity, and related topology-preservation criteria) at each GTSOM snapshot. Metrics are stored in learn_history_ and displayed as a caption on plots. Passed directly to GTSOM.compile(). Adds computational overhead — disable for speed when not needed. Default False.


soumap.UMAPParams dataclass

UMAPParams(
    update_freq: int = 5,
    n_epochs: int = 100,
    min_dist_0: float = 0.01,
    min_dist_f: float = 0.01,
    spread_0: float = 2.0,
    spread_f: float = 2.0,
    lrate_0: float = 1.0,
    lrate_f: float = 0.1,
    negative_sample_rate: int = 5,
    gamma: float = 1.0,
    use_standard_umap: bool = False,
)

Parameters governing UMAP embedding updates.

Attributes:

Name Type Description
update_freq int

Number of SOM epochs between consecutive UMAP embedding updates.

n_epochs int

Number of UMAP layout optimizer epochs per embedding update.

min_dist_0 float

Initial UMAP min_dist parameter.

min_dist_f float

Final UMAP min_dist parameter.

spread_0 float

Initial UMAP spread parameter. Default is 2.0, derived from the default embedding_range (-3, 3) as (hi - lo) / 3 = 6 / 3 = 2.0. This ensures find_ab_params fits its curve over [0, diameter], covering the full range of inter-prototype distances. If you change embedding_range in CtrlParams, call tune_embed_scale() which sets this automatically.

spread_f float

Final UMAP spread parameter. Defaults to spread_0 so spread does not anneal. Set asymmetrically only if you want spread to change over training.

lrate_0 float

Initial UMAP layout optimizer learning rate.

lrate_f float

Final UMAP layout optimizer learning rate.

negative_sample_rate int

Number of negative samples per positive sample in the UMAP layout optimizer.

gamma float

Repulsion strength in the UMAP layout loss. Higher values push non-neighbor prototypes further apart. Default 1.0 is the standard UMAP setting.

use_standard_umap bool

Diagnostic flag. If True, bypasses FSIM entirely and runs a standard UMAP call on the current prototype matrix W at each embedding update step, using UMAP's own kNN similarity graph (default n_neighbors=15) warm-started from current coords. Useful for isolating whether cluster quality issues stem from FSIM construction or from the SOM step itself. Default False.


soumap.CtrlParams dataclass

CtrlParams(
    total_epochs: int = 100,
    min_nhbs: int = 3,
    fill_val: float = 0.5,
    coord_init: str = "pca",
    embedding_range: tuple = (-3.0, 3.0),
    n_jobs: int = None,
    random_state: int = None,
    verbose: bool = True,
    plot_every: int = 0,
)

Parameters governing training control and initialization.

Attributes:

Name Type Description
total_epochs int

Total number of SOM epochs to run. Controls parameter annealing: all schedules decay from initial to final value over this many epochs (halflife at total_epochs / 2).

min_nhbs int

Minimum number of neighbors required per row in PCADJ before similarity construction. Rows below this are padded with synthetic edges.

fill_val float

Edge weight for synthetic PCADJ padding edges.

coord_init str

Method for initializing embedding coordinates from prototypes W. Options: 'pca', 'le', 'random'. Passed to GTSOM.from_data().

embedding_range tuple of float

Target coordinate range for each axis of the embedding. After each UMAP update, coordinates are rescaled to fit within this range via scale_coords(). Also used by tune_embed_scale() to derive spread = (hi - lo) / 3.

n_jobs int or None

Number of parallel jobs. Passed to GTSOM (numba parallelism for prototype updates) and converted to a boolean for the UMAP layout optimizer (parallel=True if n_jobs != 1). Set to 1 for fully sequential execution (enables reproducibility). None uses all available cores.

random_state int or None

Random seed for reproducibility. Note: parallel execution (n_jobs != 1) in the UMAP optimizer uses fresh random samples each call regardless of random_state. Set n_jobs=1 for fully deterministic UMAP steps.

verbose bool

If True, print progress during fit().

plot_every int

Plot the SOM embedding every this many UMAP update steps. Set to 0 to disable in-training plotting. The initialization state is always plotted if plot_every > 0.


MPEC

soumap.MPEClustering

MPEClustering(
    walktrap_n_steps: int | str = "auto",
    kernel_w_cadj: float = 1.0,
    kernel_w_high_d: float = 1.0,
    kernel_w_low_d: float = 1.0,
    kernel_power: float = 2.0,
    kernel_min_value: float = 0.01,
    remove_empty_protos: bool = True,
    kernel_min_nhbs: int = 3,
    kernel_support: str = "dense",
    walktrap_max_steps: int = 15,
    verbose: bool = False,
)

Multiview Prototype Embedding & Clustering.

Fuses a CADJ-topology view, a high-D Euclidean view, and a low-D Euclidean view of prototype space into a single weighted graph, then partitions it with the Walktrap community-detection algorithm.

Parameters:

Name Type Description Default
walktrap_n_steps int or 'auto'

Number of random-walk steps for the Walktrap algorithm. If "auto", the optimal step count is found automatically by analysing the tradeoff between Markov-chain transience and cluster cohesion (see :func:_find_walktrap_steps).

"auto"
kernel_w_cadj float

Fusion weight applied to the CADJ view.

1.0
kernel_w_high_d float

Fusion weight applied to the high-D Euclidean kernel view.

1.0
kernel_w_low_d float

Fusion weight applied to the low-D Euclidean kernel view.

1.0
kernel_power float

Exponent applied to each kernel view before fusion. Values > 1 sharpen inter-view agreement: pairs that are similar in all views receive disproportionately stronger edges, while disagreements are suppressed. Motivated by the kernel combination results of Cortes, Mohri & Rostamizadeh (NeurIPS 2009).

2.0
kernel_min_value float

Hard lower bound on kernel values retained after sparsification in :func:CADJ_self_tuning_kernel. Passed through to both Euclidean kernel calls.

0.01
remove_empty_protos bool

If True, prototypes with empty receptive fields (no data mapped to them during VQ recall, i.e. zero CADJ row sums) are excluded from clustering. Their entries in labels_ are set to -1.

True
kernel_min_nhbs int

Minimum number of neighbours guaranteed per prototype. Does double duty: passed to :func:CADJ_self_tuning_kernel as min_nhbs, where it controls (a) internal padding used only for sigma/ connectivity computation in the Euclidean views, and (b) the per-row minimum kept after sparsification. Does not pad kernel_cadj_ itself — see kernel_support and the Step 2 comment in :meth:fit for why CADJ's own density signal is left untouched.

3
kernel_support ('dense', 'CADJ')

Sparsity pattern used when building the high-D and low-D Euclidean kernel views (kernel_high_d_, kernel_low_d_) via :func:CADJ_self_tuning_kernel. Does not affect kernel_cadj_, which is always derived directly from (unpadded) CADJ.

"dense" (default): kernel evaluated for all M×M prototype pairs. Allows the Euclidean views to introduce edges that CADJ did not encode — the intended behavior for multi-view fusion, since each view should be able to contribute independent structural information.

"CADJ": kernel evaluated only for pairs where CADJ[i,j] > 0. Cheaper for large M, but the Euclidean views become topologically redundant with the CADJ view (they reuse its sparsity pattern, only contributing different edge weights). Useful for experimentation or when M is large enough that the dense pairwise computation becomes a bottleneck.

"dense"
walktrap_max_steps int

Number of steps evaluated when walktrap_n_steps="auto". The tradeoff curve is computed at every step from 1 to this value and the first crossing point is returned.

15
verbose bool

If True, print progress messages and warnings during :meth:fit. Useful for monitoring long-running fits or diagnosing unexpected results (e.g. many empty prototypes, fragmented graph, step count hitting the maximum).

False

Attributes:

Name Type Description
labels_ np.ndarray, shape (M,), dtype int

Cluster membership for each prototype (0-indexed). Empty prototypes (excluded when remove_empty_protos=True) are assigned the sentinel value -1. This follows the sklearn convention for excluded or unclustered points and keeps the array in integer dtype (numpy integer arrays have no NaN representation). Use labels_[labels_ >= 0] or the active_labels_ property to access only the clustered labels.

active_labels_ np.ndarray, shape (M_active,), dtype int

Cluster labels for active (non-empty) prototypes only — equivalent to labels_[active_indices_]. No -1 sentinels. Convenience accessor for downstream code that operates on the clustered subset.

active_indices_ np.ndarray, shape (M_active,), dtype int

Indices into the full prototype array of the prototypes that were actually clustered (i.e. the non-empty ones).

rf_sizes_ np.ndarray, shape (M_active,), dtype float

Receptive field sizes for active prototypes — CADJ row sums of the active sub-matrix. Reflects how many data points each prototype attracted as first BMU. Useful as point-size weights in visualisation.

fused_graph_ (csr_matrix, shape(M_active, M_active))

Symmetric weighted adjacency matrix of the fused graph, defined over the active (non-empty) prototypes only.

n_steps_ int

Walktrap step count actually used.

walktrap_result_ VertexClustering

Walktrap clustering result. Gives access to modularity, membership, and cluster sizes.

walktrap_dendrogram_ VertexDendrogram

Raw Walktrap dendrogram before the optimal cut. Use walktrap_dendrogram_.as_clustering(k) to cut at any number of clusters k, or extract the full modularity curve across all k.

step_analysis_ list of dict or None

Per-communicating-class tradeoff analysis from :func:_find_walktrap_steps. Each dict contains mixing, cohesion, hd_norm, cc_norm, best_step, size, walk_lengths, and indices keys. None if walktrap_n_steps was supplied manually.

kernel_cadj_ (csr_matrix, shape(M_active, M_active))

Row-max-normalised CADJ view kernel (before fusion and power). Values in [0, 1].

kernel_high_d_ (csr_matrix, shape(M_active, M_active))

Self-tuning Euclidean kernel on W (high-D view, before fusion and power). Values in (0, 1].

kernel_low_d_ (csr_matrix, shape(M_active, M_active))

Self-tuning Euclidean kernel on Y (low-D view, before fusion and power). Values in (0, 1].

Source code in src/soumap/mpec.py
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
522
523
524
525
526
527
528
def __init__(
    self,
    walktrap_n_steps: int | str = "auto",
    kernel_w_cadj: float = 1.0,
    kernel_w_high_d: float = 1.0,
    kernel_w_low_d: float = 1.0,
    kernel_power: float = 2.0,
    kernel_min_value: float = 0.01,
    remove_empty_protos: bool = True,
    kernel_min_nhbs: int = 3,
    kernel_support: str = "dense",
    walktrap_max_steps: int = 15,
    verbose: bool = False,
) -> None:
    if walktrap_n_steps != "auto" and (
        not isinstance(walktrap_n_steps, int) or walktrap_n_steps < 1
    ):
        raise ValueError(
            "walktrap_n_steps must be a positive integer or 'auto'; "
            f"got {walktrap_n_steps!r}"
        )
    if not (kernel_w_cadj >= 0 and kernel_w_high_d >= 0 and kernel_w_low_d >= 0):
        raise ValueError("Kernel fusion weights must be non-negative.")
    if (kernel_w_cadj + kernel_w_high_d + kernel_w_low_d) == 0:
        raise ValueError("At least one kernel fusion weight must be positive.")
    if kernel_support not in ("dense", "CADJ"):
        raise ValueError(
            f"kernel_support must be 'dense' or 'CADJ'; got {kernel_support!r}"
        )

    self.walktrap_n_steps = walktrap_n_steps
    self.kernel_w_cadj = kernel_w_cadj
    self.kernel_w_high_d = kernel_w_high_d
    self.kernel_w_low_d = kernel_w_low_d
    self.kernel_power = kernel_power
    self.kernel_min_value = kernel_min_value
    self.remove_empty_protos = remove_empty_protos
    self.kernel_min_nhbs = kernel_min_nhbs
    self.kernel_support = kernel_support
    self.walktrap_max_steps = walktrap_max_steps
    self.verbose = verbose

    # Results — populated by fit()
    # Clustering outputs
    self.labels_: np.ndarray | None = None
    self.active_indices_: np.ndarray | None = None
    self.rf_sizes_: np.ndarray | None = None
    # Graph and Walktrap
    self.fused_graph_: sp.csr_matrix | None = None
    self.n_steps_: int | None = None
    self.walktrap_result_: igraph.VertexClustering | None = None
    self.walktrap_dendrogram_: object | None = None  # igraph VertexDendrogram
    self.step_analysis_: list[dict] | None = None
    # Per-view kernels (before fusion; useful for diagnostics)
    self.kernel_cadj_: sp.csr_matrix | None = None
    self.kernel_high_d_: sp.csr_matrix | None = None
    self.kernel_low_d_: sp.csr_matrix | None = None

active_labels_ property

active_labels_: ndarray

Cluster labels for active (non-empty) prototypes only.

Equivalent to labels_[active_indices_]. Contains no -1 sentinels — every entry is a valid cluster index (0-indexed). Raises RuntimeError if called before :meth:fit.

fit

fit(
    W: ndarray,
    Y: ndarray,
    CADJ: spmatrix,
    CADJ_nhbs: list[list[int]] | None = None,
) -> "MPEClustering"

Fit the multiview prototype clustering.

Parameters:

Name Type Description Default
W (ndarray, shape(M, d))

Prototype matrix in the original (high-D) feature space.

required
Y (ndarray, shape(M, d2))

Low-D embedding of the prototypes (e.g. UMAP or PCA coordinates).

required
CADJ scipy.sparse matrix, shape (M, M)

Asymmetric co-adjacency matrix from VQRecaller.

required
CADJ_nhbs list of list of int, length M

Precomputed CADJ neighbour index lists. Derived from CADJ's CSR structure if not supplied.

None

Returns:

Name Type Description
self MPEClustering

The fitted instance. Results are available as instance attributes.

Source code in src/soumap/mpec.py
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
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
739
740
741
742
743
def fit(
    self,
    W: np.ndarray,
    Y: np.ndarray,
    CADJ: sp.spmatrix,
    CADJ_nhbs: list[list[int]] | None = None,
) -> "MPEClustering":
    """
    Fit the multiview prototype clustering.

    Parameters
    ----------
    W : np.ndarray, shape (M, d)
        Prototype matrix in the original (high-D) feature space.
    Y : np.ndarray, shape (M, d2)
        Low-D embedding of the prototypes (e.g. UMAP or PCA coordinates).
    CADJ : scipy.sparse matrix, shape (M, M)
        Asymmetric co-adjacency matrix from VQRecaller.
    CADJ_nhbs : list of list of int, length M, optional
        Precomputed CADJ neighbour index lists.  Derived from CADJ's CSR
        structure if not supplied.

    Returns
    -------
    self : MPEClustering
        The fitted instance.  Results are available as instance attributes.
    """
    M = W.shape[0]
    if Y.shape[0] != M or CADJ.shape != (M, M):
        raise ValueError(
            f"W, Y, and CADJ must all have M={M} prototypes; "
            f"got Y.shape={Y.shape}, CADJ.shape={CADJ.shape}"
        )

    self._vprint(f"Starting fit: M={M} prototypes, W.shape={W.shape}, Y.shape={Y.shape}")

    # --- Step 1: identify and optionally remove empty prototypes ----------
    # A prototype is "empty" if its CADJ row sum is zero — no data point
    # ever had it as first BMU, so its receptive field is empty.
    # rf_sizes[i] = CADJ row sum = total co-mapping events from prototype i.
    rf_sizes = np.asarray(CADJ.sum(axis=1)).ravel()  # shape (M,)
    is_empty = rf_sizes == 0
    n_empty = int(is_empty.sum())

    if n_empty > 0:
        self._vprint(
            f"Found {n_empty}/{M} empty prototypes "
            f"({100 * n_empty / M:.1f}%).",
            warning=n_empty > 0.1 * M,  # warn if >10% are empty
        )
    else:
        self._vprint("No empty prototypes found.")

    if self.remove_empty_protos and is_empty.any():
        active_indices = np.where(~is_empty)[0]
    else:
        active_indices = np.arange(M)

    M_active = len(active_indices)
    self._vprint(f"Clustering {M_active} active prototypes.")

    W_active = W[active_indices]
    Y_active = Y[active_indices]
    CADJ_active = CADJ[np.ix_(active_indices, active_indices)].tocsr()

    # Derive neighbour lists for the active sub-matrix
    CADJ_active_nhbs = [
        list(CADJ_active.indices[
            CADJ_active.indptr[i]:CADJ_active.indptr[i + 1]
        ])
        for i in range(M_active)
    ]
    CADJ_active_nhbs_size = np.diff(CADJ_active.indptr).astype(int)

    n_under = int((CADJ_active_nhbs_size < self.kernel_min_nhbs).sum())
    if n_under > 0:
        self._vprint(
            f"{n_under} prototype(s) have fewer than "
            f"{self.kernel_min_nhbs} CADJ neighbours after subsetting. "
            f"CADJ_self_tuning_kernel will pad internally for the "
            f"Euclidean views; kernel_cadj_ is left unpadded so genuine "
            f"low-density rows remain visible in the fused graph.",
            warning=n_under > 0.1 * M_active,
        )

    # --- Step 2: build kernel views ---------------------------------------
    # CADJ is passed unpadded here. CADJ_self_tuning_kernel pads internally
    # (as needed) to compute well-defined sigmas and guarantee minimum
    # connectivity for the Euclidean views — but that padding stays
    # internal to the kernel function and never touches kernel_cadj_
    # (built below from CADJ_active directly). This preserves CADJ's
    # density signal: a genuinely sparse/empty CADJ row honestly reflects
    # low data support for that prototype, and the Euclidean views already
    # guarantee baseline connectivity for the fused graph as a whole.
    #
    # kernel_support controls the sparsity pattern of the Euclidean
    # views: "dense" (default) lets them introduce edges that CADJ did
    # not encode, which is the intended behavior for multi-view fusion.
    # "CADJ" restricts them to CADJ's existing topology — cheaper but
    # more redundant with the CADJ view. See class docstring.
    self._vprint("Building high-D Euclidean kernel view...")
    K_W = CADJ_self_tuning_kernel(
        W=W_active,
        CADJ=CADJ_active,
        CADJ_nhbs=CADJ_active_nhbs,
        CADJ_nhbs_size=CADJ_active_nhbs_size,
        min_similarity=self.kernel_min_value,
        min_nhbs=self.kernel_min_nhbs,
        support=self.kernel_support,
    )
    self.kernel_high_d_ = K_W

    self._vprint("Building low-D Euclidean kernel view...")
    K_Y = CADJ_self_tuning_kernel(
        W=Y_active,
        CADJ=CADJ_active,
        CADJ_nhbs=CADJ_active_nhbs,
        CADJ_nhbs_size=CADJ_active_nhbs_size,
        min_similarity=self.kernel_min_value,
        min_nhbs=self.kernel_min_nhbs,
        support=self.kernel_support,
    )
    self.kernel_low_d_ = K_Y

    # --- Step 3: fuse views into a single graph -------------------------
    self._vprint("Fusing views into weighted graph...")
    # CADJ view: scale each row by its own max value, so the row's
    # strongest co-mapping becomes 1.0 and all others are in [0, 1).
    # This bounds CADJ_norm to the same [0, 1] range as the two
    # Euclidean kernels (K_W, K_Y) regardless of CADJ's raw count
    # magnitudes, so kernel_w_* weights are comparable across views.
    # Rows with zero density stay all-zero — no synthetic padding is
    # applied here (see Step 2 comment above).
    CADJ_float = CADJ_active.astype(np.float64)
    row_maxes = np.asarray(CADJ_float.max(axis=1).todense()).ravel()
    row_maxes[row_maxes == 0] = 1.0  # guard div-by-zero; row stays all-zero
    CADJ_norm = CADJ_float.multiply(1.0 / row_maxes[:, None])
    self.kernel_cadj_ = CADJ_norm.tocsr()

    A = (
        self.kernel_w_cadj   * CADJ_norm.power(self.kernel_power)
        + self.kernel_w_high_d * K_W.power(self.kernel_power)
        + self.kernel_w_low_d  * K_Y.power(self.kernel_power)
    )

    # Symmetrise: A + A^T makes the graph undirected
    A = A + A.T
    A = A.tocsr()
    self._vprint(
        f"Fused graph: {M_active} vertices, {A.nnz // 2} edges "
        f"(density={A.nnz / M_active**2:.3f})."
    )

    # --- Step 4: find optimal Walktrap steps if requested ---------------
    if self.walktrap_n_steps == "auto":
        self._vprint("Finding optimal Walktrap step count...")
        # Row sums of original (un-padded) CADJ as vertex weights
        cadj_row_sums = np.asarray(
            CADJ_active.sum(axis=1)
        ).ravel().astype(np.float64)
        n_steps, step_analysis = _find_walktrap_steps(
            A=A,
            row_weights=cadj_row_sums,
            max_steps=self.walktrap_max_steps,
            verbose=self.verbose,
        )
        self.step_analysis_ = step_analysis
        self._vprint(f"Selected n_steps={n_steps}.")
    else:
        n_steps = self.walktrap_n_steps
        self.step_analysis_ = None
        self._vprint(f"Using user-supplied n_steps={n_steps}.")

    # --- Step 6: build igraph object and run Walktrap -------------------
    self._vprint(f"Running Walktrap (steps={n_steps})...")
    A_coo = sp.triu(A, k=1).tocoo()
    g = igraph.Graph(
        n=M_active,
        edges=list(zip(A_coo.row.tolist(), A_coo.col.tolist())),
        edge_attrs={"weight": A_coo.data.tolist()},
        directed=False,
    )
    wt = g.community_walktrap(weights="weight", steps=n_steps)
    wt_clustering = wt.as_clustering()
    membership = np.asarray(wt_clustering.membership, dtype=int)
    n_clusters = int(membership.max()) + 1
    self._vprint(f"Walktrap complete: {n_clusters} clusters found.")

    # --- Step 7: store results ------------------------------------------
    labels = np.full(M, -1, dtype=int)  # -1 sentinel for empty protos
    labels[active_indices] = membership

    # Clustering outputs
    self.labels_ = labels
    self.active_indices_ = active_indices
    self.rf_sizes_ = np.asarray(CADJ_active.sum(axis=1)).ravel().astype(np.float64)

    # Graph and Walktrap
    self.fused_graph_ = A
    self.n_steps_ = n_steps
    self.walktrap_result_ = wt_clustering
    self.walktrap_dendrogram_ = wt  # raw VertexDendrogram for modularity curve

    self._vprint(
        f"Done. {n_clusters} clusters over {M_active} active prototypes "
        f"({n_empty} empty, labelled -1)."
    )
    return self

save

save(path: str) -> None

Save this fitted MPEClustering instance to an HDF5 file.

All parameters, clustering results, kernel matrices, and step analysis are serialized. igraph objects (walktrap_result_, walktrap_dendrogram_) are not stored but are recomputed identically from fused_graph_ and n_steps_ on :meth:load — Walktrap is deterministic.

Parameters:

Name Type Description Default
path str

Destination file path. Created or overwritten.

required

Examples:

>>> mpec.fit(W, Y, CADJ)
>>> mpec.save("mpec.h5")
>>> mpec2 = MPEClustering.load("mpec.h5")
>>> mpec2.plot_diagnostics(embed_coords=Y)
Source code in src/soumap/mpec.py
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
def save(self, path: str) -> None:
    """
    Save this fitted MPEClustering instance to an HDF5 file.

    All parameters, clustering results, kernel matrices, and step
    analysis are serialized.  igraph objects (walktrap_result_,
    walktrap_dendrogram_) are not stored but are recomputed identically
    from fused_graph_ and n_steps_ on :meth:`load` — Walktrap is
    deterministic.

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

    Examples
    --------
    >>> mpec.fit(W, Y, CADJ)
    >>> mpec.save("mpec.h5")
    >>> mpec2 = MPEClustering.load("mpec.h5")
    >>> mpec2.plot_diagnostics(embed_coords=Y)
    """
    from soumap.io import MPECio
    MPECio(self).save(path)

load classmethod

load(path: str) -> 'MPEClustering'

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

All parameters and results are restored. walktrap_result_ and walktrap_dendrogram_ are recomputed from the saved fused_graph_ and n_steps_ (Walktrap is deterministic — results are identical).

Parameters:

Name Type Description Default
path str

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

required

Returns:

Type Description
MPEClustering

Fully reconstructed instance with all plot and diagnostic functionality available immediately.

Examples:

>>> mpec = MPEClustering.load("mpec.h5")
>>> mpec.n_steps_
4
>>> mpec.plot_diagnostics(embed_coords=Y)
Source code in src/soumap/mpec.py
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
@classmethod
def load(cls, path: str) -> "MPEClustering":
    """
    Load a MPEClustering from an HDF5 file created by :meth:`save`.

    All parameters and results are restored.  walktrap_result_ and
    walktrap_dendrogram_ are recomputed from the saved fused_graph_
    and n_steps_ (Walktrap is deterministic — results are identical).

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

    Returns
    -------
    MPEClustering
        Fully reconstructed instance with all plot and diagnostic
        functionality available immediately.

    Examples
    --------
    >>> mpec = MPEClustering.load("mpec.h5")
    >>> mpec.n_steps_
    4
    >>> mpec.plot_diagnostics(embed_coords=Y)
    """
    from soumap.io import MPECio
    return MPECio.load(path)

plot_diagnostics

plot_diagnostics(
    embed_coords: ndarray | None = None,
    show_graph: bool = False,
    which: list | str = "all",
    max_components: int = 3,
    point_size: float = 2.0,
    figsize: tuple = (6, 5),
    save_dir: str | None = None,
    save_format: str = "pdf",
) -> dict

Produce diagnostic plots for the fitted clustering.

Each plot is rendered independently as a separate figure, displayed on screen, and optionally saved to disk. This avoids any dependency on panel-assembly libraries (e.g. patchworklib) and works with any plotnine version.

Parameters:

Name Type Description Default
embed_coords (ndarray, shape(M, d))

Coordinates for the embedding scatter. First 2 columns are used if d > 2. If None, the embedding plot is skipped.

None
show_graph bool

If True, overlay fused_graph_ edges on the embedding scatter.

False
which list of str or "all"

Subset of plots to produce. Valid names:

"step_tradeoff" — mixing / cohesion / score vs. step. "edge_distributions" — kernel edge weight distributions. "modularity" — Walktrap modularity curve. "cluster_sizes" — cluster size bar chart. "embedding" — prototype embedding scatter. "view_agreement" — kernel view agreement heatmap.

"all"
max_components int

Maximum number of communicating classes shown in the step tradeoff plot.

3
point_size float

Base point size for the embedding scatter.

2.0
figsize tuple

(width, height) in inches for each individual figure.

(6, 5)
save_dir str or None

Directory in which to save figures. If None, figures are shown on screen only. Files are named mpec_<plot_name>.<save_format>.

None
save_format str

File format passed to plotnine's save() method. Any format supported by matplotlib is valid (e.g. "pdf", "svg", "png").

"pdf"

Returns:

Name Type Description
plots dict

{name: ggplot} for every plot that was produced. Allows the caller to further customise or save individual plots.

Source code in src/soumap/mpec.py
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
def plot_diagnostics(
    self,
    embed_coords: np.ndarray | None = None,
    show_graph: bool = False,
    which: list | str = "all",
    max_components: int = 3,
    point_size: float = 2.0,
    figsize: tuple = (6, 5),
    save_dir: str | None = None,
    save_format: str = "pdf",
) -> dict:
    """
    Produce diagnostic plots for the fitted clustering.

    Each plot is rendered independently as a separate figure, displayed
    on screen, and optionally saved to disk.  This avoids any dependency
    on panel-assembly libraries (e.g. patchworklib) and works with any
    plotnine version.

    Parameters
    ----------
    embed_coords : np.ndarray, shape (M, d), optional
        Coordinates for the embedding scatter.  First 2 columns are used
        if d > 2.  If None, the embedding plot is skipped.
    show_graph : bool, default False
        If True, overlay ``fused_graph_`` edges on the embedding scatter.
    which : list of str or "all", default "all"
        Subset of plots to produce.  Valid names:

        ``"step_tradeoff"``    — mixing / cohesion / score vs. step.
        ``"edge_distributions"`` — kernel edge weight distributions.
        ``"modularity"``       — Walktrap modularity curve.
        ``"cluster_sizes"``    — cluster size bar chart.
        ``"embedding"``        — prototype embedding scatter.
        ``"view_agreement"``   — kernel view agreement heatmap.

    max_components : int, default 3
        Maximum number of communicating classes shown in the step
        tradeoff plot.
    point_size : float, default 2.0
        Base point size for the embedding scatter.
    figsize : tuple, default (6, 5)
        (width, height) in inches for each individual figure.
    save_dir : str or None
        Directory in which to save figures.  If None, figures are shown
        on screen only.  Files are named
        ``mpec_<plot_name>.<save_format>``.
    save_format : str, default "pdf"
        File format passed to plotnine's ``save()`` method.  Any format
        supported by matplotlib is valid (e.g. ``"pdf"``, ``"svg"``,
        ``"png"``).

    Returns
    -------
    plots : dict
        ``{name: ggplot}`` for every plot that was produced.  Allows
        the caller to further customise or save individual plots.
    """
    self._check_fitted("plot_diagnostics()")

    all_names = [
        "step_tradeoff", "edge_distributions", "modularity",
        "cluster_sizes", "embedding", "view_agreement",
    ]
    if which == "all":
        which = list(all_names)
    invalid = set(which) - set(all_names)
    if invalid:
        raise ValueError(
            f"Unknown plot name(s): {invalid}. "
            f"Valid options: {all_names}"
        )

    # Skip embedding if no coords supplied (rather than placeholder)
    if embed_coords is None and "embedding" in which:
        print("[MPEClustering] embed_coords not supplied — skipping embedding plot.")
        which = [n for n in which if n != "embedding"]

    # Build shared color table so all plots use consistent cluster colors
    active_labels_str = [str(lb) for lb in self.active_labels_]
    ctab = build_ctab(active_labels_str)

    plot_map = {
        "step_tradeoff":      lambda: self._plot_step_tradeoff(max_components),
        "edge_distributions": lambda: self._plot_edge_distributions(),
        "modularity":         lambda: self._plot_modularity_curve(),
        "cluster_sizes":      lambda: self._plot_cluster_sizes(ctab),
        "embedding":          lambda: self._plot_embedding(
                                  embed_coords, ctab, show_graph, point_size),
        "view_agreement":     lambda: self._plot_view_agreement(),
    }

    plots = {}
    for name in all_names:
        if name not in which:
            continue

        self._vprint(f"Rendering: {name}...")
        gg = plot_map[name]()
        plots[name] = gg

        if save_dir is not None:
            import os
            path = os.path.join(save_dir, f"mpec_{name}.{save_format}")
            gg.save(path, width=figsize[0], height=figsize[1], verbose=False)
            self._vprint(f"  Saved: {path}")

        # Show on screen
        gg.draw()
        plt.show()

    return plots