use std::sync::Arc;
use crate::field::Fp;
use crate::linalg::DenseMat;
use crate::module::Module;
use crate::profile::{Site, hit};
use crate::quiver::ArrowId;
pub(crate) fn matrix_is_zero(matrix: &DenseMat) -> bool {
(0..matrix.rows()).all(|row| matrix.row(row).iter().all(|value| value.is_zero()))
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HomError {
DifferentAlgebras,
MapCountMismatch { expected: usize, got: usize },
MapShapeMismatch {
vertex: u32,
expected: (usize, usize),
got: (usize, usize),
},
NonCanonicalEntry { vertex: u32, row: usize, col: usize },
SquareViolated { arrow: ArrowId },
EndpointMismatch,
}
display_error! { error HomError {
Self::DifferentAlgebras => "modules live over different algebras";
Self::MapCountMismatch { expected, got } => "morphism has {got} maps, quiver has {expected} vertices";
Self::MapShapeMismatch { vertex, expected, got } => "map at vertex {vertex} is {}x{}, expected {}x{}", got.0, got.1, expected.0, expected.1;
Self::NonCanonicalEntry { vertex, row, col } => "map at vertex {vertex} has a non-canonical entry at ({row}, {col}) for the modules' field";
Self::SquareViolated { arrow } => "commuting square fails at arrow {}", arrow.0;
Self::EndpointMismatch => "target of the first morphism is not the source of the second";
} }
#[derive(Clone, Debug)]
pub struct Morphism {
source: Module,
target: Module,
maps: Vec<DenseMat>,
}
impl PartialEq for Morphism {
fn eq(&self, other: &Morphism) -> bool {
self.source.ptr_eq(&other.source)
&& self.target.ptr_eq(&other.target)
&& self.maps == other.maps
}
}
impl Eq for Morphism {}
pub(super) fn check_parallel(m: &Module, n: &Module) -> Result<(), HomError> {
if !Arc::ptr_eq(m.algebra(), n.algebra()) {
return Err(HomError::DifferentAlgebras);
}
Ok(())
}
impl Morphism {
pub(super) fn from_parts(source: &Module, target: &Module, maps: Vec<DenseMat>) -> Morphism {
Morphism {
source: source.clone(),
target: target.clone(),
maps,
}
}
pub fn new(
source: &Module,
target: &Module,
maps: Vec<DenseMat>,
) -> Result<Morphism, HomError> {
hit(Site::MorphismNew);
let (m, n) = (source, target);
check_parallel(m, n)?;
let quiver = m.algebra().quiver();
let num_vertices = quiver.num_vertices() as usize;
if maps.len() != num_vertices {
return Err(HomError::MapCountMismatch {
expected: num_vertices,
got: maps.len(),
});
}
let field = m.field();
for (v, map) in maps.iter().enumerate() {
let expected = (m.dim_at(v as u32), n.dim_at(v as u32));
let got = (map.rows(), map.cols());
if got != expected {
return Err(HomError::MapShapeMismatch {
vertex: v as u32,
expected,
got,
});
}
if let Some((row, col)) = map.first_noncanonical(&field) {
return Err(HomError::NonCanonicalEntry {
vertex: v as u32,
row,
col,
});
}
}
for i in 0..quiver.num_arrows() {
hit(Site::MorphismSquare);
let arrow = ArrowId(i as u32);
let (u, v) = (quiver.source(arrow), quiver.target(arrow));
let left = maps[u as usize].mul(n.map(arrow), &field);
let right = m.map(arrow).mul(&maps[v as usize], &field);
if left != right {
return Err(HomError::SquareViolated { arrow });
}
}
Ok(Morphism::from_parts(source, target, maps))
}
pub(crate) fn new_unchecked(source: &Module, target: &Module, maps: Vec<DenseMat>) -> Morphism {
debug_assert!(
Morphism::new(source, target, maps.clone()).is_ok(),
"new_unchecked: the maps are not an A-linear map of these modules"
);
Morphism::from_parts(source, target, maps)
}
accessor_methods! {
pub source() -> &Module = |this| &this.source;
pub target() -> &Module = |this| &this.target;
pub map_at(v: u32) -> &DenseMat = |this| &this.maps[v as usize];
}
pub fn then(&self, g: &Morphism) -> Result<Morphism, HomError> {
hit(Site::MorphismThen);
if !self.target.ptr_eq(&g.source) {
return Err(HomError::EndpointMismatch);
}
let field = self.source.field();
let maps = self
.maps
.iter()
.zip(&g.maps)
.map(|(a, b)| a.mul(b, &field))
.collect();
Ok(Morphism::from_parts(&self.source, &g.target, maps))
}
pub fn is_isomorphism(&self) -> bool {
let field = self.source.field();
self.maps
.iter()
.all(|m| m.rows() == m.cols() && m.rank(&field) == m.rows())
}
pub fn apply(&self, element: &[Vec<Fp>]) -> Vec<Vec<Fp>> {
assert_eq!(
element.len(),
self.maps.len(),
"apply: needs one vector per vertex"
);
let field = self.source.field();
self.maps
.iter()
.zip(element)
.map(|(map, x)| map.transpose().mul_vec(x, &field))
.collect()
}
pub fn is_zero(&self) -> bool {
self.maps.iter().all(matrix_is_zero)
}
}
pub fn identity(m: &Module) -> Morphism {
let maps = m
.dim_vector()
.iter()
.map(|&d| DenseMat::identity(d))
.collect();
Morphism::from_parts(m, m, maps)
}
pub fn zero_morphism(m: &Module, n: &Module) -> Result<Morphism, HomError> {
check_parallel(m, n)?;
let maps = m
.dim_vector()
.iter()
.zip(n.dim_vector())
.map(|(&a, &b)| DenseMat::zero(a, b))
.collect();
Ok(Morphism::from_parts(m, n, maps))
}