use crate::field::Fp;
use crate::hom::Morphism;
use crate::linalg::DenseMat;
use crate::module::Module;
use super::core::{
check_endpoints, deterministic_complement, flat_row, flat_width, rref_coords, rref_coords_many,
};
use super::{HomQuotient, HomSpaceError, HomSubspace};
impl PartialEq for HomSubspace {
fn eq(&self, other: &HomSubspace) -> bool {
self.source.ptr_eq(&other.source)
&& self.target.ptr_eq(&other.target)
&& self.basis == other.basis
}
}
impl Eq for HomSubspace {}
impl HomSubspace {
pub(crate) fn spanned_by(
source: &Module,
target: &Module,
spanning: &[Morphism],
) -> Result<HomSubspace, HomSpaceError> {
for f in spanning {
check_endpoints(source, target, f)?;
}
let field = source.field();
let rows: Vec<Vec<Fp>> = spanning.iter().map(flat_row).collect();
let stacked = DenseMat::from_rows_with_cols(&rows, flat_width(source, target));
Ok(HomSubspace {
source: source.clone(),
target: target.clone(),
basis: stacked.row_space_basis(&field),
})
}
accessor_methods! {
pub source() -> &Module = |this| &this.source;
pub target() -> &Module = |this| &this.target;
pub dim() -> usize = |this| this.basis.rows();
pub rref_basis() -> &DenseMat = |this| &this.basis;
pub basis_morphism(r: usize) -> Morphism = |this| super::core::morphism_from_flat(&this.source, &this.target, this.basis.row(r));
}
pub fn contains(&self, f: &Morphism) -> Result<bool, HomSpaceError> {
Ok(self.witness_contains(f)?.is_some())
}
pub fn witness_contains(&self, f: &Morphism) -> Result<Option<Vec<Fp>>, HomSpaceError> {
check_endpoints(&self.source, &self.target, f)?;
let field = self.source.field();
Ok(rref_coords(&self.basis, &flat_row(f), &field))
}
pub fn quotient_by(&self, sub: &HomSubspace) -> Result<HomQuotient, HomSpaceError> {
if !(self.source.ptr_eq(&sub.source) && self.target.ptr_eq(&sub.target)) {
return Err(HomSpaceError::IncompatibleSubspaces);
}
let field = self.source.field();
if rref_coords_many(&self.basis, &sub.basis, &field).is_none() {
return Err(HomSpaceError::NotContained);
}
let complement = deterministic_complement(&self.basis, &sub.basis, &field);
Ok(HomQuotient {
subspace: sub.clone(),
complement,
})
}
}