universalmotif 0.4.0

Sequence motif types, conversions and analysis, following the universalmotif R package
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
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
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
230
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
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
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
644
645
646
647
648
649
650
651
652
653
//! Merging motifs with [`merge_motifs`] and [`merge_similar`].
//!
//! Gaps are not used: gapped motifs are aligned with their columns running
//! together, and merged motifs have no gaps.

use crate::alphabet::Alphabet;
use crate::cluster::{Linkage, hclust};
use crate::compare::{CompareOptions, NullModel, align, compare_matrix};
use crate::convert::convert_type;
use crate::create::{CreateOptions, from_typed_matrix};
use crate::error::{Result, arg_err};
use crate::matrix::Matrix;
use crate::motif::{Motif, MotifType, Strand};
use crate::similarity::{CwmCompareOptions, CwmMetric, align_cwm_pair, cwm_similarity_matrix};

/// Options for [`merge_motifs`].
#[derive(Debug, Clone, PartialEq)]
pub struct MergeOptions {
    /// Fewest overlapping columns for a motif to be aligned to the anchor,
    /// lowered to the width of the narrower motif when needed; 5 by default,
    /// where trees use 6.
    pub min_overlap: usize,
    /// Allow motifs to be reverse complemented to fit the anchor.
    pub rc: bool,
    /// Name of the merged motif; by default `merged_` followed by the names
    /// of the motifs used, joined by `+`.
    pub name: Option<String>,
    /// Weight each motif by its `nsites` when averaging.
    pub weighted: bool,
    /// Threads to use; 0 means all available.
    pub nthreads: usize,
}

impl Default for MergeOptions {
    fn default() -> Self {
        MergeOptions {
            min_overlap: 5,
            rc: true,
            name: None,
            weighted: false,
            nthreads: 1,
        }
    }
}

fn shared_alphabet(motifs: &[Motif]) -> Result<Alphabet> {
    let Some(first) = motifs.first() else {
        return arg_err("no motifs given");
    };
    if motifs.iter().any(|m| m.alphabet != first.alphabet) {
        return arg_err("all motifs must share the same alphabet");
    }
    Ok(first.alphabet.clone())
}

/// Merge motifs into one.
///
/// The motif with the highest total IC is the anchor. Every other motif is
/// aligned to it as [`crate::compare::compare_motifs`] aligns motifs and, for
/// DNA and RNA, reverse complemented if that fits better, and the aligned probabilities are averaged
/// position by position. Positions covered by no motif are uniform. The result
/// is a PPM whose `nsites` is the sum of the motifs', counting 1 for motifs
/// without one, with the average background and the anchor's pseudocount.
///
/// When every motif is a CWM, the result is a CWM instead: the anchor is the
/// motif with the largest total contribution, motifs are aligned to it by
/// the cosine of [`crate::similarity`], keeping their sign, and the aligned
/// contributions are averaged, with positions covered by no motif left at 0.
///
/// # Example
///
/// ```
/// use universalmotif::create::{CreateOptions, from_strings};
/// use universalmotif::merge::{MergeOptions, merge_motifs};
///
/// let opts = CreateOptions { nsites: Some(20.0), pseudocount: 1.0, ..Default::default() };
/// let a = from_strings(&["TGACTCA"], None, &opts)?;
/// let b = from_strings(&["ATGAGTCAT"], None, &opts)?;
/// let merged = merge_motifs(&[a, b], &MergeOptions::default())?;
/// assert_eq!(merged.width(), 9);
/// # Ok::<(), universalmotif::Error>(())
/// ```
pub fn merge_motifs(motifs: &[Motif], opts: &MergeOptions) -> Result<Motif> {
    merge_motifs_detailed(motifs, opts).map(|m| m.motif)
}

/// A merged motif and the motifs that went into it, from
/// [`merge_motifs_detailed`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct MergedMotif {
    /// The merged motif.
    pub motif: Motif,
    /// Indices of the motifs that went into the merge; any others could not
    /// be aligned to the anchor.
    pub used: Vec<usize>,
}

