auslander 0.1.0

Computational representation theory of finite-dimensional bound quiver algebras
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
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
786
787
788
789
790
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
//! Monomial bound quiver algebras `kQ/I` with an exact standard-path basis.
//!
//! `I` is generated by forbidden paths of length ≥ 2 (an admissible monomial ideal).
//! The basis consists of all standard paths: paths containing no forbidden word as a
//! contiguous factor. Construction certifies the basis finite or fails, so dimension,
//! Cartan data, and multiplication are exact; nothing in this module truncates.

use std::fmt;
use std::sync::Arc;

use rustc_hash::{FxHashMap, FxHashSet};

use crate::quiver::{ArrowId, PathWord, Quiver, QuiverError};

/// Index into [`MonomialAlgebra::basis`].
pub type BasisIdx = usize;

/// Rejected algebra construction input.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AlgebraError {
    /// Forbidden word `index` has length < 2, violating admissibility `I ⊆ J²`.
    ForbiddenWordTooShort { index: usize, len: usize },
    /// Forbidden word `index` is not a path in the quiver.
    ForbiddenWordInvalid { index: usize, error: QuiverError },
    /// The standard-path language is infinite; v0.1 supports finite-dimensional
    /// algebras only.
    InfiniteDimensional,
    /// Kupisch series violating the conditions documented on the constructor.
    InvalidKupisch { reason: String },
    /// No path with this start and length exists in the linear quiver.
    ZeroPathOutOfRange { start: usize, len: usize },
}

impl fmt::Display for AlgebraError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ForbiddenWordTooShort { index, len } => write!(
                f,
                "forbidden word {index} has length {len}; admissibility needs length >= 2"
            ),
            Self::ForbiddenWordInvalid { index, error } => {
                write!(f, "forbidden word {index} is not a path: {error}")
            }
            Self::InfiniteDimensional => f.write_str(
                "the standard-path language is infinite; v0.1 supports finite-dimensional algebras only",
            ),
            Self::InvalidKupisch { reason } => write!(f, "invalid Kupisch series: {reason}"),
            Self::ZeroPathOutOfRange { start, len } => write!(
                f,
                "no path of length {len} starting at vertex {start} in the linear quiver"
            ),
        }
    }
}

impl std::error::Error for AlgebraError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::ForbiddenWordInvalid { error, .. } => Some(error),
            _ => None,
        }
    }
}

/// The monomial algebra `kQ/I`, `I` generated by the forbidden words.
///
/// Field-free: only the standard-path combinatorics live here. Every such algebra is
/// basic (its vertex idempotents are a complete set of primitive orthogonal
/// idempotents). Basis order, fixed: `basis[v]` is the trivial path `e_v` for
/// `v < num_vertices`; the rest sorted by length, then source vertex, then
/// lexicographic arrow word.
///
/// ```
/// use auslander::algebra::MonomialAlgebra;
/// use auslander::quiver::{ArrowId, Quiver};
/// let loop_x = Quiver::new(1, &[(0, 0)]).unwrap();
/// let a = MonomialAlgebra::new(loop_x, vec![vec![ArrowId(0); 2]]).unwrap();
/// assert_eq!(a.dim(), 2); // k[x]/(x²): basis e, x
/// ```
#[derive(Debug)]
pub struct MonomialAlgebra {
    quiver: Quiver,
    forbidden: Vec<Vec<ArrowId>>,
    basis: Vec<PathWord>,
    index_of: FxHashMap<Vec<ArrowId>, BasisIdx>,
    from: Vec<Vec<BasisIdx>>,
    to: Vec<Vec<BasisIdx>>,
    between: Vec<Vec<Vec<BasisIdx>>>,
    right_mul: Vec<Vec<Option<BasisIdx>>>,
    left_mul: Vec<Vec<Option<BasisIdx>>>,
}

