algeon-cugraph 0.1.2

Safe libcugraph execution component for Algeon
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Strongly-typed parameter wrappers for cuGraph algorithm configuration.
//!
//! Enforces range, non-zero, and finiteness invariants at construction time.
//!
//! # Overview
//!
//! | Type | Constraint | Use Cases |
//! |------|-----------|-----------|
//! | [`IterationCount`] | `> 0` (u32) | `max_iter`, `max_iterations` |
//! | [`BfsDepthLimit`] | `>= 0` (usize) | BFS `depth_limit` |
//! | [`PositiveF64`] | `> 0.0`, finite | `scaling_ratio` |
//! | [`UnitF64`] | `∈ (0.0, 1.0)`, finite | *(currently unused: kept for future algorithms)* |
//! | [`NonNegativeF64`] | `>= 0.0`, finite | `epsilon`, `edge_weight_influence`, `gravity`, `jitter_tolerance` |
//! | [`ClosedUnitF64`] | `∈ [0.0, 1.0]`, finite | `alpha` (damping factor), `barnes_hut_theta` |
//! | [`FractionF64`] | `∈ (0.0, 1.0]`, finite | ECG `threshold` and `resolution` |
//! | [`HalfOpenUnitF64`] | `∈ [0.0, 1.0)`, finite | spectral `evs_tolerance` |
//! | [`ClusterCount`] | `>= 2` (usize) | spectral `n_clusters` |
//!
//! # Examples
//!
//! ```
//! use cugraph::params::{IterationCount, PositiveF64, UnitF64};
//!
//! let iters = IterationCount::new(100).unwrap();
//! assert_eq!(iters.get(), 100);
//!
//! let eps = PositiveF64::new(1e-5).unwrap();
//! assert_eq!(eps.get(), 1e-5);
//!
//! let alpha = UnitF64::new(0.85).unwrap();
//! assert_eq!(alpha.get(), 0.85);
//! ```

use std::{fmt, num::NonZeroU32};

use crate::error::{Error, ErrorKind, Result};

pub(crate) mod defaults {
    use super::{ClosedUnitF64, FractionF64, IterationCount, NonNegativeF64, NonZeroU32, PositiveF64};

    pub(crate) const PAGERANK_ALPHA: ClosedUnitF64 = ClosedUnitF64(0.85);
    pub(crate) const PAGERANK_EPSILON: NonNegativeF64 = NonNegativeF64(1e-5);
    pub(crate) const PAGERANK_MAX_ITERATIONS: IterationCount = IterationCount(NonZeroU32::new(100).unwrap());

    pub(crate) const FORCE_ATLAS2_MAX_ITER: IterationCount = IterationCount(NonZeroU32::new(500).unwrap());
    pub(crate) const FORCE_ATLAS2_OVERLAP_SCALING_RATIO: PositiveF64 = PositiveF64(2.0);
    pub(crate) const FORCE_ATLAS2_EDGE_WEIGHT_INFLUENCE: NonNegativeF64 = NonNegativeF64(1.0);
    pub(crate) const FORCE_ATLAS2_JITTER_TOLERANCE: NonNegativeF64 = NonNegativeF64(1.0);
    pub(crate) const FORCE_ATLAS2_BARNES_HUT_THETA: ClosedUnitF64 = ClosedUnitF64(0.5);
    pub(crate) const FORCE_ATLAS2_SCALING_RATIO: PositiveF64 = PositiveF64(2.0);
    pub(crate) const FORCE_ATLAS2_GRAVITY: NonNegativeF64 = NonNegativeF64(1.0);

    pub(crate) const LOUVAIN_MAX_LEVEL: IterationCount = IterationCount(NonZeroU32::new(100).unwrap());
    pub(crate) const LOUVAIN_THRESHOLD: NonNegativeF64 = NonNegativeF64(1e-7);
    pub(crate) const LOUVAIN_RESOLUTION: PositiveF64 = PositiveF64(1.0);

    pub(crate) const ECG_THRESHOLD: FractionF64 = FractionF64(1e-7);
    pub(crate) const ECG_RESOLUTION: FractionF64 = FractionF64(1.0);
}