/// [`merge_motifs`], also reporting which motifs went into the merge.
pub fn merge_motifs_detailed(motifs: &[Motif], opts: &MergeOptions) -> Result<MergedMotif> {
    let alphabet = shared_alphabet(motifs)?;
    if motifs.iter().all(|m| m.motif_type == MotifType::Cwm) {
        return merge_cwms(motifs, alphabet, opts);
    }
    let nl = alphabet.len();
    if motifs.len() == 1 {
        let mut p = convert_type(&motifs[0], MotifType::Ppm, None, false)?.into_parts();
        if let Some(n) = &opts.name {
            p.name = n.clone();
        }
        return Ok(MergedMotif {
            motif: Motif::from_parts(p)?,
            used: vec![0],
        });
    }
    let ppms: Vec<Motif> = motifs
        .iter()
        .map(|m| convert_type(m, MotifType::Ppm, None, false))
        .collect::<Result<_>>()?;
    let nsites: Vec<f64> = ppms
        .iter()
        .map(|m| m.nsites.filter(|n| *n > 0.0).unwrap_or(1.0))
        .collect();
    let ic: Vec<f64> = ppms.iter().map(|m| m.icscore).collect();
    // The first motif with the most IC, so that rounding cannot hand the
    // anchor to a later motif with the same IC, such as a reverse complement.
    let mut anchor = 0;
    for (i, &v) in ic.iter().enumerate().skip(1) {
        if v > ic[anchor] + 1e-9 * ic[anchor].abs().max(1.0) {
            anchor = i;
        }
    }

    let pairs: Vec<(usize, usize)> = (0..ppms.len()).map(|i| (anchor, i)).collect();
    let copts = CompareOptions {
        min_overlap: opts.min_overlap,
        rc: opts.rc,
        nthreads: opts.nthreads,
        ..Default::default()
    };
    let al = align(&ppms, &pairs, &copts)?;
    let w_anchor = ppms[anchor].width() as i64;

    let mut used: Vec<(usize, Matrix, i64)> = Vec::new();
    for (i, m) in ppms.iter().enumerate() {
        if i == anchor {
            used.push((i, m.matrix.clone(), 0));
            continue;
        }
        let a = &al[i];
        let len = a.overlap as i64;
        // The alignment lowers min_overlap to the narrower motif's width, and
        // so must this check, or narrow motifs would always be left out.
        if a.overlap < opts.min_overlap.min(m.width()).min(ppms[anchor].width()) {
            continue;
        }
        let t_start = (-a.offset).max(0);
        let w = m.width() as i64;
        if a.strand == Strand::Minus {
            let q_start = w_anchor - a.query_start as i64 - len;
            let t_start_oriented = w - t_start - len;
            used.push((i, m.matrix.reversed(), q_start - t_start_oriented));
        } else {
            used.push((i, m.matrix.clone(), a.query_start as i64 - t_start));
        }
    }

    let lo = used.iter().map(|u| u.2).min().unwrap();
    let hi = used.iter().map(|u| u.2 + u.1.ncol() as i64).max().unwrap();
    let width = (hi - lo) as usize;
    let weights: Vec<f64> = used
        .iter()
        .map(|u| if opts.weighted { nsites[u.0] } else { 1.0 })
        .collect();
    let mut cols = Vec::with_capacity(width);
    for p in 0..width as i64 {
        let frame = lo + p;
        let mut sum = vec![0.0; nl];
        let mut wsum = 0.0;
        for (u, &w) in used.iter().zip(&weights) {
            let local = frame - u.2;
            if local < 0 || local >= u.1.ncol() as i64 {
                continue;
            }
            for (s, v) in sum.iter_mut().zip(u.1.col(local as usize)) {
                *s += w * v;
            }
            wsum += w;
        }
        cols.push(if wsum == 0.0 {
            vec![1.0 / nl as f64; nl]
        } else {
            sum.iter().map(|s| s / wsum).collect()
        });
    }

    let total_nsites: f64 = used.iter().map(|u| nsites[u.0]).sum();
    let mut bkg = vec![0.0; nl];
    for u in &used {
        for (b, v) in bkg.iter_mut().zip(&ppms[u.0].bkg) {
            *b += v;
        }
    }
    let bkg: Vec<f64> = bkg.iter().map(|b| b / used.len() as f64).collect();
    let name = opts.name.clone().unwrap_or_else(|| {
        let names: Vec<&str> = used.iter().map(|u| ppms[u.0].name.as_str()).collect();
        format!("merged_{}", names.join("+"))
    });
    let copts = CreateOptions {
        motif_type: MotifType::Ppm,
        name,
        nsites: Some(total_nsites),
        bkg: Some(bkg),
        pseudocount: ppms[anchor].pseudocount,
        ..Default::default()
    };
    // Declared as probabilities, since columns of zeros and ones would
    // otherwise be taken for counts.
    let merged = from_typed_matrix(
        Matrix::from_columns(&cols)?,
        None,
        Some(alphabet),
        MotifType::Ppm,
        &copts,
    )?;
    let mut used_idx: Vec<usize> = used.iter().map(|u| u.0).collect();
    used_idx.sort_unstable();
    Ok(MergedMotif {
        motif: merged,
        used: used_idx,
    })
}