impl MonomialAlgebra {
    /// Builds `kQ/(forbidden)` with a certified finite standard-path basis.
    ///
    /// Forbidden words must be composable paths of length ≥ 2. Words containing another
    /// forbidden word as a factor are dropped silently (the ideal is unchanged).
    /// Errors with [`AlgebraError::InfiniteDimensional`] when the standard-path
    /// language is infinite, decided exactly by cycle detection on the forbidden-prefix
    /// automaton.
    pub fn new(quiver: Quiver, forbidden: Vec<Vec<ArrowId>>) -> Result<Arc<Self>, AlgebraError> {
        for (index, word) in forbidden.iter().enumerate() {
            if word.len() < 2 {
                return Err(AlgebraError::ForbiddenWordTooShort {
                    index,
                    len: word.len(),
                });
            }
            if let Err(error) = PathWord::from_arrows(&quiver, word) {
                return Err(AlgebraError::ForbiddenWordInvalid { index, error });
            }
        }
        let forbidden = minimal_words(forbidden);
        let automaton = Automaton::build(&quiver, &forbidden);
        if automaton.has_cycle() {
            return Err(AlgebraError::InfiniteDimensional);
        }

        let n = quiver.num_vertices() as usize;
        let mut basis: Vec<PathWord> = (0..quiver.num_vertices())
            .map(PathWord::trivial_unchecked)
            .collect();
        let mut state: Vec<usize> = (0..n).collect();
        let mut level_start = 0;
        while level_start < basis.len() {
            let level_end = basis.len();
            for i in level_start..level_end {
                let word = basis[i].arrows().to_vec();
                let target = basis[i].target();
                let s = state[i];
                for &a in quiver.arrows_from(target) {
                    if let Some(next) = automaton.step(s, a) {
                        let mut extended = word.clone();
                        extended.push(a);
                        basis.push(PathWord::from_arrows_unchecked(&quiver, extended));
                        state.push(next);
                    }
                }
            }
            level_start = level_end;
        }

        let mut index_of = FxHashMap::default();
        for (i, p) in basis.iter().enumerate() {
            if !p.is_trivial() {
                index_of.insert(p.arrows().to_vec(), i);
            }
        }
        let mut from = vec![Vec::new(); n];
        let mut to = vec![Vec::new(); n];
        let mut between = vec![vec![Vec::new(); n]; n];
        for (i, p) in basis.iter().enumerate() {
            from[p.source() as usize].push(i);
            to[p.target() as usize].push(i);
            between[p.source() as usize][p.target() as usize].push(i);
        }

        let num_arrows = quiver.num_arrows();
        let mut right_mul = vec![vec![None; num_arrows]; basis.len()];
        let mut left_mul = vec![vec![None; basis.len()]; num_arrows];
        for (i, p) in basis.iter().enumerate() {
            for &a in quiver.arrows_from(p.target()) {
                let mut word = p.arrows().to_vec();
                word.push(a);
                right_mul[i][a.index()] = index_of.get(&word).copied();
            }
            for &a in quiver.arrows_to(p.source()) {
                let mut word = vec![a];
                word.extend_from_slice(p.arrows());
                left_mul[a.index()][i] = index_of.get(&word).copied();
            }
        }

        Ok(Arc::new(MonomialAlgebra {
            quiver,
            forbidden,
            basis,
            index_of,
            from,
            to,
            between,
            right_mul,
            left_mul,
        }))
    }

    /// `dim_k A` = number of standard paths.
    #[inline]
    pub fn dim(&self) -> usize {
        self.basis.len()
    }

    #[inline]
    pub fn quiver(&self) -> &Quiver {
        &self.quiver
    }

    /// The standard-path basis, in the order documented on the type.
    #[inline]
    pub fn basis(&self) -> &[PathWord] {
        &self.basis
    }

    /// The minimal forbidden words in force, sorted by length then arrow word.
    #[inline]
    pub fn forbidden(&self) -> &[Vec<ArrowId>] {
        &self.forbidden
    }

    /// Basis index of `path`: `Ok(Some(i))` when the path is standard,
    /// `Ok(None)` when it is a valid path of the quiver but zero in the algebra
    /// (contains a forbidden factor), and `Err` when it is not a path of this
    /// algebra's quiver at all (see [`PathWord::validate_in`]).
    pub fn path_index(&self, path: &PathWord) -> Result<Option<BasisIdx>, QuiverError> {
        path.validate_in(&self.quiver)?;
        if path.is_trivial() {
            Ok(Some(path.source() as usize))
        } else {
            Ok(self.index_of.get(path.arrows()).copied())
        }
    }

