qudit-core 0.3.3

Accelerated and Extensible Quantum Library
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
// TODO: remove all mentions of the old macro radices!
// TODO: Order mods: implementations; python; strategies; test
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::radix::Radix;
use crate::{CompactStorage, CompactVec, QuditSystem};

/// The number of basis states for each qudit (or dit) in a quantum system.
///
/// This object represents the radix -- sometimes called the base, level
/// or ditness -- of each qudit in a qudit system or dit in a classical system,
/// and is implemented as a sequence of unsigned, byte-sized integers.
/// A qubit is a two-level qudit or a qudit with radix two, while a
/// qutrit is a three-level qudit. Two qutrits together are represented
/// by the [3, 3] radices object.
///
/// No radix can be less than 2, as this would not be a valid.
/// As each radix is represented by a byte, this implementation does not
/// support individual radices greater than 255.
///
/// ## Ordering and Endianness
///
/// Indices are counted left to right, for example a [2, 3] qudit
/// radices is interpreted as a qubit as the first qudit and a qutrit as
/// the second one. OpenQudit uses big-endian ordering, so the qubit in
/// the previous example is the most significant qudit and the qutrit is
/// the least significant qudit. For example, in the same system, a state
/// |10> would be represented by the decimal number 3.
#[derive(Hash, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct Radices(CompactVec<Radix>);

impl Radices {
    /// Constructs a Radices object from the given input.
    ///
    /// # Arguments
    ///
    /// * `radices` - A slice detailing the radices of a qudit system.
    ///
    /// # Panics
    ///
    /// If radices does not represent a valid system. This can happen
    /// if any of the radices are 0 or 1.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    /// let three_qubits = Radices::new([2; 3]);
    /// let qubit_qutrit = Radices::new([2, 3]);
    /// ```
    pub fn new<T: Into<Radices>>(radices: T) -> Self {
        radices.into()
    }

    /// Attempts to determine the radices for a qudit system with given dimension.
    ///
    /// It first tries powers of two, failing that powers of three. If neither
    /// then it will return a QuditRadices with only one qudit of dimension
    /// equal to the input.
    pub fn guess(dimension: usize) -> Radices {
        if dimension < 2 {
            panic!("Invalid dimension in Radices");
        }

        // Is a power of two?
        if dimension & (dimension - 1) == 0 {
            let num_qudits = dimension.trailing_zeros() as usize;
            return vec![2; num_qudits].into();
        }

        let mut n = dimension;
        let mut power = 0;
        while n > 1 {
            if !n.is_multiple_of(3) {
                return [dimension].into();
            }
            n /= 3;
            power += 1;
        }
        vec![3; power].into()
    }

    /// Construct the expanded form of an index in this numbering system.
    ///
    /// # Arguments
    ///
    /// * `index` - The number to expand.
    ///
    /// # Returns
    ///
    /// A vector of coefficients for each qudit in the system. Note that
    /// the coefficients are in big-endian order, that is, the first
    /// coefficient is for the most significant qudit.
    ///
    /// # Panics
    ///
    /// If `index` is too large for this system, that is, if it is greater
    /// than the product of the radices.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    ///
    /// let hybrid_system = Radices::new([2, 3]);
    /// assert_eq!(hybrid_system.expand(3), vec![1, 0]);
    ///
    /// let four_qubits = Radices::new([2, 2, 2, 2]);
    /// assert_eq!(four_qubits.expand(7), vec![0, 1, 1, 1]);
    ///
    /// let two_qutrits = Radices::new([3, 3]);
    /// assert_eq!(two_qutrits.expand(7), vec![2, 1]);
    ///
    /// let hybrid_system = Radices::new([3, 2, 3]);
    /// assert_eq!(hybrid_system.expand(17), vec![2, 1, 2]);
    /// ```
    ///
    /// # See Also
    ///
    /// * [Self::compress] - The inverse of this function.
    /// * [Self::place_values] - The place values for each position in the expansion.
    #[track_caller]
    pub fn expand(&self, mut index: usize) -> Vec<usize> {
        if index >= self.dimension() {
            panic!(
                "Provided index {} is too large for this system with radices: {:#?}",
                index, self
            );
        }

        let mut expansion = vec![0; self.num_qudits()];

        for (idx, radix) in self.iter().enumerate().rev() {
            let casted_radix: usize = (*radix).into();
            let coef: usize = index % casted_radix;
            index -= coef;
            index /= casted_radix;
            expansion[idx] = coef;
        }

        expansion
    }

