use std::sync::Arc;
use crate::algebra::Algebra;
use crate::arquiver::IndecomposableCatalog;
use crate::context::VerificationContext;
use crate::decompose::{
Decomposition, KrullSchmidtOutcome, Split, decompose, direct_sum_or_zero,
krull_schmidt_from_decomposition,
};
use crate::endo::EndoAlgebra;
use crate::hom::HomError;
use crate::indec::{IndecError, IndecomposableModule};
use crate::iso::indecomposable_iso;
use crate::module::Module;
use crate::profile::{Site, hit};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BasicError {
CertificationBlocked {
reason: String,
},
NotBasic {
first: usize,
second: usize,
},
VertexOutOfRange {
vertex: u32,
num_vertices: u32,
},
DifferentAlgebras,
Hom(HomError),
Defect {
reason: String,
},
}
display_error! { error BasicError {
Self::CertificationBlocked { reason } => "certification blocked: {reason}";
Self::NotBasic { first, second } => "summands {first} and {second} are isomorphic, so the module is not basic";
Self::VertexOutOfRange { vertex, num_vertices } => "vertex {vertex} is out of range, the quiver has {num_vertices} vertices";
Self::DifferentAlgebras => "the inputs do not share one algebra";
Self::Hom(error) => "morphism rejected: {error}";
Self::Defect { reason } => "internal cross-check failed: {reason}";
} }
from_variants!(BasicError { HomError => Hom });
pub(super) fn certified(endo: EndoAlgebra) -> Result<IndecomposableModule, BasicError> {
IndecomposableModule::from_endo(endo).map_err(|error| match error {
IndecError::Undetermined { attempts } => BasicError::CertificationBlocked {
reason: format!("a summand stayed undetermined after {attempts} split attempts"),
},
other => BasicError::Defect {
reason: format!("a certified summand failed the indecomposability gate: {other}"),
},
})
}
pub(super) fn defect_non_invertible() -> BasicError {
BasicError::Defect {
reason: "the radical criterion returned a non-invertible map between certified \
indecomposables"
.to_string(),
}
}
#[derive(Clone)]
pub struct BasicDecomposition {
module: Module,
split: Split,
summands: Vec<IndecomposableModule>,
}
fn assemble(algebra: &Arc<Algebra>, summands: Vec<IndecomposableModule>) -> BasicDecomposition {
let (module, inclusions, projections) =
direct_sum_or_zero(algebra, summands.iter().map(|summand| summand.module()));
let parts = summands
.iter()
.map(|summand| summand.module().clone())
.collect();
let split = Split::new(&module, parts, inclusions, projections)
.expect("a direct sum carries its canonical split");
BasicDecomposition {
module,
split,
summands,
}
}
debug_fields!(BasicDecomposition |this| {
"dim_vector" => this.module.dim_vector();
"summand_dim_vectors" => this.dim_vectors();
});
impl BasicDecomposition {
pub fn new(m: &Module) -> Result<BasicDecomposition, BasicError> {
hit(Site::BasicDecompositionNew);
let decomposition = decompose(m);
Self::from_decomposition(m, &decomposition)
}
pub(crate) fn new_with_context(
m: &Module,
context: &VerificationContext,
) -> Result<BasicDecomposition, BasicError> {
hit(Site::BasicDecompositionNew);
let decomposition = context.decompose_for(m);
Self::from_decomposition(m, &decomposition)
}
pub(crate) fn from_decomposition(
m: &Module,
decomposition: &Decomposition,
) -> Result<BasicDecomposition, BasicError> {
hit(Site::KrullSchmidt);
if !decomposition.split().total().ptr_eq(m) {
return Err(BasicError::Defect {
reason: "the supplied decomposition belongs to another module".to_string(),
});
}
Self::from_krull_schmidt(
m,
decomposition.split().clone(),
krull_schmidt_from_decomposition(decomposition),
)
}
fn from_krull_schmidt(
m: &Module,
split: Split,
outcome: KrullSchmidtOutcome,
) -> Result<BasicDecomposition, BasicError> {
let classes = match outcome {
KrullSchmidtOutcome::Classes(classes) => classes,
KrullSchmidtOutcome::Unknown { reason } => {
return Err(BasicError::CertificationBlocked { reason });
}
};
let mut summands = Vec::with_capacity(classes.len());
for class in &classes {
if class.multiplicity > 1 {
return Err(BasicError::NotBasic {
first: summands.len(),
second: summands.len() + 1,
});
}
summands.push(certified(class.endo.clone())?);
}
Ok(BasicDecomposition {
module: m.clone(),
split,
summands,
})
}
pub fn without(&self, slot: usize) -> Option<BasicDecomposition> {
self.summands.get(slot)?;
let summands: Vec<IndecomposableModule> = self
.summands
.iter()
.enumerate()
.filter(|(i, _)| *i != slot)
.map(|(_, x)| x.clone())
.collect();
Some(assemble(self.module.algebra(), summands))
}
pub fn with_new_summand(
&self,
summand: &IndecomposableModule,
) -> Result<BasicDecomposition, BasicError> {
if !Arc::ptr_eq(self.module.algebra(), summand.module().algebra()) {
return Err(BasicError::DifferentAlgebras);
}
for (first, x) in self.summands.iter().enumerate() {
if indecomposable_iso(summand.module(), x.module(), summand.endo()).is_some() {
return Err(BasicError::NotBasic {
first,
second: self.summands.len(),
});
}
}
let mut summands = self.summands.clone();
summands.push(summand.clone());
Ok(assemble(self.module.algebra(), summands))
}
pub fn from_catalog(
catalog: &IndecomposableCatalog,
chosen: &[usize],
) -> Result<BasicDecomposition, BasicError> {
for (second, &i) in chosen.iter().enumerate() {
assert!(
i < catalog.len(),
"from_catalog: entry {i} is not one of the {} catalog positions",
catalog.len()
);
if let Some(first) = chosen[..second].iter().position(|&j| j == i) {
return Err(BasicError::NotBasic { first, second });
}
}
let summands: Vec<IndecomposableModule> = chosen
.iter()
.map(|&i| (*catalog.entries()[i]).clone())
.collect();
Ok(assemble(catalog.algebra(), summands))
}
accessor_methods! {
pub module() -> &Module = |this| &this.module;
pub summands() -> &[IndecomposableModule] = |this| &this.summands;
pub len() -> usize = |this| this.summands.len();
pub is_empty() -> bool = |this| this.summands.is_empty();
}
pub(crate) fn split(&self) -> &Split {
&self.split
}
pub fn dim_vectors(&self) -> Vec<Vec<usize>> {
let mut out: Vec<Vec<usize>> = self
.summands
.iter()
.map(|s| s.module().dim_vector().to_vec())
.collect();
out.sort();
out
}
}