    /// Basis index of `e_v`; equals `v`. Panics if `v >= num_vertices`.
    pub fn vertex_idempotent(&self, v: u32) -> BasisIdx {
        assert!(v < self.quiver.num_vertices());
        v as usize
    }

    /// Basis indices of paths with source `v`, the basis of `e_v A = P_v`.
    /// Panics if `v >= num_vertices`.
    #[inline]
    pub fn paths_from(&self, v: u32) -> &[BasisIdx] {
        &self.from[v as usize]
    }

    /// Basis indices of paths with target `v`, the basis of `A e_v`.
    /// Panics if `v >= num_vertices`.
    #[inline]
    pub fn paths_to(&self, v: u32) -> &[BasisIdx] {
        &self.to[v as usize]
    }

    /// Basis indices of paths from `u` to `v`, the basis of `e_u A e_v`.
    /// Panics if either vertex is out of range.
    #[inline]
    pub fn paths_between(&self, u: u32, v: u32) -> &[BasisIdx] {
        &self.between[u as usize][v as usize]
    }

    /// Cartan matrix: `c[i][j] = dim e_i A e_j`, the number of standard paths from `i`
    /// to `j`; row `i` is the dimension vector of the projective `P_i = e_i A`.
    pub fn cartan_matrix(&self) -> Vec<Vec<usize>> {
        self.between
            .iter()
            .map(|row| row.iter().map(Vec::len).collect())
            .collect()
    }

    /// `basis[i] · a`: `Some(j)` when the product is the standard path `basis[j]`,
    /// `None` when it is zero (non-composable or forbidden). Panics on out-of-range
    /// `i` or `a`.
    #[inline]
    pub fn right_mul(&self, i: BasisIdx, a: ArrowId) -> Option<BasisIdx> {
        self.right_mul[i][a.index()]
    }

    /// `a · basis[i]`, as [`Self::right_mul`].
    #[inline]
    pub fn left_mul(&self, a: ArrowId, i: BasisIdx) -> Option<BasisIdx> {
        self.left_mul[a.index()][i]
    }
}

/// Drops duplicate words and words containing another as a contiguous factor;
/// the generated ideal is unchanged. Result sorted by length, then lexicographically.
fn minimal_words(mut words: Vec<Vec<ArrowId>>) -> Vec<Vec<ArrowId>> {
    words.sort();
    words.dedup();
    words.sort_by_key(Vec::len);
    let mut minimal: Vec<Vec<ArrowId>> = Vec::new();
    for word in words {
        let contains_kept = minimal
            .iter()
            .any(|v| word.windows(v.len()).any(|w| w == v.as_slice()));
        if !contains_kept {
            minimal.push(word);
        }
    }
    minimal
}

/// Deterministic automaton recognizing standard paths.
///
/// States `v < num_starts`: "at vertex `v`, no forbidden-word progress". Remaining
/// states: the nonempty proper prefixes of the (minimal) forbidden words. The state
/// after reading a standard path is its longest suffix that is such a prefix. A
/// transition is absent exactly when appending the arrow completes a forbidden word
/// (or leaves the vertex's arrows). Minimality of the forbidden set guarantees no
/// prefix state contains a forbidden factor, so every state is reachable from a start
/// state. Any cycle then proves the standard-path language infinite.
struct Automaton {
    trans: Vec<Vec<Option<usize>>>,
}