    /// Destruct an expanded form of an index back into its base 10 number.
    ///
    /// # Arguments
    ///
    /// * `expansion` - The expansion to compress.
    ///
    /// # Panics
    ///
    /// If `expansion` has a mismatch in length or radices.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    ///
    /// let hybrid_system = Radices::new([2, 3]);
    /// assert_eq!(hybrid_system.compress(&vec![1, 0]), 3);
    ///
    /// let four_qubits = Radices::new([2, 2, 2, 2]);
    /// assert_eq!(four_qubits.compress(&vec![0, 1, 1, 1]), 7);
    ///
    /// let two_qutrits = Radices::new([3, 3]);
    /// assert_eq!(two_qutrits.compress(&vec![2, 1]), 7);
    ///
    /// let hybrid_system = Radices::new([3, 2, 3]);
    /// assert_eq!(hybrid_system.compress(&vec![2, 1, 2]), 17);
    /// ```
    ///
    /// # See Also
    ///
    /// * [Self::expand] - The inverse of this function.
    /// * [Self::place_values] - The place values for each position in the expansion.
    #[track_caller]
    pub fn compress(&self, expansion: &[usize]) -> usize {
        if self.len() != expansion.len() {
            panic!("Invalid expansion: incorrect number of qudits.")
        }

        if expansion
            .iter()
            .enumerate()
            .any(|(index, coef)| *coef >= usize::from(self[index]))
        {
            panic!("Invalid expansion: mismatch in qudit radices.")
        }

        if expansion.is_empty() {
            return 0;
        }

        let mut acm_val = expansion[self.num_qudits() - 1];
        let mut acm_base = usize::from(self[self.num_qudits() - 1]);

        for coef_index in (0..expansion.len() - 1).rev() {
            let coef = expansion[coef_index];
            acm_val += coef * acm_base;
            acm_base *= usize::from(self[coef_index]);
        }

        acm_val
    }

    /// Calculate the value for each expansion position in this numbering system.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    ///
    /// let two_qubits = Radices::new([2, 2]);
    /// assert_eq!(two_qubits.place_values(), vec![2, 1]);
    ///
    /// let two_qutrits = Radices::new([3, 3]);
    /// assert_eq!(two_qutrits.place_values(), vec![3, 1]);
    ///
    /// let hybrid_system = Radices::new([3, 2, 3]);
    /// assert_eq!(hybrid_system.place_values(), vec![6, 3, 1]);
    /// ```
    ///
    /// # See Also
    /// * [Self::expand] - Expand an decimal value into this numbering system.
    /// * [Self::compress] - Compress an expansion in this numbering system to decimal.
    pub fn place_values(&self) -> Vec<usize> {
        let mut place_values = vec![0; self.num_qudits()];
        let mut acm = 1;
        for (idx, r) in self.iter().enumerate().rev() {
            place_values[idx] = acm;
            acm *= usize::from(*r);
        }
        place_values
    }

    /// Concatenates two QuditRadices objects into a new object.
    ///
    /// # Arguments
    ///
    /// * `other` - The other QuditRadices object to concatenate with `self`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    ///
    /// let two_qubits = Radices::new([2, 2]);
    /// let two_qutrits = Radices::new([3, 3]);
    /// let four_qudits = Radices::new([2, 2, 3, 3]);
    /// assert_eq!(two_qubits.concat(&two_qutrits), four_qudits);
    ///
    /// let hybrid_system = Radices::new([3, 2, 3]);
    /// let two_qutrits = Radices::new([3, 3]);
    /// let five_qudits = Radices::new([3, 2, 3, 3, 3]);
    /// assert_eq!(hybrid_system.concat(&two_qutrits), five_qudits);
    /// ```
    #[inline(always)]
    pub fn concat(&self, other: &Radices) -> Radices {
        self.iter().chain(other.iter()).copied().collect()
    }

