auslander 0.5.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
//! Finite-dimensional right modules over an [`Algebra`].
//!
//! A module assigns to each vertex `v` the row-vector space `k^{dims[v]}`, and to each
//! arrow `a` a `dims[source(a)] × dims[target(a)]` matrix. A path acts by the product
//! of its arrow matrices in word order, so `M(p·q) = M(p) M(q)` under the left-to-right
//! convention of [`crate::quiver`]. The field comes from the algebra.
//!
//! [`Module::new`] checks that every relation of the reduced Groebner basis acts as the
//! zero matrix. That covers the whole ideal, because the action of `u·r·v` factors
//! through the matrix of `r`. A `Module` value is therefore always a `kQ/I`-module.

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

use crate::algebra::{Algebra, BasisIdx};
use crate::field::{Fp, PrimeField};
use crate::hom::Morphism;
use crate::linalg::DenseMat;
use crate::profile::{Site, hit};
use crate::quiver::{ArrowId, PathWord, QuiverError};

/// Rejected module construction input.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ModuleError {
    /// `dims` needs one entry per vertex.
    DimsLengthMismatch { expected: usize, got: usize },
    /// `maps` needs one matrix per arrow.
    MapCountMismatch { expected: usize, got: usize },
    /// `maps[arrow]` must be `dims[source] × dims[target]`.
    MapShapeMismatch {
        arrow: ArrowId,
        expected: (usize, usize),
        got: (usize, usize),
    },
    /// `maps[arrow]` holds an entry at `(row, col)` whose representative is not
    /// canonical for the algebra's field, meaning it is not below the modulus.
    /// Such an entry comes from arithmetic over some other field.
    NonCanonicalEntry {
        arrow: ArrowId,
        row: usize,
        col: usize,
    },
    /// Groebner relation `index` acts as a nonzero matrix, so the data is a
    /// `kQ`-representation but not a `kQ/I`-module.
    RelationActsNonzero { index: usize },
}

impl fmt::Display for ModuleError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DimsLengthMismatch { expected, got } => {
                write!(f, "dims has {got} entries, quiver has {expected} vertices")
            }
            Self::MapCountMismatch { expected, got } => {
                write!(f, "maps has {got} matrices, quiver has {expected} arrows")
            }
            Self::MapShapeMismatch {
                arrow,
                expected,
                got,
            } => write!(
                f,
                "map for arrow {} is {}x{}, expected {}x{}",
                arrow.0, got.0, got.1, expected.0, expected.1
            ),
            Self::NonCanonicalEntry { arrow, row, col } => write!(
                f,
                "map for arrow {} has a non-canonical entry at ({row}, {col}) for the algebra's field",
                arrow.0
            ),
            Self::RelationActsNonzero { index } => {
                write!(f, "relation {index} acts as a nonzero matrix")
            }
        }
    }
}

impl std::error::Error for ModuleError {}

/// A finite-dimensional right `kQ/I`-module, validated at construction.
///
/// Identity is nominal, matching the algebra [`Arc`] policy. Clones share the
/// underlying representation and compare equal under [`Module::ptr_eq`]. Two
/// modules constructed separately stay distinct even when entrywise identical.
/// Morphism endpoints use this identity; there is no structural equality.
/// Cloning is a reference count bump.
#[derive(Clone, Debug)]
pub struct Module(Arc<ModuleInner>);

#[derive(Debug)]
struct ModuleInner {
    algebra: Arc<Algebra>,
    dims: Vec<usize>,
    // One matrix per arrow, dims[source] × dims[target], acting on row vectors.
    maps: Vec<DenseMat>,
}

fn is_zero_mat(m: &DenseMat) -> bool {
    (0..m.rows()).all(|r| m.row(r).iter().all(|v| v.is_zero()))
}