impl Automaton {
    fn build(quiver: &Quiver, forbidden: &[Vec<ArrowId>]) -> Automaton {
        let n = quiver.num_vertices() as usize;
        let mut prefixes: Vec<Vec<ArrowId>> = Vec::new();
        let mut prefix_index: FxHashMap<Vec<ArrowId>, usize> = FxHashMap::default();
        for word in forbidden {
            for len in 1..word.len() {
                let prefix = word[..len].to_vec();
                if !prefix_index.contains_key(&prefix) {
                    prefix_index.insert(prefix.clone(), prefixes.len());
                    prefixes.push(prefix);
                }
            }
        }
        let forbidden_set: FxHashSet<&[ArrowId]> = forbidden.iter().map(Vec::as_slice).collect();

        let num_states = n + prefixes.len();
        let mut trans = vec![vec![None; quiver.num_arrows()]; num_states];
        for (s, row) in trans.iter_mut().enumerate() {
            let (word, vertex): (&[ArrowId], u32) = if s < n {
                (&[], s as u32)
            } else {
                let w = prefixes[s - n].as_slice();
                (w, quiver.target(w[w.len() - 1]))
            };
            for &a in quiver.arrows_from(vertex) {
                let mut extended = word.to_vec();
                extended.push(a);
                // Longest suffix in (forbidden ∪ prefixes) decides; minimality makes
                // the two sets disjoint and rules out shorter forbidden suffixes
                // hiding under a prefix match.
                let mut next = Some(quiver.target(a) as usize);
                for start in 0..extended.len() {
                    let suffix = &extended[start..];
                    if forbidden_set.contains(suffix) {
                        next = None;
                        break;
                    }
                    if let Some(&k) = prefix_index.get(suffix) {
                        next = Some(n + k);
                        break;
                    }
                }
                row[a.index()] = next;
            }
        }
        Automaton { trans }
    }

    /// Kahn's algorithm; every state is reachable, so any cycle means infinitely
    /// many standard paths.
    fn has_cycle(&self) -> bool {
        let m = self.trans.len();
        let mut indegree = vec![0usize; m];
        for row in &self.trans {
            for &t in row.iter().flatten() {
                indegree[t] += 1;
            }
        }
        let mut stack: Vec<usize> = (0..m).filter(|&s| indegree[s] == 0).collect();
        let mut visited = 0;
        while let Some(s) = stack.pop() {
            visited += 1;
            for &t in self.trans[s].iter().flatten() {
                indegree[t] -= 1;
                if indegree[t] == 0 {
                    stack.push(t);
                }
            }
        }
        visited < m
    }

    #[inline]
    fn step(&self, s: usize, a: ArrowId) -> Option<usize> {
        self.trans[s][a.index()]
    }
}

fn linear_quiver(n: usize) -> Quiver {
    let n = u32::try_from(n).expect("vertex count fits in u32");
    let arrows: Vec<(u32, u32)> = (0..n.saturating_sub(1)).map(|i| (i, i + 1)).collect();
    Quiver::new(n, &arrows).expect("endpoints in range by construction")
}

fn cyclic_quiver(n: usize) -> Quiver {
    let arrows: Vec<(u32, u32)> = (0..n).map(|i| (i as u32, ((i + 1) % n) as u32)).collect();
    Quiver::new(u32::try_from(n).expect("vertex count fits in u32"), &arrows)
        .expect("endpoints in range by construction")
}

/// Path algebra of linearly oriented `A_n`: vertices `0..n`, arrows `i → i+1`.
pub fn linear_an(n: usize) -> Arc<MonomialAlgebra> {
    MonomialAlgebra::new(linear_quiver(n), Vec::new())
        .expect("acyclic quiver without relations is finite-dimensional")
}

/// Kronecker-type algebra: vertices `0, 1` and `m` parallel arrows `0 → 1`,
/// no relations. Hereditary; `dim = m + 2`.
pub fn kronecker(m: usize) -> Arc<MonomialAlgebra> {
    let arrows = vec![(0u32, 1u32); m];
    let quiver = Quiver::new(2, &arrows).expect("endpoints in range by construction");
    MonomialAlgebra::new(quiver, Vec::new())
        .expect("acyclic quiver without relations is finite-dimensional")
}

/// `k[x]/(x²)`: one vertex, one loop `x`, forbidden word `xx`.
pub fn dual_numbers() -> Arc<MonomialAlgebra> {
    truncated_poly(2).expect("x² is an admissible relation")
}