    /// Returns the number of each radix in the system.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    /// # use std::collections::HashMap;
    /// let two_qubits = Radices::new([2, 2]);
    /// let counts = two_qubits.counts();
    /// assert_eq!(counts.get(&(2.into())), Some(&2));
    ///
    /// let two_qutrits = Radices::new([3, 3]);
    /// let counts = two_qutrits.counts();
    /// assert_eq!(counts.get(&(3.into())), Some(&2));
    ///
    /// let hybrid_system = Radices::new([3, 2, 3]);
    /// let counts = hybrid_system.counts();
    /// assert_eq!(counts.get(&(3.into())), Some(&2));
    /// assert_eq!(counts.get(&(2.into())), Some(&1));
    /// ```
    pub fn counts(&self) -> HashMap<Radix, usize> {
        let mut counts = HashMap::new();
        for radix in self.iter() {
            *counts.entry(*radix).or_insert(0) += 1;
        }
        counts
    }

    /// Returns the length of the radices object.
    pub fn len(&self) -> usize {
        self.num_qudits()
    }

    /// Returns true is the system is empty, false otherwise.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl crate::QuditSystem for Radices {
    /// Returns the radices of the system.
    ///
    /// See [`QuditSystem`] for more information.
    #[inline(always)]
    fn radices(&self) -> Radices {
        self.clone()
    }

    /// Returns the dimension of a system described by these radices.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    /// # use qudit_core::QuditSystem;
    ///
    /// let two_qubits = Radices::new([2, 2]);
    /// assert_eq!(two_qubits.dimension(), 4);
    ///
    /// let two_qutrits = Radices::new([3, 3]);
    /// assert_eq!(two_qutrits.dimension(), 9);
    ///
    /// let hybrid_system = Radices::new([3, 2, 3]);
    /// assert_eq!(hybrid_system.dimension(), 18);
    /// ```
    #[inline(always)]
    fn dimension(&self) -> usize {
        self.iter().product::<usize>()
    }

    /// Returns the number of qudits represented by these radices.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    /// # use qudit_core::QuditSystem;
    ///
    /// let two_qubits = Radices::new([2, 2]);
    /// assert_eq!(two_qubits.num_qudits(), 2);
    ///
    /// let two_qutrits = Radices::new([3, 3]);
    /// assert_eq!(two_qutrits.num_qudits(), 2);
    ///
    /// let hybrid_system = Radices::new([3, 2, 3]);
    /// assert_eq!(hybrid_system.num_qudits(), 3);
    ///
    /// let ten_qubits = Radices::new(vec![2; 10]);
    /// assert_eq!(ten_qubits.num_qudits(), 10);
    /// ```
    #[inline(always)]
    fn num_qudits(&self) -> usize {
        self.0.len()
    }

    /// Returns true if these radices describe a qubit-only system.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    /// # use qudit_core::QuditSystem;
    ///
    /// let two_qubits = Radices::new([2, 2]);
    /// assert!(two_qubits.is_qubit_only());
    ///
    /// let qubit_qutrit = Radices::new([2, 3]);
    /// assert!(!qubit_qutrit.is_qubit_only());
    ///
    /// let two_qutrits = Radices::new([3, 3]);
    /// assert!(!two_qutrits.is_qubit_only());
    /// ```
    #[inline(always)]
    fn is_qubit_only(&self) -> bool {
        self.iter().all(|r| *r == 2)
    }

    /// Returns true if these radices describe a qutrit-only system.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    /// # use qudit_core::QuditSystem;
    ///
    /// let two_qubits = Radices::new([2, 2]);
    /// assert!(!two_qubits.is_qutrit_only());
    ///
    /// let qubit_qutrit = Radices::new([2, 3]);
    /// assert!(!qubit_qutrit.is_qutrit_only());
    ///
    /// let two_qutrits = Radices::new([3, 3]);
    /// assert!(two_qutrits.is_qutrit_only());
    /// ```
    #[inline(always)]
    fn is_qutrit_only(&self) -> bool {
        self.iter().all(|r| *r == 3)
    }