/// [`merge_motifs_detailed`] for CWMs, keeping their sign.
fn merge_cwms(motifs: &[Motif], alphabet: Alphabet, opts: &MergeOptions) -> Result<MergedMotif> {
    let nl = alphabet.len();
    let nsites: Vec<f64> = motifs
        .iter()
        .map(|m| m.nsites.filter(|n| *n > 0.0).unwrap_or(1.0))
        .collect();
    let mass: Vec<f64> = motifs
        .iter()
        .map(|m| m.matrix.as_slice().iter().map(|v| v.abs()).sum())
        .collect();
    let mut anchor = 0;
    for (i, &v) in mass.iter().enumerate().skip(1) {
        if v > mass[anchor] + 1e-9 * mass[anchor].abs().max(1.0) {
            anchor = i;
        }
    }
    let copts = CwmCompareOptions {
        min_overlap: opts.min_overlap,
        rc: opts.rc,
        nthreads: opts.nthreads,
        ..Default::default()
    };
    // Each motif's matrix, oriented to the anchor, and the anchor column
    // its first column faces.
    let mut used: Vec<(usize, Matrix, i64)> = Vec::new();
    for (i, m) in motifs.iter().enumerate() {
        if i == anchor {
            used.push((i, m.matrix.clone(), 0));
            continue;
        }
        let a = align_cwm_pair(m, &motifs[anchor], &copts)?;
        if a.overlap < opts.min_overlap.min(m.width()).min(motifs[anchor].width()) {
            continue;
        }
        let matrix = if a.strand == Strand::Minus {
            m.matrix.reversed()
        } else {
            m.matrix.clone()
        };
        used.push((i, matrix, -a.offset));
    }
    let lo = used.iter().map(|u| u.2).min().unwrap();
    let hi = used.iter().map(|u| u.2 + u.1.ncol() as i64).max().unwrap();
    let mut cols = Vec::with_capacity((hi - lo) as usize);
    for frame in lo..hi {
        let mut sum = vec![0.0; nl];
        let mut wsum = 0.0;
        for u in &used {
            let local = frame - u.2;
            if local < 0 || local >= u.1.ncol() as i64 {
                continue;
            }
            let w = if opts.weighted { nsites[u.0] } else { 1.0 };
            for (s, v) in sum.iter_mut().zip(u.1.col(local as usize)) {
                *s += w * v;
            }
            wsum += w;
        }
        cols.push(if wsum == 0.0 {
            sum
        } else {
            sum.iter().map(|s| s / wsum).collect()
        });
    }
    let mut bkg = vec![0.0; nl];
    for u in &used {
        for (b, v) in bkg.iter_mut().zip(&motifs[u.0].bkg) {
            *b += v / used.len() as f64;
        }
    }
    let name = opts.name.clone().unwrap_or_else(|| {
        let names: Vec<&str> = used.iter().map(|u| motifs[u.0].name.as_str()).collect();
        format!("merged_{}", names.join("+"))
    });
    let copts = CreateOptions {
        motif_type: MotifType::Cwm,
        name,
        nsites: Some(used.iter().map(|u| nsites[u.0]).sum()),
        bkg: Some(bkg),
        ..Default::default()
    };
    let merged = from_typed_matrix(
        Matrix::from_columns(&cols)?,
        None,
        Some(alphabet),
        MotifType::Cwm,
        &copts,
    )?;
    let mut used_idx: Vec<usize> = used.iter().map(|u| u.0).collect();
    used_idx.sort_unstable();
    Ok(MergedMotif {
        motif: merged,
        used: used_idx,
    })
}