/// `k[x]/(xⁿ)`: one vertex, one loop `x`, forbidden word `xⁿ`.
/// Errors for `n < 2` (the ideal would not be admissible).
pub fn truncated_poly(n: usize) -> Result<Arc<MonomialAlgebra>, AlgebraError> {
    let quiver = Quiver::new(1, &[(0, 0)]).expect("endpoints in range by construction");
    MonomialAlgebra::new(quiver, vec![vec![ArrowId(0); n]])
}

/// Linear Nakayama algebra over linearly oriented `A_n` with `dim P_i = kupisch[i]`.
///
/// Valid series `c`: nonempty; `c[n-1] == 1`; `c[i] >= 2` for `i < n-1`
/// (admissibility); `c[i+1] >= c[i] - 1` (rad `P_i` is a quotient of `P_{i+1}`).
/// Anything else errors; for example `[3, 3, 2]`, where no admissible ideal gives
/// the prescribed projective dimensions.
pub fn linear_nakayama(kupisch: &[usize]) -> Result<Arc<MonomialAlgebra>, AlgebraError> {
    let n = kupisch.len();
    if n == 0 {
        return Err(AlgebraError::InvalidKupisch {
            reason: "series is empty".to_string(),
        });
    }
    if kupisch[n - 1] != 1 {
        return Err(AlgebraError::InvalidKupisch {
            reason: format!(
                "linear series must end with 1, got c[{}] = {}",
                n - 1,
                kupisch[n - 1]
            ),
        });
    }
    for i in 0..n - 1 {
        if kupisch[i] < 2 {
            return Err(AlgebraError::InvalidKupisch {
                reason: format!("c[{i}] = {} but interior entries need c >= 2", kupisch[i]),
            });
        }
        if kupisch[i + 1] < kupisch[i] - 1 {
            return Err(AlgebraError::InvalidKupisch {
                reason: format!(
                    "c[{}] = {} violates c[i+1] >= c[i] - 1 = {}",
                    i + 1,
                    kupisch[i + 1],
                    kupisch[i] - 1
                ),
            });
        }
    }
    let mut forbidden = Vec::new();
    for (i, &c) in kupisch.iter().enumerate() {
        // Kill paths from i of length c; the word exists only when i + c <= n - 1.
        if i + c <= n - 1 {
            forbidden.push((i..i + c).map(|j| ArrowId(j as u32)).collect());
        }
    }
    MonomialAlgebra::new(linear_quiver(n), forbidden)
}

/// Cyclic Nakayama algebra over the cycle `0 → 1 → … → n-1 → 0` with
/// `dim P_i = kupisch[i]`.
///
/// Valid series `c`: nonempty; `c[i] >= 2` for all `i` (admissibility); cyclically
/// `c[(i+1) % n] >= c[i] - 1`. Anything else errors.
pub fn cyclic_nakayama(kupisch: &[usize]) -> Result<Arc<MonomialAlgebra>, AlgebraError> {
    let n = kupisch.len();
    if n == 0 {
        return Err(AlgebraError::InvalidKupisch {
            reason: "series is empty".to_string(),
        });
    }
    for (i, &c) in kupisch.iter().enumerate() {
        if c < 2 {
            return Err(AlgebraError::InvalidKupisch {
                reason: format!("c[{i}] = {c} but cyclic entries need c >= 2"),
            });
        }
        if kupisch[(i + 1) % n] < c - 1 {
            return Err(AlgebraError::InvalidKupisch {
                reason: format!(
                    "c[{}] = {} violates cyclic c[i+1] >= c[i] - 1 = {}",
                    (i + 1) % n,
                    kupisch[(i + 1) % n],
                    c - 1
                ),
            });
        }
    }
    let forbidden: Vec<Vec<ArrowId>> = (0..n)
        .map(|i| {
            (0..kupisch[i])
                .map(|j| ArrowId(((i + j) % n) as u32))
                .collect()
        })
        .collect();
    MonomialAlgebra::new(cyclic_quiver(n), forbidden)
}