    /// Returns true if these radices describe a `radix`-only system.
    ///
    /// # Arguments
    ///
    /// * `radix` - The radix to check for.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    /// # use qudit_core::QuditSystem;
    ///
    /// let two_qubits = Radices::new([2, 2]);
    /// assert!(two_qubits.is_qudit_only(2));
    /// assert!(!two_qubits.is_qudit_only(3));
    ///
    /// let mixed_qudits = Radices::new([2, 3]);
    /// assert!(!mixed_qudits.is_qudit_only(2));
    /// assert!(!mixed_qudits.is_qudit_only(3));
    /// ```
    #[inline(always)]
    fn is_qudit_only<T: Into<Radix>>(&self, radix: T) -> bool {
        let radix = radix.into();
        self.iter().all(|r| *r == radix)
    }

    /// Returns true if these radices describe a homogenous system.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    /// # use qudit_core::QuditSystem;
    ///
    /// let two_qubits = Radices::new([2, 2]);
    /// assert!(two_qubits.is_homogenous());
    ///
    /// let mixed_qudits = Radices::new([2, 3]);
    /// assert!(!mixed_qudits.is_homogenous());
    /// ```
    #[inline(always)]
    fn is_homogenous(&self) -> bool {
        self.is_qudit_only(self[0])
    }
}

impl<T: Into<Radix>> core::iter::FromIterator<T> for Radices {
    /// Creates a new QuditRadices object from an iterator.
    ///
    /// # Arguments
    ///
    /// * `iter` - An iterator over the radices of a qudit system.
    ///
    /// # Panics
    ///
    /// If radices does not represent a valid system. This can happen
    /// if any of the radices are 0 or 1.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    ///
    /// let qubit_qutrit = Radices::from_iter(2..4);
    /// assert_eq!(qubit_qutrit, Radices::new([2, 3]));
    ///
    /// let two_qutrits = Radices::from_iter(vec![3, 3]);
    /// assert_eq!(two_qutrits, Radices::new([3, 3]));
    ///
    /// // Ten qubits then ten qutrits
    /// let mixed_system = Radices::from_iter(vec![2; 10].into_iter()
    ///                         .chain(vec![3; 10].into_iter()));
    ///
    /// // Using .collect()
    /// let from_collect: Radices = (2..5).collect();
    /// assert_eq!(from_collect, Radices::new([2, 3, 4]));
    /// ```
    ///
    /// # Note
    ///
    /// This will attempt to avoid an allocation when possible.
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let vec: CompactVec<Radix> = iter.into_iter().map(|r| r.into()).collect();
        Radices(vec)
    }
}

impl core::ops::Deref for Radices {
    type Target = [Radix];

    #[inline(always)]
    fn deref(&self) -> &[Radix] {
        // Safety Radix is a transparent wrapper around u8
        unsafe {
            std::mem::transmute(
                std::mem::transmute::<&CompactVec<Radix>, &CompactVec<u8>>(&self.0).deref(),
            )
        }
    }
}

impl<T: Into<Radix> + CompactStorage> From<CompactVec<T>> for Radices {
    #[inline(always)]
    fn from(value: CompactVec<T>) -> Self {
        value.into_iter().map(|x| x.into()).collect()
    }
}

impl<T: Into<Radix> + 'static> From<Vec<T>> for Radices {
    #[inline(always)]
    fn from(value: Vec<T>) -> Self {
        let vec = if std::any::TypeId::of::<T>() == std::any::TypeId::of::<Radix>() {
            // If T is radix, then doing CompactVec::from will provide move semantics efficiently
            // Safety: T == Radix, so Vec<T> == Vec<Radix>
            CompactVec::<Radix>::from(unsafe { std::mem::transmute::<Vec<T>, Vec<Radix>>(value) })
        } else {
            value.into_iter().map(|x| x.into()).collect()
        };

        Radices(vec)
    }
}

impl<T: Into<Radix> + Copy> From<&[T]> for Radices {
    #[inline(always)]
    fn from(value: &[T]) -> Self {
        value.iter().copied().collect()
    }
}

impl<T: Into<Radix>, const N: usize> From<[T; N]> for Radices {
    #[inline(always)]
    fn from(value: [T; N]) -> Self {
        value.into_iter().collect()
    }
}

impl<'a, T: Into<Radix> + Copy, const N: usize> From<&'a [T; N]> for Radices {
    #[inline(always)]
    fn from(value: &'a [T; N]) -> Self {
        value.iter().copied().collect()
    }
}