/// A strictly positive iteration count.
///
/// Wraps a [`NonZeroU32`] to guarantee that iteration-count parameters (like
/// `max_iter`) are always at least 1. This prevents no-ops that finish without an
/// error from passing zero iterations to algorithm functions.
///
/// # Construction
///
/// ```
/// use cugraph::params::IterationCount;
///
/// // From a runtime value (fallible):
/// let count = IterationCount::new(500).unwrap();
/// assert_eq!(count.get(), 500);
///
/// // TryFrom conversions:
/// let count: IterationCount = 100u32.try_into().unwrap();
/// let count: IterationCount = 100i32.try_into().unwrap();
/// let count: IterationCount = 100usize.try_into().unwrap();
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IterationCount(NonZeroU32);

impl IterationCount {
    /// Create a new `IterationCount` from a `u32`.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidInput`] if `value` is zero.
    pub fn new(value: u32) -> Result<Self> {
        NonZeroU32::new(value).map(IterationCount).ok_or_else(|| {
            Error::new(ErrorKind::InvalidInput, "IterationCount::new")
                .with_message("iteration count must be greater than zero")
        })
    }

    /// Create a new `IterationCount` from a [`NonZeroU32`] (infallible).
    pub const fn from_non_zero(value: NonZeroU32) -> Self {
        IterationCount(value)
    }

    /// Get the underlying value as a `u32`.
    pub const fn get(self) -> u32 {
        self.0.get()
    }

    /// Get the underlying [`NonZeroU32`].
    pub const fn into_inner(self) -> NonZeroU32 {
        self.0
    }
}

impl fmt::Display for IterationCount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<IterationCount> for u32 {
    fn from(count: IterationCount) -> u32 {
        count.get()
    }
}

impl From<IterationCount> for usize {
    fn from(count: IterationCount) -> usize {
        count.get() as usize
    }
}

impl TryFrom<IterationCount> for i32 {
    type Error = Error;

    fn try_from(count: IterationCount) -> Result<i32> {
        i32::try_from(count.get()).map_err(|_| {
            Error::new(ErrorKind::InvalidInput, "IterationCount::try_into<i32>")
                .with_message("iteration count exceeds i32::MAX")
                .with_context("value", count.get().to_string())
        })
    }
}

impl TryFrom<u32> for IterationCount {
    type Error = Error;

    fn try_from(value: u32) -> Result<Self> {
        Self::new(value)
    }
}

impl TryFrom<i32> for IterationCount {
    type Error = Error;

    fn try_from(value: i32) -> Result<Self> {
        if value <= 0 {
            return Err(Error::new(ErrorKind::InvalidInput, "IterationCount::try_from<i32>")
                .with_message("iteration count must be greater than zero")
                .with_context("value", value.to_string()));
        }
        Self::new(value as u32)
    }
}

impl TryFrom<usize> for IterationCount {
    type Error = Error;

    fn try_from(value: usize) -> Result<Self> {
        let val_u32 = u32::try_from(value).map_err(|_| {
            Error::new(ErrorKind::InvalidInput, "IterationCount::try_from<usize>")
                .with_message("iteration count exceeds u32::MAX")
                .with_context("value", value.to_string())
        })?;
        Self::new(val_u32)
    }
}

/// A BFS depth limit: the number of hops to expand from the sources.
///
/// `0` expands no hops and reaches only the sources. Use `None` at the API
/// boundary to request unlimited traversal. A limit larger than the graph's
/// vertex type can index behaves as unlimited.
///
/// # Construction
///
/// ```
/// use cugraph::params::BfsDepthLimit;
///
/// let limit = BfsDepthLimit::new(3);
/// assert_eq!(limit.get(), 3);
///
/// assert_eq!(BfsDepthLimit::new(0).get(), 0);
/// assert!(BfsDepthLimit::try_from(-1i32).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BfsDepthLimit(usize);

impl BfsDepthLimit {
    /// Create a new `BfsDepthLimit` from a `usize`.
    pub const fn new(value: usize) -> Self {
        BfsDepthLimit(value)
    }

