feanor_math/pid.rs
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
use crate::ring::*;
use crate::divisibility::*;
///
/// Trait for rings that are principal ideal rings, i.e. every ideal is generated
/// by a single element.
///
/// A principal ideal ring currently must be commutative, since otherwise we would
/// have to distinguish left-, right-and two-sided ideals.
///
pub trait PrincipalIdealRing: DivisibilityRing {
///
/// Similar to [`DivisibilityRing::checked_left_div()`] this computes a "quotient" `q`
/// of `lhs` and `rhs`, if it exists. However, we impose the additional constraint
/// that this quotient be minimal, i.e. there is no `q'` with `q' | q` properly and
/// `q' * rhs = lhs`.
///
/// In domains, this is always satisfied, i.e. this function behaves exactly like
/// [`DivisibilityRing::checked_left_div()`]. However, if there are zero-divisors, weird
/// things can happen. For example in `Z/6Z`, `checked_div(4, 4)` may return `4`, however
/// this is not minimal since `1 | 4` and `1 * 4 = 4`.
///
/// In particular, this function can be used to compute a generator of the annihilator ideal
/// of an element `x`, by using it as `checked_div_min(0, x)`.
///
fn checked_div_min(&self, lhs: &Self::Element, rhs: &Self::Element) -> Option<Self::Element>;
///
/// Returns the (w.r.t. divisibility) smallest element `x` such that `x * val = 0`.
///
/// If the ring is a domain, this returns `0` for all ring elements except zero (for
/// which it returns any unit).
///
/// # Example
/// ```
/// # use feanor_math::assert_el_eq;
/// # use feanor_math::ring::*;
/// # use feanor_math::pid::*;
/// # use feanor_math::homomorphism::*;
/// # use feanor_math::rings::zn::zn_64::*;
/// let Z6 = Zn::new(6);
/// assert_el_eq!(Z6, Z6.int_hom().map(3), Z6.annihilator(&Z6.int_hom().map(2)));
/// ```
///
fn annihilator(&self, val: &Self::Element) -> Self::Element {
self.checked_div_min(&self.zero(), val).unwrap()
}
///
/// Computes a Bezout identity for the generator `g` of the ideal `(lhs, rhs)`
/// as `g = s * lhs + t * rhs`.
///
/// More concretely, this returns (s, t, g) such that g is a generator
/// of the ideal `(lhs, rhs)` and `g = s * lhs + t * rhs`. This `g` is also known
/// as the greatest common divisor of `lhs` and `rhs`, since `g | lhs, rhs` and
/// for every `g'` with this property, have `g' | g`. Note that this `g` is only
/// unique up to multiplication by units.
///
fn extended_ideal_gen(&self, lhs: &Self::Element, rhs: &Self::Element) -> (Self::Element, Self::Element, Self::Element);
///
/// Creates a matrix `A` of unit determinant such that `A * (a, b)^T = (d, 0)`.
/// Returns `(A, d)`.
///
#[stability::unstable(feature = "enable")]
fn create_elimination_matrix(&self, a: &Self::Element, b: &Self::Element) -> ([Self::Element; 4], Self::Element) {
assert!(self.is_commutative());
let old_gcd = self.ideal_gen(a, b);
let new_a = self.checked_div_min(a, &old_gcd).unwrap();
let new_b = self.checked_div_min(b, &old_gcd).unwrap();
let (s, t, gcd_new) = self.extended_ideal_gen(&new_a, &new_b);
debug_assert!(self.is_unit(&gcd_new));
let subtract_factor = self.checked_left_div(&self.sub(self.mul_ref(b, &new_a), self.mul_ref(a, &new_b)), &gcd_new).unwrap();
// this has unit determinant and will map `(a, b)` to `(d, b * new_a - a * new_b)`; after a subtraction step, we are done
let mut result = [s, t, self.negate(new_b), new_a];
let sub1 = self.mul_ref(&result[0], &subtract_factor);
self.sub_assign(&mut result[2], sub1);
let sub2 = self.mul_ref_fst(&result[1], subtract_factor);
self.sub_assign(&mut result[3], sub2);
debug_assert!(self.is_unit(&self.sub(self.mul_ref(&result[0], &result[3]), self.mul_ref(&result[1], &result[2]))));
return (result, gcd_new);
}
///
/// Computes a generator `g` of the ideal `(lhs, rhs) = (g)`, also known as greatest
/// common divisor.
///
/// If you require also a Bezout identiy, i.e. `g = s * lhs + t * rhs`, consider
/// using [`PrincipalIdealRing::extended_ideal_gen()`].
///
fn ideal_gen(&self, lhs: &Self::Element, rhs: &Self::Element) -> Self::Element {
self.extended_ideal_gen(lhs, rhs).2
}
///
/// Computes a generator of the ideal `(lhs) ∩ (rhs)`, also known as least common
/// multiple.
///
/// In other words, computes a ring element `g` such that `lhs, rhs | g` and for every
/// `g'` with this property, have `g | g'`. Note that such an `g` is only unique up to
/// multiplication by units.
///
fn lcm(&self, lhs: &Self::Element, rhs: &Self::Element) -> Self::Element {
self.checked_left_div(&self.mul_ref(lhs, rhs), &self.ideal_gen(lhs, rhs)).unwrap()
}
}
///
/// Trait for [`RingStore`]s that store [`PrincipalIdealRing`]s. Mainly used
/// to provide a convenient interface to the `PrincipalIdealRing`-functions.
///
pub trait PrincipalIdealRingStore: RingStore
where Self::Type: PrincipalIdealRing
{
delegate!{ PrincipalIdealRing, fn checked_div_min(&self, lhs: &El<Self>, rhs: &El<Self>) -> Option<El<Self>> }
delegate!{ PrincipalIdealRing, fn extended_ideal_gen(&self, lhs: &El<Self>, rhs: &El<Self>) -> (El<Self>, El<Self>, El<Self>) }
delegate!{ PrincipalIdealRing, fn ideal_gen(&self, lhs: &El<Self>, rhs: &El<Self>) -> El<Self> }
delegate!{ PrincipalIdealRing, fn annihilator(&self, val: &El<Self>) -> El<Self> }
delegate!{ PrincipalIdealRing, fn lcm(&self, lhs: &El<Self>, rhs: &El<Self>) -> El<Self> }
///
/// Alias for [`PrincipalIdealRingStore::ideal_gen()`].
///
fn gcd(&self, lhs: &El<Self>, rhs: &El<Self>) -> El<Self> {
self.ideal_gen(lhs, rhs)
}
}
impl<R> PrincipalIdealRingStore for R
where R: RingStore,
R::Type: PrincipalIdealRing
{}
///
/// Trait for rings that support euclidean division.
///
/// In other words, there is a degree function d(.)
/// returning nonnegative integers such that for every `x, y`
/// with `y != 0` there are `q, r` with `x = qy + r` and
/// `d(r) < d(y)`. Note that `q, r` do not have to be unique,
/// and implementations are free to use any choice.
///
/// # Example
/// ```
/// # use feanor_math::assert_el_eq;
/// # use feanor_math::ring::*;
/// # use feanor_math::pid::*;
/// # use feanor_math::primitive_int::*;
/// let ring = StaticRing::<i64>::RING;
/// let (q, r) = ring.euclidean_div_rem(14, &6);
/// assert_el_eq!(ring, 14, ring.add(ring.mul(q, 6), r));
/// assert!(ring.euclidean_deg(&r) < ring.euclidean_deg(&6));
/// ```
///
pub trait EuclideanRing: PrincipalIdealRing {
///
/// Computes euclidean division with remainder.
///
/// In general, the euclidean division of `lhs` by `rhs` is a tuple `(q, r)` such that
/// `lhs = q * rhs + r`, and `r` is "smaller" than "rhs". The notion of smallness is
/// given by the smallness of the euclidean degree function [`EuclideanRing::euclidean_deg()`].
///
fn euclidean_div_rem(&self, lhs: Self::Element, rhs: &Self::Element) -> (Self::Element, Self::Element);
///
/// Defines how "small" an element is. For details, see [`EuclideanRing`].
///
fn euclidean_deg(&self, val: &Self::Element) -> Option<usize>;
///
/// Computes euclidean division without remainder.
///
/// In general, the euclidean division of `lhs` by `rhs` is a tuple `(q, r)` such that
/// `lhs = q * rhs + r`, and `r` is "smaller" than "rhs". The notion of smallness is
/// given by the smallness of the euclidean degree function [`EuclideanRing::euclidean_deg()`].
///
fn euclidean_div(&self, lhs: Self::Element, rhs: &Self::Element) -> Self::Element {
self.euclidean_div_rem(lhs, rhs).0
}
///
/// Computes only the remainder of euclidean division.
///
/// In general, the euclidean division of `lhs` by `rhs` is a tuple `(q, r)` such that
/// `lhs = q * rhs + r`, and `r` is "smaller" than "rhs". The notion of smallness is
/// given by the smallness of the euclidean degree function [`EuclideanRing::euclidean_deg()`].
///
fn euclidean_rem(&self, lhs: Self::Element, rhs: &Self::Element) -> Self::Element {
self.euclidean_div_rem(lhs, rhs).1
}
}
///
/// [`RingStore`] for [`EuclideanRing`]s
///
pub trait EuclideanRingStore: RingStore + DivisibilityRingStore
where Self::Type: EuclideanRing
{
delegate!{ EuclideanRing, fn euclidean_div_rem(&self, lhs: El<Self>, rhs: &El<Self>) -> (El<Self>, El<Self>) }
delegate!{ EuclideanRing, fn euclidean_div(&self, lhs: El<Self>, rhs: &El<Self>) -> El<Self> }
delegate!{ EuclideanRing, fn euclidean_rem(&self, lhs: El<Self>, rhs: &El<Self>) -> El<Self> }
delegate!{ EuclideanRing, fn euclidean_deg(&self, val: &El<Self>) -> Option<usize> }
}
impl<R> EuclideanRingStore for R
where R: RingStore, R::Type: EuclideanRing
{}
#[allow(missing_docs)]
#[cfg(any(test, feature = "generic_tests"))]
pub mod generic_tests {
use super::*;
use crate::{algorithms::int_factor::factor, homomorphism::Homomorphism, integer::{int_cast, BigIntRing, IntegerRingStore}, ordered::OrderedRingStore, primitive_int::StaticRing, ring::El};
pub fn test_euclidean_ring_axioms<R: RingStore, I: Iterator<Item = El<R>>>(ring: R, edge_case_elements: I)
where R::Type: EuclideanRing
{
assert!(ring.is_commutative());
assert!(ring.is_noetherian());
let elements = edge_case_elements.collect::<Vec<_>>();
for a in &elements {
for b in &elements {
if ring.is_zero(b) {
continue;
}
let (q, r) = ring.euclidean_div_rem(ring.clone_el(a), b);
assert!(ring.euclidean_deg(b).is_none() || ring.euclidean_deg(&r).unwrap_or(usize::MAX) < ring.euclidean_deg(b).unwrap());
assert_el_eq!(ring, a, ring.add(ring.mul(q, ring.clone_el(b)), r));
}
}
}
pub fn test_principal_ideal_ring_axioms<R: RingStore, I: Iterator<Item = El<R>>>(ring: R, edge_case_elements: I)
where R::Type: PrincipalIdealRing
{
assert!(ring.is_commutative());
assert!(ring.is_noetherian());
let elements = edge_case_elements.collect::<Vec<_>>();
let expected_unit = ring.checked_div_min(&ring.zero(), &ring.zero()).unwrap();
assert!(ring.is_unit(&expected_unit), "checked_div_min() returned a non-minimal quotient {} * {} = {}", ring.format(&expected_unit), ring.format(&ring.zero()), ring.format(&ring.zero()));
let expected_zero = ring.checked_div_min(&ring.zero(), &ring.one()).unwrap();
assert!(ring.is_zero(&expected_zero), "checked_div_min() returned a wrong quotient {} * {} = {}", ring.format(&expected_zero), ring.format(&ring.one()), ring.format(&ring.zero()));
for a in &elements {
let expected_unit = ring.checked_div_min(a, a).unwrap();
assert!(ring.is_unit(&expected_unit), "checked_div_min() returned a non-minimal quotient {} * {} = {}", ring.format(&expected_unit), ring.format(a), ring.format(a));
}
for a in &elements {
for b in &elements {
for c in &elements {
let g1 = ring.mul_ref(a, b);
let g2 = ring.mul_ref(a, c);
let (s, t, g) = ring.extended_ideal_gen(&g1, &g2);
assert!(ring.checked_div(&g, a).is_some(), "Wrong ideal generator: ({}) contains the ideal I = ({}, {}), but extended_ideal_gen() found a generator I = ({}) that does not satisfy {} | {}", ring.format(a), ring.format(&g1), ring.format(&g2), ring.format(&g), ring.format(a), ring.format(&g));
assert_el_eq!(ring, g, ring.add(ring.mul_ref(&s, &g1), ring.mul_ref(&t, &g2)));
}
}
}
for a in &elements {
for b in &elements {
let g1 = ring.mul_ref(a, b);
let g2 = ring.mul_ref_fst(a, ring.add_ref_fst(b, ring.one()));
let (s, t, g) = ring.extended_ideal_gen(&g1, &g2);
assert!(ring.checked_div(&g, a).is_some() && ring.checked_div(a, &g).is_some(), "Expected ideals ({}) and I = ({}, {}) to be equal, but extended_ideal_gen() returned generator {} of I", ring.format(a), ring.format(&g1), ring.format(&g2), ring.format(&g));
assert_el_eq!(ring, g, ring.add(ring.mul_ref(&s, &g1), ring.mul_ref(&t, &g2)));
}
}
let ZZbig = BigIntRing::RING;
let char = ring.characteristic(ZZbig).unwrap();
if !ZZbig.is_zero(&char) && ZZbig.is_leq(&char, &ZZbig.power_of_two(30)) {
let p = factor(ZZbig, ZZbig.clone_el(&char)).into_iter().next().unwrap().0;
let expected = ring.int_hom().map(int_cast(ZZbig.checked_div(&char, &p).unwrap(), StaticRing::<i32>::RING, ZZbig));
let ann_p = ring.annihilator(&ring.int_hom().map(int_cast(p, StaticRing::<i32>::RING, ZZbig)));
assert!(ring.checked_div(&ann_p, &expected).is_some());
assert!(ring.checked_div(&expected, &ann_p).is_some());
}
}
}