impl Module {
    /// Builds a module after checking map shapes, entry canonicity for the
    /// algebra's field, and that every Groebner relation acts as zero.
    pub fn new(
        algebra: Arc<Algebra>,
        dims: Vec<usize>,
        maps: Vec<DenseMat>,
    ) -> Result<Module, ModuleError> {
        hit(Site::ModuleNew);
        let field = algebra.field();
        let quiver = algebra.quiver();
        let num_vertices = quiver.num_vertices() as usize;
        if dims.len() != num_vertices {
            return Err(ModuleError::DimsLengthMismatch {
                expected: num_vertices,
                got: dims.len(),
            });
        }
        if maps.len() != quiver.num_arrows() {
            return Err(ModuleError::MapCountMismatch {
                expected: quiver.num_arrows(),
                got: maps.len(),
            });
        }
        for (i, map) in maps.iter().enumerate() {
            let arrow = ArrowId(i as u32);
            let expected = (
                dims[quiver.source(arrow) as usize],
                dims[quiver.target(arrow) as usize],
            );
            let got = (map.rows(), map.cols());
            if got != expected {
                return Err(ModuleError::MapShapeMismatch {
                    arrow,
                    expected,
                    got,
                });
            }
        }
        for (i, map) in maps.iter().enumerate() {
            if let Some((row, col)) = map.first_noncanonical(&field) {
                return Err(ModuleError::NonCanonicalEntry {
                    arrow: ArrowId(i as u32),
                    row,
                    col,
                });
            }
        }
        for (index, relation) in algebra.relations().iter().enumerate() {
            hit(Site::ModuleRelationCheck);
            let source = relation.source() as usize;
            let target = relation.target() as usize;
            let mut acc = DenseMat::zero(dims[source], dims[target]);
            for (coeff, word) in relation.terms() {
                let mut action = DenseMat::identity(dims[source]);
                for &a in word.arrows() {
                    action = action.mul(&maps[a.index()], &field);
                }
                for r in 0..acc.rows() {
                    for c in 0..acc.cols() {
                        let scaled = field.mul(*coeff, action.get(r, c));
                        acc.set(r, c, field.add(acc.get(r, c), scaled));
                    }
                }
            }
            if !is_zero_mat(&acc) {
                return Err(ModuleError::RelationActsNonzero { index });
            }
        }
        Ok(Module(Arc::new(ModuleInner {
            algebra,
            dims,
            maps,
        })))
    }