impl From<Radix> for Radices {
    fn from(value: Radix) -> Self {
        [value].into()
    }
}

impl core::fmt::Debug for Radices {
    /// Formats the radices as a string.
    ///
    /// See Display for more information.
    #[inline(always)]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> std::fmt::Result {
        <Radices as core::fmt::Display>::fmt(self, f)
    }
}

impl core::fmt::Display for Radices {
    /// Formats the radices as a string.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::Radices;
    /// let two_qubits = Radices::new([2, 2]);
    /// let two_qutrits = Radices::new([3, 3]);
    /// let qubit_qutrit = Radices::new([2, 3]);
    ///
    /// assert_eq!(format!("{}", two_qubits), "[2, 2]");
    /// assert_eq!(format!("{}", two_qutrits), "[3, 3]");
    /// assert_eq!(format!("{}", qubit_qutrit), "[2, 3]");
    /// ```
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[")?;
        let enum_iter = self.iter().enumerate();
        for (i, r) in enum_iter {
            if i == self.len() - 1 {
                write!(f, "{}", r)?;
            } else {
                write!(f, "{}, ", r)?;
            }
        }

        write!(f, "]")?;
        Ok(())
    }
}

#[cfg(test)]
pub mod strategies {
    use proptest::prelude::*;

    use super::*;

    impl Arbitrary for Radices {
        type Parameters = (core::ops::Range<u8>, core::ops::Range<usize>);
        type Strategy = BoxedStrategy<Self>;

        /// Generate a random Radices object.
        ///
        /// By default, the number of radices is chosen randomly between
        /// 1 and 4, and the radices themselves are chosen randomly
        /// between 2 and 4.
        fn arbitrary() -> Self::Strategy {
            Self::arbitrary_with((2..5u8, 1..5))
        }

        /// Generate a random Radices object with the given parameters.
        ///
        /// # Arguments
        ///
        /// * `args` - A tuple of ranges for the number of radices and the
        ///   radices themselves. The first range is for the number
        ///   of radices, and the second range is for the radices
        ///   themselves.
        fn arbitrary_with(args: Self::Parameters) -> Self::Strategy {
            prop::collection::vec(args.0, args.1)
                .prop_map(Radices::new)
                .boxed()
        }
    }
}

#[cfg(feature = "python")]
mod python {
    use super::*;
    use pyo3::{exceptions::PyTypeError, prelude::*};
    use pyo3_stub_gen::impl_stub_type;

    impl_stub_type!(Radices = usize | Vec<usize>);

    impl<'a, 'py> FromPyObject<'a, 'py> for Radices {
        type Error = PyErr;

        fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
            if let Ok(num) = ob.extract::<usize>() {
                Ok(Radices::new([num]))
            } else if let Ok(nums) = ob.extract::<Vec<usize>>() {
                Ok(Radices::new(nums))
            } else {
                Err(PyTypeError::new_err(
                    "Expected a list of integers for radices.",
                ))
            }
        }
    }

    impl<'py> IntoPyObject<'py> for Radices {
        type Target = pyo3::types::PyList;
        type Output = Bound<'py, Self::Target>;
        type Error = PyErr;

        /// Converts into a Python list of ints, mirroring `FromPyObject`.
        ///
        /// This only exists so that `pyo3-stub-gen` can render `Radices`
        /// default parameter values (e.g. `Radices::new([2])`) in generated
        /// `.pyi` stubs; `Radices` is otherwise only ever a pyfunction
        /// input, never a return value.
        fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
            let ints: Vec<usize> = self.iter().map(|&r| usize::from(r)).collect();
            pyo3::types::PyList::new(py, ints)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        /// An expansion should compress to the same value.
        #[test]
        fn test_expand_compress(radices in any::<Radices>()) {
            for index in 0..radices.dimension() {
                let exp = radices.expand(index);
                assert_eq!(radices.compress(&exp), index);
            }
        }
    }

    #[test]
    fn test_slice_ops() {
        let rdx = Radices::new(vec![2, 3, 4usize]);
        assert_eq!(rdx.len(), 3);
        assert_eq!(rdx[1], 3);
        assert_eq!(rdx[1..], [3, 4]);
        assert_eq!(rdx.clone(), rdx);
    }
}