/// Clusters of similar motifs and the motif made from each, from
/// [`merge_similar`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct MergedClusters {
    /// The cluster of each input motif, numbered from 0 in order of first
    /// appearance.
    pub clusters: Vec<usize>,
    /// One motif per cluster, in cluster order.
    pub motifs: Vec<Motif>,
    /// Notes on clusters that may be too broad to merge well, such as one
    /// cluster holding over a quarter of the motifs, for the caller to pass
    /// on.
    pub warnings: Vec<String>,
}

/// How [`merge_similar`] grows clusters from the links between motifs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum MergeLinkage {
    /// Clusters are the connected groups of linked motifs, so one link to any
    /// member is enough to join a cluster. Motifs alike only in part can
    /// then chain into one large cluster.
    #[default]
    Single,
    /// Every pair of motifs in a cluster is linked. Clusters come from
    /// complete-linkage clustering of the q-values, or of the similarities
    /// of CWMs, with motifs that are not
    /// linked kept apart, which joins the closest pair of clusters first and
    /// breaks ties by input order, so the result is fully determined by the
    /// motifs.
    Complete,
}

impl MergeLinkage {
    /// `"single"` or `"complete"`, as [`str::parse`] reads them.
    pub fn as_str(&self) -> &'static str {
        match self {
            MergeLinkage::Single => "single",
            MergeLinkage::Complete => "complete",
        }
    }
}

impl std::str::FromStr for MergeLinkage {
    type Err = crate::error::Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "single" => Ok(MergeLinkage::Single),
            "complete" => Ok(MergeLinkage::Complete),
            _ => arg_err(format!("linkage must be 'single' or 'complete', not '{s}'")),
        }
    }
}

/// Options for [`merge_similar`].
#[derive(Debug, Clone, PartialEq)]
pub struct MergeSimilarOptions {
    /// Motifs are linked when their comparison q-value in either direction is
    /// at most this.
    pub qvalue: f64,
    /// The null model for the comparison P-values; the empirical one by
    /// default.
    pub null: NullModel,
    /// Fewest overlapping columns when comparing and merging motifs, lowered
    /// to the width of the narrower motif when needed; 5 by default,
    /// where trees use 6.
    pub min_overlap: usize,
    /// Also align motifs as reverse complements.
    pub rc: bool,
    /// Background for the parametric null in A, C, G, T order, used for DNA and
    /// RNA only.
    pub bkg: [f64; 4],
    /// Weight each motif by its `nsites` when merging.
    pub weighted: bool,
    /// How CWMs are compared when every motif is one; the cosine by default.
    /// Other motifs are compared by column correlation and linked by
    /// q-value.
    pub cwm_metric: CwmMetric,
    /// Compare CWMs by their absolute values, so that a pattern and its
    /// opposite are alike.
    pub ignore_sign: bool,
    /// The similarity at which CWMs are linked, by default
    /// [`CwmMetric::default_min_score`]. Unused for other motifs, which are
    /// linked by `qvalue`.
    pub min_score: Option<f64>,
    /// How clusters grow from the links; single linkage by default.
    pub linkage: MergeLinkage,
    /// Threads to use; 0 means all available.
    pub nthreads: usize,
}