    /// Get the underlying value as `usize`.
    pub const fn get(self) -> usize {
        self.0
    }
}

impl fmt::Display for BfsDepthLimit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<BfsDepthLimit> for usize {
    fn from(limit: BfsDepthLimit) -> usize {
        limit.get()
    }
}

impl From<usize> for BfsDepthLimit {
    fn from(value: usize) -> Self {
        Self::new(value)
    }
}

impl From<u32> for BfsDepthLimit {
    fn from(value: u32) -> Self {
        Self::new(value as usize)
    }
}

impl TryFrom<i32> for BfsDepthLimit {
    type Error = Error;

    fn try_from(value: i32) -> Result<Self> {
        usize::try_from(value).map(Self::new).map_err(|_| {
            Error::new(ErrorKind::InvalidInput, "BfsDepthLimit::try_from<i32>")
                .with_message("BFS depth limit must not be negative")
                .with_context("value", value.to_string())
        })
    }
}

/// A strictly positive, finite `f64` value.
///
/// Used for parameters that must be greater than zero, such as scaling ratios.
///
/// # Construction
///
/// ```
/// use cugraph::params::PositiveF64;
///
/// let eps = PositiveF64::new(1e-5).unwrap();
/// assert_eq!(eps.get(), 1e-5);
///
/// // Zero and negative values are rejected:
/// assert!(PositiveF64::new(0.0).is_err());
/// assert!(PositiveF64::new(-1.0).is_err());
///
/// // Infinity and NaN are rejected:
/// assert!(PositiveF64::new(f64::INFINITY).is_err());
/// assert!(PositiveF64::new(f64::NAN).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct PositiveF64(f64);

impl PositiveF64 {
    /// Create a new `PositiveF64` from an `f64`.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidInput`] if `value` is not finite and
    /// positive (i.e., `<= 0.0`, `NaN`, or infinity).
    pub fn new(value: f64) -> Result<Self> {
        if !value.is_finite() || value <= 0.0 {
            return Err(Error::new(ErrorKind::InvalidInput, "PositiveF64::new")
                .with_message("value must be a finite number greater than zero")
                .with_context("value", format!("{value}")));
        }
        Ok(PositiveF64(value))
    }

    /// Get the underlying `f64` value.
    pub const fn get(self) -> f64 {
        self.0
    }
}

impl fmt::Display for PositiveF64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<PositiveF64> for f64 {
    fn from(val: PositiveF64) -> f64 {
        val.get()
    }
}

impl TryFrom<f64> for PositiveF64 {
    type Error = Error;

    fn try_from(value: f64) -> Result<Self> {
        Self::new(value)
    }
}

/// A finite `f64` value in the open interval `(0.0, 1.0)`.
///
/// Used for parameters that represent fractions or probabilities, such as the
/// PageRank damping factor (`alpha`) and Barnes-Hut trade-off (`theta`).
///
/// # Construction
///
/// ```
/// use cugraph::params::UnitF64;
///
/// let alpha = UnitF64::new(0.85).unwrap();
/// assert_eq!(alpha.get(), 0.85);
///
/// // Boundary values are rejected (open interval):
/// assert!(UnitF64::new(0.0).is_err());
/// assert!(UnitF64::new(1.0).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct UnitF64(f64);

impl UnitF64 {
    /// Create a new `UnitF64` from an `f64`.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidInput`] if `value` is not in the open
    /// interval `(0.0, 1.0)` or is not finite.
    pub fn new(value: f64) -> Result<Self> {
        if !value.is_finite() || value <= 0.0 || value >= 1.0 {
            return Err(Error::new(ErrorKind::InvalidInput, "UnitF64::new")
                .with_message("value must be in the open interval (0.0, 1.0)")
                .with_context("value", format!("{value}")));
        }
        Ok(UnitF64(value))
    }

    /// Get the underlying `f64` value.
    pub const fn get(self) -> f64 {
        self.0
    }
}