    /// Whether `self` and `other` are the same module value (clones of one
    /// construction), the identity used for morphism endpoints.
    #[inline]
    pub fn ptr_eq(&self, other: &Module) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }

    /// The address of the shared representation, as a hash key for nominal
    /// identity.
    ///
    /// Equal addresses mean [`Module::ptr_eq`], and clones share one address.
    /// Two modules built separately never share one, even when entrywise
    /// identical. The address is only a key while a clone stays alive: a
    /// dropped module frees it for the next allocation, so a map keyed by it
    /// has to hold the module too.
    #[inline]
    pub(crate) fn addr(&self) -> usize {
        Arc::as_ptr(&self.0) as usize
    }

    /// The zero module.
    pub fn zero(algebra: &Arc<Algebra>) -> Module {
        let dims = vec![0; algebra.quiver().num_vertices() as usize];
        let maps = vec![DenseMat::zero(0, 0); algebra.quiver().num_arrows()];
        Module::new(algebra.clone(), dims, maps).expect("the zero module is a module")
    }

    /// The simple module `S_v`: one-dimensional at `v`, zero at every other vertex,
    /// with every arrow acting as zero.
    ///
    /// # Panics
    /// Panics if `v` is not a vertex of the algebra's quiver.
    pub fn simple(algebra: &Arc<Algebra>, v: u32) -> Module {
        let quiver = algebra.quiver();
        assert!(v < quiver.num_vertices(), "simple: vertex {v} out of range");
        let dims: Vec<usize> = (0..quiver.num_vertices())
            .map(|w| usize::from(w == v))
            .collect();
        let maps = (0..quiver.num_arrows())
            .map(|i| {
                let a = ArrowId(i as u32);
                DenseMat::zero(
                    dims[quiver.source(a) as usize],
                    dims[quiver.target(a) as usize],
                )
            })
            .collect();
        Module::new(algebra.clone(), dims, maps).expect("S_v is a module")
    }

    /// The indecomposable projective `P_v = e_v A`: at vertex `w` the basis is the
    /// normal words `v → w`, and an arrow `a` sends the basis word `p` to the
    /// normal form of `p·a`.
    ///
    /// # Panics
    /// Panics if `v` is not a vertex of the algebra's quiver.
    pub fn projective(algebra: &Arc<Algebra>, v: u32) -> Module {
        hit(Site::ModuleProjective);
        let quiver = algebra.quiver();
        assert!(
            v < quiver.num_vertices(),
            "projective: vertex {v} out of range"
        );
        // pos[b] = position of basis word b inside its component's ordered basis.
        let mut pos = vec![usize::MAX; algebra.dim()];
        let mut dims = vec![0usize; quiver.num_vertices() as usize];
        for w in 0..quiver.num_vertices() {
            let component = algebra.paths_between(v, w);
            dims[w as usize] = component.len();
            for (i, &b) in component.iter().enumerate() {
                pos[b] = i;
            }
        }
        let maps = (0..quiver.num_arrows())
            .map(|i| {
                let a = ArrowId(i as u32);
                let (s, t) = (quiver.source(a), quiver.target(a));
                let mut mat = DenseMat::zero(dims[s as usize], dims[t as usize]);
                for (row, &p) in algebra.paths_between(v, s).iter().enumerate() {
                    for &(q, c) in algebra.right_mul(p, a) {
                        mat.set(row, pos[q], c);
                    }
                }
                mat
            })
            .collect();
        Module::new(algebra.clone(), dims, maps).expect("P_v is a module")
    }

    /// The indecomposable injective `I_v = D(A e_v)`: at vertex `w` the basis is the
    /// dual basis `{p* : p a normal word w → v}`.
    ///
    /// The right action dualizes left multiplication: `(f·a)(x) = f(a·x)`, so for an
    /// arrow `a: w → w'` the matrix entry at row `q ∈ paths(w, v)`, column
    /// `p ∈ paths(w', v)` is the coefficient of `q` in the normal form of `a·p`.
    ///
    /// # Panics
    /// Panics if `v` is not a vertex of the algebra's quiver.
    pub fn injective(algebra: &Arc<Algebra>, v: u32) -> Module {
        hit(Site::ModuleInjective);
        let quiver = algebra.quiver();
        assert!(
            v < quiver.num_vertices(),
            "injective: vertex {v} out of range"
        );
        let mut pos = vec![usize::MAX; algebra.dim()];
        let mut dims = vec![0usize; quiver.num_vertices() as usize];
        for w in 0..quiver.num_vertices() {
            let component = algebra.paths_between(w, v);
            dims[w as usize] = component.len();
            for (i, &b) in component.iter().enumerate() {
                pos[b] = i;
            }
        }
        let maps = (0..quiver.num_arrows())
            .map(|i| {
                let a = ArrowId(i as u32);
                let (s, t) = (quiver.source(a), quiver.target(a));
                let mut mat = DenseMat::zero(dims[s as usize], dims[t as usize]);
                for (col, &p) in algebra.paths_between(t, v).iter().enumerate() {
                    for &(q, c) in algebra.left_mul(a, p) {
                        mat.set(pos[q], col, c);
                    }
                }
                mat
            })
            .collect();
        Module::new(algebra.clone(), dims, maps).expect("I_v is a module")
    }

    /// The algebra the module lives over.
    #[inline]
    pub fn algebra(&self) -> &Arc<Algebra> {
        &self.0.algebra
    }

    /// The algebra's field.
    #[inline]
    pub fn field(&self) -> PrimeField {
        self.0.algebra.field()
    }

    /// The dimension vector, indexed by vertex.
    #[inline]
    pub fn dim_vector(&self) -> &[usize] {
        &self.0.dims
    }

    /// `dim_k M_v`.
    ///
    /// # Panics
    /// Panics if `v` is not a vertex of the algebra's quiver.
    #[inline]
    pub fn dim_at(&self, v: u32) -> usize {
        self.0.dims[v as usize]
    }

    /// `dim_k M`.
    pub fn total_dim(&self) -> usize {
        self.0.dims.iter().sum()
    }

    /// Whether every vertex dimension is zero.
    pub fn is_zero(&self) -> bool {
        self.0.dims.iter().all(|&d| d == 0)
    }

    /// The matrix of `a` acting on row vectors, `dims[source] × dims[target]`.
    ///
    /// # Panics
    /// Panics if `a` is not an arrow of the algebra's quiver.
    #[inline]
    pub fn map(&self, a: ArrowId) -> &DenseMat {
        &self.0.maps[a.index()]
    }

    /// The matrix of `word` acting on row vectors: the identity for a trivial path,
    /// otherwise the product of the arrow matrices in word order. Errors when
    /// `word` is not a path of this algebra's quiver (see [`PathWord::validate_in`]).
    pub fn word_action(&self, word: &PathWord) -> Result<DenseMat, QuiverError> {
        hit(Site::WordAction);
        word.validate_in(self.0.algebra.quiver())?;
        let field = self.field();
        let mut acc = DenseMat::identity(self.0.dims[word.source() as usize]);
        for &a in word.arrows() {
            acc = acc.mul(&self.0.maps[a.index()], &field);
        }
        Ok(acc)
    }

    /// The matrix of the uniform element `Σ c_i · basis[i]` acting on row
    /// vectors, `dims[u] × dims[v]` for the shared source `u` and target `v`
    /// of the named basis words.
    ///
    /// # Panics
    /// Panics when `terms` is empty, names a basis index out of range, or
    /// mixes sources or targets.
    pub fn element_action(&self, terms: &[(BasisIdx, Fp)]) -> DenseMat {
        hit(Site::ElementAction);
        assert!(!terms.is_empty(), "element_action: terms are empty");
        let basis = self.0.algebra.basis();
        let source = basis[terms[0].0].source();
        let target = basis[terms[0].0].target();
        let field = self.field();
        let mut acc = DenseMat::zero(self.0.dims[source as usize], self.0.dims[target as usize]);
        for &(index, coeff) in terms {
            let word = &basis[index];
            assert!(
                word.source() == source && word.target() == target,
                "element_action: terms mix sources or targets"
            );
            let action = self
                .word_action(word)
                .expect("algebra basis words are valid in their own quiver");
            for r in 0..acc.rows() {
                for c in 0..acc.cols() {
                    let scaled = field.mul(coeff, action.get(r, c));
                    acc.set(r, c, field.add(acc.get(r, c), scaled));
                }
            }
        }
        acc
    }
}