impl Default for MergeSimilarOptions {
    fn default() -> Self {
        MergeSimilarOptions {
            qvalue: 0.01,
            null: NullModel::Empirical,
            min_overlap: 5,
            rc: true,
            bkg: [0.25; 4],
            weighted: false,
            cwm_metric: CwmMetric::Cosine,
            ignore_sign: false,
            min_score: None,
            linkage: MergeLinkage::Single,
            nthreads: 1,
        }
    }
}

/// Cluster similar motifs and merge each cluster.
///
/// Motifs are linked when their comparison q-value is within `opts.qvalue` in
/// either direction. When every motif is a CWM, they are linked instead when
/// their similarity, by [`crate::similarity`] with `opts.cwm_metric` and
/// `opts.ignore_sign`, reaches `opts.min_score`, which keeps the sign and
/// magnitude of their contributions. With [`MergeLinkage::Single`] clusters
/// are the connected groups, and with [`MergeLinkage::Complete`] every pair
/// within a cluster is linked. Single motifs are kept as they were, and
/// larger clusters merged with [`merge_motifs`], which keeps CWMs as CWMs.
///
/// A cluster of more than two motifs that holds over a quarter of them has
/// likely grown from chains of partial likenesses, and is named in
/// [`MergedClusters::warnings`].
#[allow(clippy::needless_range_loop)]
pub fn merge_similar(motifs: &[Motif], opts: &MergeSimilarOptions) -> Result<MergedClusters> {
    if motifs.is_empty() {
        return Ok(MergedClusters {
            clusters: Vec::new(),
            motifs: Vec::new(),
            warnings: Vec::new(),
        });
    }
    shared_alphabet(motifs)?;
    let cwms = motifs.iter().all(|m| m.motif_type == MotifType::Cwm);
    if !cwms && !(opts.qvalue > 0.0 && opts.qvalue <= 1.0) {
        return arg_err("qvalue must be in (0, 1]");
    }
    let n = motifs.len();
    if n == 1 {
        return Ok(MergedClusters {
            clusters: vec![0],
            motifs: motifs.to_vec(),
            warnings: Vec::new(),
        });
    }
    let clusters = if cwms {
        cwm_clusters(motifs, opts)?
    } else {
        qvalue_clusters(motifs, opts)?
    };
    let n_clusters = clusters.iter().max().map_or(0, |&c| c + 1);
    let mut sizes = vec![0usize; n_clusters];
    for &c in &clusters {
        sizes[c] += 1;
    }
    let mut warnings = Vec::new();
    if let Some((big, &size)) = sizes
        .iter()
        .enumerate()
        .max_by_key(|&(c, &s)| (s, std::cmp::Reverse(c)))
        && size > 2
        && size * 4 > n
    {
        let advice = match (cwms, opts.linkage) {
            (false, MergeLinkage::Single) => "a smaller qvalue or complete linkage",
            (false, MergeLinkage::Complete) => "a smaller qvalue",
            (true, MergeLinkage::Single) => "a higher min_score or complete linkage",
            (true, MergeLinkage::Complete) => "a higher min_score",
        };
        warnings.push(format!(
            "cluster {big} holds {size} of the {n} motifs, which suggests that unlike motifs \
             were joined; try {advice} to split it"
        ));
    }

    let mopts = MergeOptions {
        min_overlap: opts.min_overlap,
        rc: opts.rc,
        weighted: opts.weighted,
        nthreads: opts.nthreads,
        name: None,
    };
    let merged = (0..n_clusters)
        .map(|c| {
            let members: Vec<Motif> = (0..n)
                .filter(|&i| clusters[i] == c)
                .map(|i| motifs[i].clone())
                .collect();
            if members.len() == 1 {
                Ok(members.into_iter().next().unwrap())
            } else {
                merge_motifs(&members, &mopts)
            }
        })
        .collect::<Result<_>>()?;
    Ok(MergedClusters {
        clusters,
        motifs: merged,
        warnings,
    })
}