impl fmt::Display for UnitF64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<UnitF64> for f64 {
    fn from(val: UnitF64) -> f64 {
        val.get()
    }
}

impl TryFrom<f64> for UnitF64 {
    type Error = Error;

    fn try_from(value: f64) -> Result<Self> {
        Self::new(value)
    }
}

/// A non-negative, finite `f64` value (i.e., `>= 0.0`).
///
/// Used for parameters that may be zero but not negative, such as
/// `edge_weight_influence` (where 0.0 means "no influence").
///
/// # Construction
///
/// ```
/// use cugraph::params::NonNegativeF64;
///
/// let influence = NonNegativeF64::new(0.0).unwrap();
/// assert_eq!(influence.get(), 0.0);
///
/// let influence = NonNegativeF64::new(1.5).unwrap();
/// assert_eq!(influence.get(), 1.5);
///
/// // Negative values are rejected:
/// assert!(NonNegativeF64::new(-0.1).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct NonNegativeF64(f64);

impl NonNegativeF64 {
    /// Create a new `NonNegativeF64` from an `f64`.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidInput`] if `value` is negative, `NaN`, or
    /// infinite.
    pub fn new(value: f64) -> Result<Self> {
        if !value.is_finite() || value < 0.0 {
            return Err(Error::new(ErrorKind::InvalidInput, "NonNegativeF64::new")
                .with_message("value must be a finite non-negative number")
                .with_context("value", format!("{value}")));
        }
        Ok(NonNegativeF64(value))
    }

    /// Get the underlying `f64` value.
    pub const fn get(self) -> f64 {
        self.0
    }
}

impl fmt::Display for NonNegativeF64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<NonNegativeF64> for f64 {
    fn from(val: NonNegativeF64) -> f64 {
        val.get()
    }
}

impl TryFrom<f64> for NonNegativeF64 {
    type Error = Error;

    fn try_from(value: f64) -> Result<Self> {
        Self::new(value)
    }
}

/// A finite `f64` value in the closed interval `[0.0, 1.0]`.
///
/// Used for parameters that represent interpolation weights or trade-offs
/// where the boundary values are valid (e.g., Barnes-Hut theta where 0.0 means
/// "maximum accuracy" and 1.0 means "maximum speed").
///
/// # Construction
///
/// ```
/// use cugraph::params::ClosedUnitF64;
///
/// let theta = ClosedUnitF64::new(0.5).unwrap();
/// assert_eq!(theta.get(), 0.5);
///
/// // Boundary values are accepted (closed interval):
/// assert!(ClosedUnitF64::new(0.0).is_ok());
/// assert!(ClosedUnitF64::new(1.0).is_ok());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct ClosedUnitF64(f64);

impl ClosedUnitF64 {
    /// Create a new `ClosedUnitF64` from an `f64`.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidInput`] if `value` is not in the closed
    /// interval `[0.0, 1.0]` or is not finite.
    pub fn new(value: f64) -> Result<Self> {
        if !(0.0..=1.0).contains(&value) {
            return Err(Error::new(ErrorKind::InvalidInput, "ClosedUnitF64::new")
                .with_message("value must be in the closed interval [0.0, 1.0]")
                .with_context("value", format!("{value}")));
        }
        Ok(ClosedUnitF64(value))
    }

    /// Get the underlying `f64` value.
    pub const fn get(self) -> f64 {
        self.0
    }
}

impl fmt::Display for ClosedUnitF64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<ClosedUnitF64> for f64 {
    fn from(val: ClosedUnitF64) -> f64 {
        val.get()
    }
}

impl TryFrom<f64> for ClosedUnitF64 {
    type Error = Error;

    fn try_from(value: f64) -> Result<Self> {
        Self::new(value)
    }
}

/// A finite `f64` value in the half-open interval `(0.0, 1.0]`.
///
/// Used for parameters libcugraph requires to be positive and at most one,
/// such as the ECG convergence `threshold` and `resolution`.
///
/// # Construction
///
/// ```
/// use cugraph::params::FractionF64;
///
/// assert_eq!(FractionF64::new(1.0).unwrap().get(), 1.0);
///
/// // Zero and values above one are rejected:
/// assert!(FractionF64::new(0.0).is_err());
/// assert!(FractionF64::new(1.5).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct FractionF64(f64);