/// The direct sum with its block inclusions and projections, in summand order.
///
/// `projections[k]` splits `inclusions[k]` (composes to the identity), and
/// `inclusions[j].then(projections[k])` is zero for `j != k`.
///
/// # Panics
/// Panics on an empty slice or when the summands do not share one algebra.
pub fn direct_sum(summands: &[&Module]) -> (Module, Vec<Morphism>, Vec<Morphism>) {
    hit(Site::DirectSum);
    assert!(!summands.is_empty(), "direct_sum: needs a summand");
    let first = summands[0];
    for s in &summands[1..] {
        assert!(
            Arc::ptr_eq(first.algebra(), s.algebra()),
            "direct_sum: mixed algebras"
        );
    }
    let quiver = first.algebra().quiver();
    let n = quiver.num_vertices() as usize;
    let field = first.field();
    let mut offsets = vec![vec![0usize; n]; summands.len()];
    let mut dims = vec![0usize; n];
    for (k, s) in summands.iter().enumerate() {
        for (v, dim) in dims.iter_mut().enumerate() {
            offsets[k][v] = *dim;
            *dim += s.dim_vector()[v];
        }
    }
    let maps = (0..quiver.num_arrows())
        .map(|i| {
            let a = ArrowId(i as u32);
            let (u, w) = (quiver.source(a) as usize, quiver.target(a) as usize);
            let mut mat = DenseMat::zero(dims[u], dims[w]);
            for (k, s) in summands.iter().enumerate() {
                let block = s.map(a);
                for r in 0..block.rows() {
                    for c in 0..block.cols() {
                        mat.set(offsets[k][u] + r, offsets[k][w] + c, block.get(r, c));
                    }
                }
            }
            mat
        })
        .collect();
    let sum = Module::new(first.algebra().clone(), dims, maps)
        .expect("a direct sum of modules is a module");
    let mut inclusions = Vec::with_capacity(summands.len());
    let mut projections = Vec::with_capacity(summands.len());
    for (k, s) in summands.iter().enumerate() {
        let mut incl = Vec::with_capacity(n);
        let mut proj = Vec::with_capacity(n);
        for (v, &offset) in offsets[k].iter().enumerate() {
            let mut inc = DenseMat::zero(s.dim_vector()[v], sum.dim_vector()[v]);
            let mut prj = DenseMat::zero(sum.dim_vector()[v], s.dim_vector()[v]);
            for i in 0..s.dim_vector()[v] {
                inc.set(i, offset + i, field.one());
                prj.set(offset + i, i, field.one());
            }
            incl.push(inc);
            proj.push(prj);
        }
        // The arrow matrices of the sum are block diagonal and these maps are
        // block selections, so both squares hold by construction. See
        // `Morphism::new_unchecked`.
        inclusions.push(Morphism::new_unchecked(s, &sum, incl));
        projections.push(Morphism::new_unchecked(&sum, s, proj));
    }
    (sum, inclusions, projections)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::algebra::{
        an_with_relations, commutative_square, cyclic_nakayama, dual_numbers, linear_an,
    };
    use crate::hom::{identity, zero_morphism};

    fn f5() -> PrimeField {
        PrimeField::new(5).unwrap()
    }

    fn mat(field: &PrimeField, rows: &[&[i64]]) -> DenseMat {
        let rows: Vec<Vec<Fp>> = rows
            .iter()
            .map(|r| r.iter().map(|&v| field.elem(v)).collect())
            .collect();
        DenseMat::from_rows(&rows)
    }

    #[test]
    fn invertible_loop_action_is_rejected() {
        let a = dual_numbers(f5());
        let result = Module::new(a, vec![1], vec![mat(&f5(), &[&[1]])]);
        assert_eq!(
            result.unwrap_err(),
            ModuleError::RelationActsNonzero { index: 0 }
        );
    }

    #[test]
    fn nilpotent_loop_action_is_accepted() {
        let a = dual_numbers(f5());
        let m = Module::new(a, vec![2], vec![mat(&f5(), &[&[0, 1], &[0, 0]])]).unwrap();
        assert_eq!(m.total_dim(), 2);
        assert!(!m.is_zero());
    }

    #[test]
    fn commutative_square_relation_is_enforced() {
        // One-dimensional everywhere; ab acts as 1. The relation ab - cd
        // rejects cd acting as 0 and accepts cd acting as 1.
        let a = commutative_square(f5());
        let one = mat(&f5(), &[&[1]]);
        let zero = mat(&f5(), &[&[0]]);
        let rejected = Module::new(
            a.clone(),
            vec![1, 1, 1, 1],
            vec![one.clone(), one.clone(), one.clone(), zero],
        );
        assert_eq!(
            rejected.unwrap_err(),
            ModuleError::RelationActsNonzero { index: 0 }
        );
        let accepted = Module::new(
            a,
            vec![1, 1, 1, 1],
            vec![one.clone(), one.clone(), one.clone(), one],
        );
        assert!(accepted.is_ok());
    }

    #[test]
    fn wrong_dims_length_is_rejected() {
        let a = linear_an(3, f5());
        let result = Module::new(a, vec![1, 1], vec![DenseMat::zero(1, 1); 2]);
        assert_eq!(
            result.unwrap_err(),
            ModuleError::DimsLengthMismatch {
                expected: 3,
                got: 2
            }
        );
    }

    #[test]
    fn wrong_map_shape_is_rejected() {
        let a = linear_an(3, f5());
        let maps = vec![DenseMat::zero(1, 1), DenseMat::zero(2, 1)];
        let result = Module::new(a, vec![1, 1, 1], maps);
        assert_eq!(
            result.unwrap_err(),
            ModuleError::MapShapeMismatch {
                arrow: ArrowId(1),
                expected: (1, 1),
                got: (2, 1)
            }
        );
    }

    #[test]
    fn zero_module_has_dimension_zero() {
        let a = linear_an(3, f5());
        let z = Module::zero(&a);
        assert!(z.is_zero());
        assert_eq!(z.total_dim(), 0);
        assert_eq!(z.dim_vector(), &[0, 0, 0]);
    }

    #[test]
    fn word_action_multiplies_arrow_matrices_in_word_order() {
        let a = linear_an(3, f5());
        let field = f5();
        let p0 = Module::projective(&a, 0);
        let word =
            PathWord::from_arrows(a.quiver(), &[ArrowId(0), ArrowId(1)]).expect("path a·b in A_3");
        let expected = p0.map(ArrowId(0)).mul(p0.map(ArrowId(1)), &field);
        assert_eq!(p0.word_action(&word), Ok(expected));
        let trivial = PathWord::trivial(a.quiver(), 0).unwrap();
        assert_eq!(p0.word_action(&trivial), Ok(DenseMat::identity(1)));
    }

    #[test]
    fn word_action_rejects_a_word_from_another_quiver() {
        let a = linear_an(3, f5());
        let other = dual_numbers(f5());
        let p0 = Module::projective(&a, 0);
        let word = PathWord::from_arrows(other.quiver(), &[ArrowId(0)]).unwrap();
        assert_eq!(
            p0.word_action(&word),
            Err(QuiverError::EndpointsDisagree {
                stored: (0, 0),
                computed: (0, 1),
            })
        );
    }

    #[test]
    fn element_action_sums_scaled_word_actions() {
        let field = f5();
        let a = commutative_square(field);
        let p0 = Module::projective(&a, 0);
        let ab = a
            .path_index(&PathWord::from_arrows(a.quiver(), &[ArrowId(0), ArrowId(1)]).unwrap())
            .unwrap()
            .unwrap();
        let action = p0.element_action(&[(ab, field.elem(3))]);
        let word_mat = p0.word_action(&a.basis()[ab]).expect("basis word is valid");
        for r in 0..action.rows() {
            for c in 0..action.cols() {
                assert_eq!(
                    action.get(r, c),
                    field.mul(field.elem(3), word_mat.get(r, c))
                );
            }
        }
    }

    #[test]
    #[should_panic(expected = "mix sources")]
    fn element_action_rejects_mixed_endpoints() {
        let a = linear_an(3, f5());
        let p0 = Module::projective(&a, 0);
        p0.element_action(&[(0, f5().one()), (1, f5().one())]);
    }

    #[test]
    fn non_canonical_entry_is_rejected_before_relation_checks() {
        // The entry 3 is canonical in F_5 but not in F_2; over F_2 the loop's square
        // would also violate x² = 0, and the canonicity error must win.
        let a = dual_numbers(PrimeField::new(2).unwrap());
        let maps = vec![mat(&f5(), &[&[3]])];
        assert_eq!(
            Module::new(a, vec![1], maps).unwrap_err(),
            ModuleError::NonCanonicalEntry {
                arrow: ArrowId(0),
                row: 0,
                col: 0,
            }
        );
    }

    #[test]
    fn simple_is_one_dimensional_at_its_vertex() {
        let a = an_with_relations(3, &[(0, 2)], f5()).unwrap();
        for v in 0..3 {
            let s = Module::simple(&a, v);
            let expected: Vec<usize> = (0..3).map(|w| usize::from(w == v as usize)).collect();
            assert_eq!(s.dim_vector(), expected.as_slice());
        }
    }

    // Cartan orientation: c[i][j] = dim e_i A e_j, so row i is the dimension vector of
    // P_i = e_i A and column j is the dimension vector of I_j = D(A e_j).
    #[test]
    fn projective_dim_vectors_are_cartan_rows() {
        for algebra in [
            linear_an(3, f5()),
            an_with_relations(3, &[(0, 2)], f5()).unwrap(),
            cyclic_nakayama(&[2, 2, 2], f5()).unwrap(),
            commutative_square(f5()),
        ] {
            let cartan = algebra.cartan_matrix();
            for v in 0..algebra.quiver().num_vertices() {
                let p = Module::projective(&algebra, v);
                assert_eq!(p.dim_vector(), cartan[v as usize].as_slice(), "P_{v}");
            }
        }
    }

    #[test]
    fn injective_dim_vectors_are_cartan_columns() {
        for algebra in [
            linear_an(3, f5()),
            an_with_relations(3, &[(0, 2)], f5()).unwrap(),
            cyclic_nakayama(&[2, 2, 2], f5()).unwrap(),
            commutative_square(f5()),
        ] {
            let cartan = algebra.cartan_matrix();
            for v in 0..algebra.quiver().num_vertices() {
                let i = Module::injective(&algebra, v);
                let column: Vec<usize> = cartan.iter().map(|row| row[v as usize]).collect();
                assert_eq!(i.dim_vector(), column.as_slice(), "I_{v}");
            }
        }
    }

    #[test]
    fn a3_mod_ab_projective_p0_has_dimension_vector_1_1_0() {
        let a = an_with_relations(3, &[(0, 2)], f5()).unwrap();
        let p0 = Module::projective(&a, 0);
        assert_eq!(p0.dim_vector(), &[1, 1, 0]);
    }

    #[test]
    fn direct_sum_projections_split_inclusions() {
        let a = linear_an(3, f5());
        let p0 = Module::projective(&a, 0);
        let p1 = Module::projective(&a, 1);
        let s2 = Module::simple(&a, 2);
        let parts = [&p0, &p1, &s2];
        let (sum, inclusions, projections) = direct_sum(&parts);
        for v in 0..3 {
            assert_eq!(
                sum.dim_at(v),
                parts.iter().map(|m| m.dim_at(v)).sum::<usize>()
            );
        }
        for (k, part) in parts.iter().enumerate() {
            assert_eq!(
                inclusions[k].then(&projections[k]).unwrap(),
                identity(part),
                "π_{k} ∘ ι_{k}"
            );
            for (j, other) in parts.iter().enumerate() {
                if j != k {
                    assert_eq!(
                        inclusions[j].then(&projections[k]).unwrap(),
                        zero_morphism(other, part).unwrap(),
                        "π_{k} ∘ ι_{j}"
                    );
                }
            }
        }
    }
}