/// Clusters of motifs linked by comparison q-values.
fn qvalue_clusters(motifs: &[Motif], opts: &MergeSimilarOptions) -> Result<Vec<usize>> {
    let n = motifs.len();
    let copts = CompareOptions {
        min_overlap: opts.min_overlap,
        rc: opts.rc,
        null: opts.null,
        bkg: opts.bkg,
        nthreads: opts.nthreads,
        ..Default::default()
    };
    let q = compare_matrix(motifs, &copts, true)?.qvalues;

    // The smaller q-value of each pair, with pairs that cannot be compared
    // never linked.
    let link = |i: usize, j: usize| {
        let qij = q[i][j].min(q[j][i]);
        if qij.is_nan() { f64::INFINITY } else { qij }
    };
    Ok(match opts.linkage {
        MergeLinkage::Single => connected_groups(n, |i, j| link(i, j) <= opts.qvalue),
        MergeLinkage::Complete => {
            // Above any q-value, so that motifs not linked stay apart.
            let dist: Vec<Vec<f64>> = (0..n)
                .map(|i| {
                    (0..n)
                        .map(|j| if i == j { 0.0 } else { link(i, j).min(2.0) })
                        .collect()
                })
                .collect();
            hclust(&dist, Linkage::Complete)?.cutree_height(opts.qvalue)?
        }
    })
}

/// Clusters of CWMs linked by their similarity.
fn cwm_clusters(motifs: &[Motif], opts: &MergeSimilarOptions) -> Result<Vec<usize>> {
    let n = motifs.len();
    let min_score = opts
        .min_score
        .unwrap_or_else(|| opts.cwm_metric.default_min_score());
    if !min_score.is_finite() {
        return arg_err("min_score must be a number");
    }
    let s = cwm_similarity_matrix(
        motifs,
        &CwmCompareOptions {
            metric: opts.cwm_metric,
            ignore_sign: opts.ignore_sign,
            min_overlap: opts.min_overlap,
            rc: opts.rc,
            nthreads: opts.nthreads,
        },
    )?;
    let link = |i: usize, j: usize| {
        let v = s[i][j].max(s[j][i]);
        if v.is_nan() { f64::NEG_INFINITY } else { v }
    };
    Ok(match opts.linkage {
        MergeLinkage::Single => connected_groups(n, |i, j| link(i, j) >= min_score),
        MergeLinkage::Complete => {
            let dist: Vec<Vec<f64>> = (0..n)
                .map(|i| {
                    (0..n)
                        .map(|j| {
                            if i == j {
                                0.0
                            } else {
                                (1.0 - link(i, j)).clamp(0.0, 3.0)
                            }
                        })
                        .collect()
                })
                .collect();
            hclust(&dist, Linkage::Complete)?.cutree_height(1.0 - min_score)?
        }
    })
}

/// The connected groups of `n` items under `linked`, numbered from 0 in order
/// of first appearance.
fn connected_groups(n: usize, linked: impl Fn(usize, usize) -> bool) -> Vec<usize> {
    let mut parent: Vec<usize> = (0..n).collect();
    fn find(parent: &mut [usize], mut x: usize) -> usize {
        let mut root = x;
        while parent[root] != root {
            root = parent[root];
        }
        while parent[x] != root {
            let next = parent[x];
            parent[x] = root;
            x = next;
        }
        root
    }
    for i in 0..n {
        for j in i + 1..n {
            if linked(i, j) {
                let (ra, rb) = (find(&mut parent, i), find(&mut parent, j));
                if ra != rb {
                    parent[rb] = ra;
                }
            }
        }
    }
    let mut seen: Vec<usize> = Vec::new();
    (0..n)
        .map(|i| {
            let r = find(&mut parent, i);
            match seen.iter().position(|&s| s == r) {
                Some(p) => p,
                None => {
                    seen.push(r);
                    seen.len() - 1
                }
            }
        })
        .collect()
}