impl FractionF64 {
    /// Create a new `FractionF64` from an `f64`.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidInput`] if `value` is not in the interval
    /// `(0.0, 1.0]` or is not finite.
    pub fn new(value: f64) -> Result<Self> {
        if !(value > 0.0 && value <= 1.0) {
            return Err(Error::new(ErrorKind::InvalidInput, "FractionF64::new")
                .with_message("value must be in the interval (0.0, 1.0]")
                .with_context("value", format!("{value}")));
        }
        Ok(FractionF64(value))
    }

    /// Get the underlying `f64` value.
    pub const fn get(self) -> f64 {
        self.0
    }
}

impl fmt::Display for FractionF64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<FractionF64> for f64 {
    fn from(val: FractionF64) -> f64 {
        val.get()
    }
}

impl TryFrom<f64> for FractionF64 {
    type Error = Error;

    fn try_from(value: f64) -> Result<Self> {
        Self::new(value)
    }
}

/// A finite `f64` value in the half-open interval `[0.0, 1.0)`.
///
/// Used for solver tolerances libcugraph requires to be non-negative and
/// below one, such as the spectral clustering eigensolver and k-means
/// tolerances.
///
/// # Construction
///
/// ```
/// use cugraph::params::HalfOpenUnitF64;
///
/// assert_eq!(HalfOpenUnitF64::new(0.0).unwrap().get(), 0.0);
///
/// // One and values above it are rejected:
/// assert!(HalfOpenUnitF64::new(1.0).is_err());
/// assert!(HalfOpenUnitF64::new(-0.1).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct HalfOpenUnitF64(f64);

impl HalfOpenUnitF64 {
    /// Create a new `HalfOpenUnitF64` from an `f64`.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidInput`] if `value` is not in the interval
    /// `[0.0, 1.0)` or is not finite.
    pub fn new(value: f64) -> Result<Self> {
        if !(0.0..1.0).contains(&value) {
            return Err(Error::new(ErrorKind::InvalidInput, "HalfOpenUnitF64::new")
                .with_message("value must be in the interval [0.0, 1.0)")
                .with_context("value", format!("{value}")));
        }
        Ok(HalfOpenUnitF64(value))
    }

    /// Get the underlying `f64` value.
    pub const fn get(self) -> f64 {
        self.0
    }
}

impl fmt::Display for HalfOpenUnitF64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<HalfOpenUnitF64> for f64 {
    fn from(val: HalfOpenUnitF64) -> f64 {
        val.get()
    }
}

impl TryFrom<f64> for HalfOpenUnitF64 {
    type Error = Error;

    fn try_from(value: f64) -> Result<Self> {
        Self::new(value)
    }
}

/// A cluster count of at least two.
///
/// Upstream libcugraph spectral clustering requires at least two clusters.
///
/// # Construction
///
/// ```
/// use cugraph::params::ClusterCount;
///
/// assert_eq!(ClusterCount::new(2).unwrap().get(), 2);
/// assert!(ClusterCount::new(1).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ClusterCount(usize);

impl ClusterCount {
    /// Create a new `ClusterCount` from a `usize`.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidInput`] if `value` is below two.
    pub fn new(value: usize) -> Result<Self> {
        if value < 2 {
            return Err(Error::new(ErrorKind::InvalidInput, "ClusterCount::new")
                .with_message("cluster count must be at least 2")
                .with_context("value", value.to_string()));
        }
        Ok(ClusterCount(value))
    }

    /// Get the underlying value as `usize`.
    pub const fn get(self) -> usize {
        self.0
    }
}

impl fmt::Display for ClusterCount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<ClusterCount> for usize {
    fn from(count: ClusterCount) -> usize {
        count.get()
    }
}

impl TryFrom<usize> for ClusterCount {
    type Error = Error;

    fn try_from(value: usize) -> Result<Self> {
        Self::new(value)
    }
}