/// Cyclic quiver on `n` vertices with `rad² = 0`: every length-2 path forbidden.
/// `dim = 2n`.
pub fn radical_square_zero_cycle(n: usize) -> Arc<MonomialAlgebra> {
    let forbidden: Vec<Vec<ArrowId>> = (0..n)
        .map(|i| vec![ArrowId(i as u32), ArrowId(((i + 1) % n) as u32)])
        .collect();
    MonomialAlgebra::new(cyclic_quiver(n), forbidden)
        .expect("rad² = 0 leaves only vertices and arrows")
}

/// Linearly oriented `A_n` with zero relations: each `(start, len)` in `zero_paths`
/// kills the unique path of length `len` from vertex `start` (arrows
/// `start, …, start + len - 1`). `kA_3/(ab)` is `an_with_relations(3, &[(0, 2)])`.
///
/// Errors when a zero path runs past vertex `n - 1` or has length < 2.
pub fn an_with_relations(
    n: usize,
    zero_paths: &[(usize, usize)],
) -> Result<Arc<MonomialAlgebra>, AlgebraError> {
    for &(start, len) in zero_paths {
        if n == 0 || start + len > n - 1 {
            return Err(AlgebraError::ZeroPathOutOfRange { start, len });
        }
    }
    let forbidden = zero_paths
        .iter()
        .map(|&(start, len)| (start..start + len).map(|j| ArrowId(j as u32)).collect())
        .collect();
    MonomialAlgebra::new(linear_quiver(n), forbidden)
}

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

    fn word(algebra: &MonomialAlgebra, arrows: &[u32]) -> PathWord {
        let ids: Vec<ArrowId> = arrows.iter().copied().map(ArrowId).collect();
        PathWord::from_arrows(algebra.quiver(), &ids).unwrap()
    }

    #[test]
    fn dual_numbers_has_basis_e_x() {
        let a = dual_numbers();
        assert_eq!(a.dim(), 2);
        assert!(a.basis()[0].is_trivial());
        assert_eq!(a.basis()[1].arrows(), &[ArrowId(0)]);
    }

    #[test]
    fn truncated_poly_3_has_dim_3() {
        let a = truncated_poly(3).unwrap();
        assert_eq!(a.dim(), 3);
        assert_eq!(a.basis()[2].len(), 2);
    }

    #[test]
    fn truncated_poly_rejects_n_below_2() {
        assert!(matches!(
            truncated_poly(1),
            Err(AlgebraError::ForbiddenWordTooShort { index: 0, len: 1 })
        ));
    }

    #[test]
    fn linear_a3_dim_and_cartan() {
        let a = linear_an(3);
        assert_eq!(a.dim(), 6);
        // Row i = dimension vector of P_i; upper triangular under left-to-right
        // composition since paths run from lower to higher vertices.
        assert_eq!(
            a.cartan_matrix(),
            vec![vec![1, 1, 1], vec![0, 1, 1], vec![0, 0, 1]]
        );
    }

    #[test]
    fn linear_a3_paths_between_counts() {
        let a = linear_an(3);
        for u in 0..3 {
            for v in 0..3 {
                let expected = usize::from(u <= v);
                assert_eq!(a.paths_between(u, v).len(), expected, "({u}, {v})");
            }
        }
    }

    #[test]
    fn a3_mod_ab_has_basis_without_ab() {
        let a = an_with_relations(3, &[(0, 2)]).unwrap();
        assert_eq!(a.dim(), 5);
        for v in 0..3 {
            assert!(a.basis()[v as usize].is_trivial());
        }
        assert_eq!(a.path_index(&word(&a, &[0])), Ok(Some(3)));
        assert_eq!(a.path_index(&word(&a, &[1])), Ok(Some(4)));
        assert_eq!(a.path_index(&word(&a, &[0, 1])), Ok(None));
    }

    #[test]
    fn kronecker_2_has_dim_4() {
        let a = kronecker(2);
        assert_eq!(a.dim(), 4);
        assert_eq!(a.cartan_matrix(), vec![vec![1, 2], vec![0, 1]]);
    }

    #[test]
    fn linear_nakayama_3_2_1_is_path_algebra_a3() {
        let a = linear_nakayama(&[3, 2, 1]).unwrap();
        assert_eq!(a.dim(), 6);
        assert!(a.forbidden().is_empty());
    }

    #[test]
    fn linear_nakayama_2_2_1_is_a3_mod_ab() {
        let a = linear_nakayama(&[2, 2, 1]).unwrap();
        assert_eq!(a.dim(), 5);
        assert_eq!(a.forbidden(), &[vec![ArrowId(0), ArrowId(1)]]);
    }

    #[test]
    fn cyclic_nakayama_2_2_2_has_dim_6() {
        let a = cyclic_nakayama(&[2, 2, 2]).unwrap();
        assert_eq!(a.dim(), 6);
    }

    #[test]
    fn cyclic_nakayama_3_3_3_has_dim_9() {
        let a = cyclic_nakayama(&[3, 3, 3]).unwrap();
        assert_eq!(a.dim(), 9);
    }

    #[test]
    fn linear_kupisch_3_3_2_rejected() {
        // Regression: the old library silently built garbage from this series.
        assert!(matches!(
            linear_nakayama(&[3, 3, 2]),
            Err(AlgebraError::InvalidKupisch { .. })
        ));
    }

    #[test]
    fn linear_kupisch_drop_violation_rejected() {
        assert!(matches!(
            linear_nakayama(&[4, 2, 1]),
            Err(AlgebraError::InvalidKupisch { .. })
        ));
    }

    #[test]
    fn cyclic_kupisch_entry_below_2_rejected() {
        assert!(matches!(
            cyclic_nakayama(&[2, 1, 2]),
            Err(AlgebraError::InvalidKupisch { .. })
        ));
    }

    #[test]
    fn cyclic_kupisch_drop_violation_rejected() {
        assert!(matches!(
            cyclic_nakayama(&[4, 2, 2]),
            Err(AlgebraError::InvalidKupisch { .. })
        ));
    }

    #[test]
    fn loop_without_relations_is_infinite_dimensional() {
        let quiver = Quiver::new(1, &[(0, 0)]).unwrap();
        assert_eq!(
            MonomialAlgebra::new(quiver, Vec::new()).unwrap_err(),
            AlgebraError::InfiniteDimensional
        );
    }

    #[test]
    fn cycle_without_relations_is_infinite_dimensional() {
        let quiver = Quiver::new(3, &[(0, 1), (1, 2), (2, 0)]).unwrap();
        assert_eq!(
            MonomialAlgebra::new(quiver, Vec::new()).unwrap_err(),
            AlgebraError::InfiniteDimensional
        );
    }

    #[test]
    fn forbidden_words_reduced_to_minimal() {
        // A4 with both ab and abc: abc contains ab, so only ab survives.
        let quiver = Quiver::new(4, &[(0, 1), (1, 2), (2, 3)]).unwrap();
        let a = MonomialAlgebra::new(
            quiver,
            vec![
                vec![ArrowId(0), ArrowId(1), ArrowId(2)],
                vec![ArrowId(0), ArrowId(1)],
            ],
        )
        .unwrap();
        assert_eq!(a.forbidden(), &[vec![ArrowId(0), ArrowId(1)]]);
        assert_eq!(a.dim(), 8); // e0..e3, a, b, c, bc
    }

    #[test]
    fn loop_with_x_cubed_forbidden_is_finite() {
        let quiver = Quiver::new(1, &[(0, 0)]).unwrap();
        let a = MonomialAlgebra::new(quiver, vec![vec![ArrowId(0); 3]]).unwrap();
        assert_eq!(a.dim(), 3);
    }

    #[test]
    fn two_loops_with_xx_yy_forbidden_is_infinite() {
        // xyxyxy… never contains xx or yy; the automaton fallback must find the cycle.
        let quiver = Quiver::new(1, &[(0, 0), (0, 0)]).unwrap();
        let result = MonomialAlgebra::new(
            quiver,
            vec![vec![ArrowId(0), ArrowId(0)], vec![ArrowId(1), ArrowId(1)]],
        );
        assert_eq!(result.unwrap_err(), AlgebraError::InfiniteDimensional);
    }

    #[test]
    fn two_loops_with_rad_square_zero_has_dim_3() {
        let quiver = Quiver::new(1, &[(0, 0), (0, 0)]).unwrap();
        let forbidden = vec![
            vec![ArrowId(0), ArrowId(0)],
            vec![ArrowId(0), ArrowId(1)],
            vec![ArrowId(1), ArrowId(0)],
            vec![ArrowId(1), ArrowId(1)],
        ];
        let a = MonomialAlgebra::new(quiver, forbidden).unwrap();
        assert_eq!(a.dim(), 3);
    }

    #[test]
    fn radical_square_zero_cycle_3_has_dim_6() {
        let a = radical_square_zero_cycle(3);
        assert_eq!(a.dim(), 6);
        assert_eq!(a.paths_from(0).len(), 2); // e_0 and the arrow out of 0
    }

    #[test]
    fn multiplication_tables_match_path_composition() {
        let a = linear_an(3);
        let (ia, ib) = (ArrowId(0), ArrowId(1));
        let a_idx = a.path_index(&word(&a, &[0])).unwrap().unwrap();
        let ab_idx = a.path_index(&word(&a, &[0, 1])).unwrap().unwrap();
        assert_eq!(a.right_mul(a.vertex_idempotent(0), ia), Some(a_idx));
        assert_eq!(a.right_mul(a_idx, ib), Some(ab_idx));
        assert_eq!(
            a.left_mul(ia, a.path_index(&word(&a, &[1])).unwrap().unwrap()),
            Some(ab_idx)
        );
        assert_eq!(a.right_mul(a_idx, ia), None); // target(a) != source(a)
    }

    #[test]
    fn multiplication_by_forbidden_extension_is_zero() {
        let a = an_with_relations(3, &[(0, 2)]).unwrap();
        let a_idx = a.path_index(&word(&a, &[0])).unwrap().unwrap();
        assert_eq!(a.right_mul(a_idx, ArrowId(1)), None);
        let b_idx = a.path_index(&word(&a, &[1])).unwrap().unwrap();
        assert_eq!(a.left_mul(ArrowId(0), b_idx), None);
    }

    #[test]
    fn basis_starts_with_trivial_paths_then_lengths_ascend() {
        let a = linear_an(3);
        for v in 0..3u32 {
            let p = &a.basis()[a.vertex_idempotent(v)];
            assert!(p.is_trivial());
            assert_eq!(p.source(), v);
        }
        let lengths: Vec<usize> = a.basis().iter().map(PathWord::len).collect();
        assert_eq!(lengths, vec![0, 0, 0, 1, 1, 2]);
    }

    #[test]
    fn forbidden_word_too_short_rejected() {
        let quiver = Quiver::new(2, &[(0, 1)]).unwrap();
        assert!(matches!(
            MonomialAlgebra::new(quiver, vec![vec![ArrowId(0)]]),
            Err(AlgebraError::ForbiddenWordTooShort { index: 0, len: 1 })
        ));
    }

    #[test]
    fn forbidden_word_not_composable_rejected() {
        let quiver = Quiver::new(3, &[(0, 1), (1, 2)]).unwrap();
        assert!(matches!(
            MonomialAlgebra::new(quiver, vec![vec![ArrowId(1), ArrowId(0)]]),
            Err(AlgebraError::ForbiddenWordInvalid {
                index: 0,
                error: QuiverError::NotComposable { position: 0 },
            })
        ));
    }

    #[test]
    fn an_zero_path_out_of_range_rejected() {
        assert!(matches!(
            an_with_relations(3, &[(1, 2)]),
            Err(AlgebraError::ZeroPathOutOfRange { start: 1, len: 2 })
        ));
    }

    #[test]
    fn paths_from_lists_projective_basis() {
        let a = an_with_relations(3, &[(0, 2)]).unwrap();
        assert_eq!(a.paths_from(0), &[0, 3]); // P_0: e_0, a
        assert_eq!(a.paths_from(1), &[1, 4]); // P_1: e_1, b
        assert_eq!(a.paths_from(2), &[2]); // P_2: e_2
        assert_eq!(a.paths_to(2), &[2, 4]); // A e_2: e_2, b
    }
}