feanor_math/rings/extension/
mod.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
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
use std::alloc::Global;
use std::cmp::min;

use crate::algorithms::linsolve::smith::determinant_using_pre_smith;
use crate::algorithms::linsolve::LinSolveRing;
use crate::algorithms::linsolve::LinSolveRingStore;
use crate::algorithms::matmul::ComputeInnerProduct;
use crate::algorithms::poly_factor::FactorPolyField;
use crate::divisibility::DivisibilityRing;
use crate::matrix::OwnedMatrix;
use crate::field::*;
use crate::pid::PrincipalIdealRing;
use crate::ring::*;
use crate::seq::*;
use crate::homomorphism::*;
use crate::wrapper::RingElementWrapper;
use super::field::AsField;
use super::field::AsFieldBase;
use super::poly::dense_poly::DensePolyRing;
use super::poly::{PolyRingStore, PolyRing};

///
/// Contains [`extension_impl::FreeAlgebraImpl`], an implementation of [`FreeAlgebra`] based
/// on polynomial division.
///
pub mod extension_impl;

///
/// Contains [`galois_field::GaloisField`], an implementation of Galois fields.
///
pub mod galois_field;

pub mod number_field;

///
/// A table of Conway polynomials, for standardized creation of finite fields.
///
pub mod conway;

///
/// A ring `R` that is an extension of a base ring `S`, generated by a single element
/// that is algebraic resp. integral over `S`.
///
/// This is equivalent to rings generated by a single element that is a zero of a monic polynomial over the
/// base ring. While sounding quite technical, this includes a wide class of important rings, like number
/// fields or galois fields.
/// One consequence of this is that `R` is a free `S`-module, with a basis given by the powers
/// of [`FreeAlgebra::canonical_gen()`], which is where the name "free" comes from.
///
/// The main implementation is [`extension_impl::FreeAlgebraImpl`].
///
/// # Nontrivial Automorphisms
///
/// Rings of this form very often have nontrivial automorphisms. In order to simplify situations
/// where morphisms or other objects are only unique up to isomorphism, canonical morphisms between rings
/// of this type must also preserve the canonical generator.
///
/// # Examples
/// One of the most common use cases seems to be the implementation of finite fields (sometimes
/// called galois fields).
/// ```
/// #![feature(allocator_api)]
/// # use std::alloc::Global;
/// # use feanor_math::assert_el_eq;
/// # use feanor_math::ring::*;
/// # use feanor_math::rings::zn::*;
/// # use feanor_math::primitive_int::*;
/// # use feanor_math::rings::extension::*;
/// # use feanor_math::rings::extension::extension_impl::*;
/// # use feanor_math::algorithms::convolution::*;
/// # use feanor_math::field::FieldStore;
/// # use feanor_math::divisibility::*;
/// # use feanor_math::rings::finite::*;
/// // we have to decide for an implementation of the prime field
/// let prime_field = zn_static::Fp::<3>::RING;
/// let galois_field = FreeAlgebraImpl::new(prime_field, 3, [2, 1]);
/// // this is now the finite field with 27 elements, or F_27 or GF(27) since X^3 + 2X + 1 is irreducible modulo 3
/// let galois_field = galois_field.as_field().ok().unwrap();
/// assert_eq!(Some(27), galois_field.size(&StaticRing::<i64>::RING));
/// for x in galois_field.elements() {
///     if !galois_field.is_zero(&x) {
///         let inv_x = galois_field.div(&galois_field.one(), &x);
///         assert_el_eq!(galois_field, galois_field.one(), galois_field.mul(x, inv_x));
///     }
/// }
/// // since galois fields are so important, an efficient construction is provided by feanor-math;
/// // this is the new impl, the old one is instead available under `self::galois_field::galois_field_dyn()`
/// let galois_field_2 = galois_field::GaloisField::new_with(prime_field, 3, Global, STANDARD_CONVOLUTION);
/// // note that the generating polynomial might be different, so it is not necessarily the "same" ring
/// assert!(galois_field_2.can_iso(&galois_field).is_none());
/// ```
///
pub trait FreeAlgebra: RingExtension {

    type VectorRepresentation<'a>: VectorFn<El<Self::BaseRing>>
        where Self: 'a;

    ///
    /// Returns the fixed element that generates this ring as a free module over the base ring.
    ///
    fn canonical_gen(&self) -> Self::Element;

    ///
    /// Returns the rank of this ring as a free module over the base ring.
    ///
    fn rank(&self) -> usize;

    ///
    /// Returns the representation of the element w.r.t. the canonical basis, that is the basis given
    /// by the powers `x^i` where `x` is the canonical generator given by [`FreeAlgebra::canonical_gen()`]
    /// and `i` goes from `0` to `rank - 1`.
    ///
    /// In this sense, this is the opposite function to [`FreeAlgebra::from_canonical_basis()`].
    ///
    fn wrt_canonical_basis<'a>(&'a self, el: &'a Self::Element) -> Self::VectorRepresentation<'a>;

    ///
    /// Returns the element that has the given representation w.r.t. the canonical basis, that is the basis given
    /// by the powers `x^i` where `x` is the canonical generator given by [`FreeAlgebra::canonical_gen()`]
    /// and `i` goes from `0` to `rank - 1`.
    ///
    /// In this sense, this is the opposite function to [`FreeAlgebra::wrt_canonical_basis()`].
    ///
    fn from_canonical_basis<V>(&self, vec: V) -> Self::Element
        where V: IntoIterator<Item = El<Self::BaseRing>>,
            V::IntoIter: DoubleEndedIterator
    {
        let mut given_len = 0;
        let x = self.canonical_gen();
        let mut result = self.zero();
        for c in vec.into_iter().rev() {
            self.mul_assign_ref(&mut result, &x);
            self.add_assign(&mut result, self.from(c));
            given_len += 1;
        }
        assert_eq!(given_len, self.rank());
        return result;
    }

    ///
    /// Like [`FreeAlgebra::from_canonical_basis()`], this computes the sum `sum_i vec[i] * x^i` where `x` is the
    /// canonical generator given by [`FreeAlgebra::canonical_gen()`]. Unlike [`FreeAlgebra::from_canonical_basis()`],
    /// `vec` can return any number elements.
    /// 
    fn from_canonical_basis_extended<V>(&self, vec: V) -> Self::Element
        where V: IntoIterator<Item = El<Self::BaseRing>>
    {
        default_implementations::from_canonical_basis_extended(self, vec)
    }

    fn charpoly<P, H>(&self, el: &Self::Element, poly_ring: P, hom: H) -> El<P>
        where P: RingStore,
            P::Type: PolyRing,
            <<P::Type as RingExtension>::BaseRing as RingStore>::Type: LinSolveRing,
            H: Homomorphism<<Self::BaseRing as RingStore>::Type, <<P::Type as RingExtension>::BaseRing as RingStore>::Type>
    {
        default_implementations::charpoly(self, el, poly_ring, hom)
    }

    ///
    /// Computes the trace of an element `a` in this ring extension, which is defined as the
    /// matrix trace of the multiplication-by-`a` map.
    /// 
    /// In nice extensions, the trace has many characterizations. For example, in a Galois
    /// field extension, it is the sum of `sigma(a)` as `sigma` runs through the Galois group 
    /// of the extension.
    /// 
    fn trace(&self, el: Self::Element) -> El<Self::BaseRing> {
        let mut current = el;
        let generator = self.canonical_gen();
        return self.base_ring().sum((0..self.rank()).map(|i| {
            let result = self.wrt_canonical_basis(&current).at(i);
            self.mul_assign_ref(&mut current, &generator);
            return result;
        }));
    }

    ///
    /// Computes the discriminant of the canonical basis of this ring extension, 
    /// which is defined as the determinant of the trace matrix `(Tr(a^(i + j)))`, 
    /// where `a` is the canonical generator of this ring extension.
    /// 
    /// Note that the discriminant in this sense depends on the choice of the canonical 
    /// generator. In particular, this is usually different from the discriminant of an
    /// algebraic number field, since that is defined as the discriminant w.r.t. the basis
    /// that generates the maximal order. On the other hand, this means that if this ring
    /// is an order in number field, this discriminant is exactly the discriminant of the
    /// order as considered in algebraic number theory.
    /// 
    fn discriminant(&self) -> El<Self::BaseRing>
        where <Self::BaseRing as RingStore>::Type: PrincipalIdealRing
    {
        default_implementations::discriminant(self)
    }
}

///
/// [`RingStore`] for [`FreeAlgebra`].
/// 
pub trait FreeAlgebraStore: RingStore
    where Self::Type: FreeAlgebra
{
    delegate!{ FreeAlgebra, fn canonical_gen(&self) -> El<Self> }
    delegate!{ FreeAlgebra, fn rank(&self) -> usize }
    delegate!{ FreeAlgebra, fn trace(&self, el: El<Self>) -> El<<Self::Type as RingExtension>::BaseRing> }

    ///
    /// See [`FreeAlgebra::wrt_canonical_basis()`].
    ///
    fn wrt_canonical_basis<'a>(&'a self, el: &'a El<Self>) -> <Self::Type as FreeAlgebra>::VectorRepresentation<'a> {
        self.get_ring().wrt_canonical_basis(el)
    }

    ///
    /// See [`FreeAlgebra::from_canonical_basis()`].
    ///
    fn from_canonical_basis<V>(&self, vec: V) -> El<Self>
        where V: IntoIterator<Item = El<<Self::Type as RingExtension>::BaseRing>>,
            V::IntoIter: DoubleEndedIterator
    {
        self.get_ring().from_canonical_basis(vec)
    }

    ///
    /// See [`FreeAlgebra::from_canonical_basis_extended()`].
    ///
    fn from_canonical_basis_extended<V>(&self, vec: V) -> El<Self>
        where V: IntoIterator<Item = El<<Self::Type as RingExtension>::BaseRing>>
    {
        self.get_ring().from_canonical_basis_extended(vec)
    }

    ///
    /// Returns the generating polynomial of this ring, i.e. the monic polynomial `f(X)` such that this ring is isomorphic
    /// to `R[X]/(f(X))`, where `R` is the base ring.
    ///
    fn generating_poly<P, H>(&self, poly_ring: P, hom: H) -> El<P>
        where P: PolyRingStore,
            P::Type: PolyRing,
            H: Homomorphism<<<Self::Type as RingExtension>::BaseRing as RingStore>::Type, <<P::Type as RingExtension>::BaseRing as RingStore>::Type>
    {
        assert!(hom.domain().get_ring() == self.base_ring().get_ring());
        poly_ring.sub(
            poly_ring.from_terms([(poly_ring.base_ring().one(), self.rank())].into_iter()),
            self.poly_repr(&poly_ring, &self.pow(self.canonical_gen(), self.rank()), hom)
        )
    }

    ///
    /// If this ring is a field, returns a wrapper around this ring that implements [`crate::field::FieldStore`].
    ///
    /// For details, see [`crate::rings::field::AsField`].
    ///
    fn as_field(self) -> Result<AsField<Self>, Self>
        where Self::Type: DivisibilityRing,
            <<Self::Type as RingExtension>::BaseRing as RingStore>::Type: Field + FactorPolyField
    {
        let poly_ring = DensePolyRing::new(self.base_ring(), "X");
        if <_ as FactorPolyField>::factor_poly(&poly_ring, &self.generating_poly(&poly_ring, self.base_ring().identity())).0.len() > 1 {
            return Err(self);
        } else {
            return Ok(RingValue::from(AsFieldBase::promise_is_perfect_field(self)));
        }
    }

    ///
    /// Returns the polynomial representation of the given element `y`, i.e. the polynomial `f(X)` of degree at most
    /// [`FreeAlgebraStore::rank()`] such that `f(x) = y`, where `y` is the canonical generator of this ring, as given by
    /// [`FreeAlgebraStore::canonical_gen()`].
    ///
    fn poly_repr<P, H>(&self, to: P, el: &El<Self>, hom: H) -> El<P>
        where P: PolyRingStore,
            P::Type: PolyRing,
            H: Homomorphism<<<Self::Type as RingExtension>::BaseRing as RingStore>::Type, <<P::Type as RingExtension>::BaseRing as RingStore>::Type>
    {
        let coeff_vec = self.wrt_canonical_basis(el);
        to.from_terms(
            (0..self.rank()).map(|i| coeff_vec.at(i)).enumerate()
                .filter(|(_, x)| !self.base_ring().is_zero(x))
                .map(|(j, x)| (hom.map(x), j))
        )
    }
    
    ///
    /// Computes the discriminant of the canonical basis of this ring extension, 
    /// which is defined as the determinant of the trace matrix `(Tr(a^(i + j)))`, 
    /// where `a` is the canonical generator of this ring extension.
    /// 
    /// See also [`FreeAlgebra::discriminant()`].
    /// 
    fn discriminant(&self) -> El<<Self::Type as RingExtension>::BaseRing>
        where <<Self::Type as RingExtension>::BaseRing as RingStore>::Type: PrincipalIdealRing
    {
        self.get_ring().discriminant()
    }

    /// 
    /// See also [`FreeAlgebra::charpoly()`].
    /// 
    fn charpoly<P, H>(&self, el: &El<Self>, poly_ring: P, hom: H) -> El<P>
        where P: RingStore,
            P::Type: PolyRing,
            <<P::Type as RingExtension>::BaseRing as RingStore>::Type: LinSolveRing,
            H: Homomorphism<<<Self::Type as RingExtension>::BaseRing as RingStore>::Type, <<P::Type as RingExtension>::BaseRing as RingStore>::Type>
    {
        self.get_ring().charpoly(el, poly_ring, hom)
    }

    #[stability::unstable(feature = "enable")]
    fn with_wrapped_generator<'a, F, const M: usize>(&'a self, f: F) -> [El<Self>; M]
        where F: FnOnce(&RingElementWrapper<&'a Self>) -> [RingElementWrapper<&'a Self>; M]
    {
        let wrapped_indet = RingElementWrapper::new(self, self.canonical_gen());
        let mut result_it = f(&wrapped_indet).into_iter();
        return std::array::from_fn(|_| result_it.next().unwrap().unwrap());
    }
}

///
/// We define the default implementations here and not directly in the trait
/// to facilitate testing of default implementations, even if the used ring
/// implementation overrides the default implementation.
/// 
mod default_implementations {
    use super::*;

    ///
    /// Default impl for [`FreeAlgebra::from_canonical_basis_extended()`]
    /// 
    pub(super) fn from_canonical_basis_extended<R, V>(ring: &R, vec: V) -> R::Element
        where R: ?Sized + FreeAlgebra,
            V: IntoIterator<Item = El<<R as RingExtension>::BaseRing>>
    {
        let mut data = vec.into_iter().collect::<Vec<_>>();
        let power_of_canonical_gen = ring.mul(
            ring.from_canonical_basis((1..ring.rank()).map(|_| ring.base_ring().zero()).chain([ring.base_ring().one()].into_iter())),
            ring.canonical_gen()
        );
        let mut current_power = ring.one();
        return <_ as ComputeInnerProduct>::inner_product(ring, (0..).map_while(|_| {
            if data.len() == 0 {
                return None;
            }
            let taken_elements = min(data.len(), ring.rank());
            let chunk = data.drain(..taken_elements).chain((taken_elements..ring.rank()).map(|_| ring.base_ring().zero()));
            let current = ring.from_canonical_basis(chunk);
            let result = (current, ring.clone_el(&current_power));
            ring.mul_assign_ref(&mut current_power, &power_of_canonical_gen);
            return Some(result);
        }));
    }

    ///
    /// Default impl for [`FreeAlgebra::charpoly()`]
    /// 
    pub(super) fn charpoly<R, P, H>(ring: &R, el: &R::Element, poly_ring: P, hom: H) -> El<P>
        where R: ?Sized + FreeAlgebra,
            P: RingStore,
            P::Type: PolyRing,
            <<P::Type as RingExtension>::BaseRing as RingStore>::Type: LinSolveRing,
            H: Homomorphism<<R::BaseRing as RingStore>::Type, <<P::Type as RingExtension>::BaseRing as RingStore>::Type>
    {
        assert!(!ring.is_zero(el));
        let base_ring = hom.codomain();
        let mut lhs = OwnedMatrix::zero(ring.rank(), ring.rank(), &base_ring);
        let mut current = ring.one();
        for j in 0..ring.rank() {
            let wrt_basis = ring.wrt_canonical_basis(&current);
            for i in 0..ring.rank() {
                *lhs.at_mut(i, j) = hom.map(wrt_basis.at(i));
            }
            drop(wrt_basis);
            ring.mul_assign_ref(&mut current, el);
        }
        let mut rhs = OwnedMatrix::zero(ring.rank(), 1, &base_ring);
        let wrt_basis = ring.wrt_canonical_basis(&current);
        for i in 0..ring.rank() {
            *rhs.at_mut(i, 0) = base_ring.negate(hom.map(wrt_basis.at(i)));
        }
        let mut sol = OwnedMatrix::zero(ring.rank(), 1, &base_ring);
        <_ as LinSolveRingStore>::solve_right(base_ring, lhs.data_mut(), rhs.data_mut(), sol.data_mut()).assert_solved();

        return poly_ring.from_terms((0..ring.rank()).map(|i| (base_ring.clone_el(sol.at(i, 0)), i)).chain([(base_ring.one(), ring.rank())].into_iter()));
    }
    
    ///
    /// Default impl for [`FreeAlgebra::discriminant()`]
    /// 
    pub(super) fn discriminant<R>(ring: &R) -> El<R::BaseRing>
        where R: ?Sized + FreeAlgebra,
            <R::BaseRing as RingStore>::Type: PrincipalIdealRing
    {
        let mut current = ring.one();
        let generator = ring.canonical_gen();
        let traces = (0..(2 * ring.rank())).map(|_| {
            let result = ring.trace(ring.clone_el(&current));
            ring.mul_assign_ref(&mut current, &generator);
            return result;
        }).collect::<Vec<_>>();
        let mut matrix = OwnedMatrix::from_fn(ring.rank(), ring.rank(), |i, j| ring.base_ring().clone_el(&traces[i + j]));
        let result = determinant_using_pre_smith(ring.base_ring(), matrix.data_mut(), Global);
        return result;
    }
}

#[stability::unstable(feature = "enable")]
pub fn create_multiplication_matrix<R: FreeAlgebraStore>(ring: R, el: &El<R>) -> OwnedMatrix<El<<R::Type as RingExtension>::BaseRing>>
    where R::Type: FreeAlgebra
{
    let mut result = OwnedMatrix::zero(ring.rank(), ring.rank(), ring.base_ring());
    let mut current = ring.clone_el(el);
    let gen = ring.canonical_gen();
    for i in 0..ring.rank() {
        {
            let current_basis_repr = ring.wrt_canonical_basis(&current);
            for j in 0..ring.rank() {
                *result.at_mut(j, i) = current_basis_repr.at(j);
            }
        }
        ring.mul_assign_ref(&mut current, &gen);
    }
    return result;
}

impl<R: RingStore> FreeAlgebraStore for R
    where R::Type: FreeAlgebra
{}

#[cfg(any(test, feature = "generic_tests"))]
pub mod generic_tests {
    use super::*;

    pub fn test_free_algebra_axioms<R: FreeAlgebraStore>(ring: R)
        where R::Type: FreeAlgebra
    {
        let x = ring.canonical_gen();
        let n = ring.rank();

        let xn_original = ring.pow(ring.clone_el(&x), n);
        let xn_vec = ring.wrt_canonical_basis(&xn_original);
        let xn = ring.sum(Iterator::map(0..n, |i| ring.mul(ring.inclusion().map(xn_vec.at(i)), ring.pow(ring.clone_el(&x), i))));
        assert_el_eq!(ring, xn_original, xn);

        let x_n_1_vec_expected = (0..n).map_fn(|i| if i > 0 {
            ring.base_ring().add(ring.base_ring().mul(xn_vec.at(n - 1), xn_vec.at(i)), xn_vec.at(i - 1))
        } else {
            ring.base_ring().mul(xn_vec.at(n - 1), xn_vec.at(0))
        });
        let x_n_1 = ring.pow(ring.clone_el(&x), n + 1);
        let x_n_1_vec_actual = ring.wrt_canonical_basis(&x_n_1);
        for i in 0..n {
            assert_el_eq!(ring.base_ring(), x_n_1_vec_expected.at(i), x_n_1_vec_actual.at(i));
        }

        // test basis wrt_root_of_unity_basis linearity and compatibility from_root_of_unity_basis/wrt_root_of_unity_basis
        for i in (0..ring.rank()).step_by(5) {
            for j in (1..ring.rank()).step_by(7) {
                if i == j {
                    continue;
                }
                let element = ring.from_canonical_basis((0..n).map(|k| if k == i { ring.base_ring().one() } else if k == j { ring.base_ring().int_hom().map(2) } else { ring.base_ring().zero() }));
                let expected = ring.add(ring.pow(ring.clone_el(&x), i), ring.int_hom().mul_map(ring.pow(ring.clone_el(&x), j), 2));
                assert_el_eq!(ring, expected, element);
                let element_vec = ring.wrt_canonical_basis(&expected);
                for k in 0..ring.rank() {
                    if k == i {
                        assert_el_eq!(ring.base_ring(), ring.base_ring().one(), element_vec.at(k));
                    } else if k == j {
                        assert_el_eq!(ring.base_ring(), ring.base_ring().int_hom().map(2), element_vec.at(k));
                    } else {
                        assert_el_eq!(ring.base_ring(), ring.base_ring().zero(), element_vec.at(k));
                    }
                }
            }
        }
    }
}

#[cfg(test)]
use crate::primitive_int::StaticRing;
#[cfg(test)]
use extension_impl::FreeAlgebraImpl;
#[cfg(test)]
use crate::rings::rational::RationalField;

#[test]
fn test_charpoly() {
    let ring = FreeAlgebraImpl::new(StaticRing::<i64>::RING, 3, [2, 0, 0]);
    let poly_ring = DensePolyRing::new(StaticRing::<i64>::RING, "X");

    let [expected] = poly_ring.with_wrapped_indeterminate(|X| [X.pow_ref(3) - 2]);
    assert_el_eq!(&poly_ring, &expected, default_implementations::charpoly(ring.get_ring(), &ring.canonical_gen(), &poly_ring, &ring.base_ring().identity()));

    let [expected] = poly_ring.with_wrapped_indeterminate(|X| [X.pow_ref(3) - 4]);
    assert_el_eq!(&poly_ring, &expected, default_implementations::charpoly(ring.get_ring(), &ring.pow(ring.canonical_gen(), 2), &poly_ring, &ring.base_ring().identity()));

    let [expected] = poly_ring.with_wrapped_indeterminate(|X| [X.pow_ref(3) - 6 * X - 6]);
    assert_el_eq!(&poly_ring, &expected, default_implementations::charpoly(ring.get_ring(), &ring.add(ring.canonical_gen(), ring.pow(ring.canonical_gen(), 2)), &poly_ring, &ring.base_ring().identity()));
}

#[test]
fn test_trace() {
    let ring = FreeAlgebraImpl::new(StaticRing::<i64>::RING, 3, [2, 0, 0]);

    assert_eq!(3, ring.trace(ring.from_canonical_basis([1, 0, 0])));
    assert_eq!(0, ring.trace(ring.from_canonical_basis([0, 1, 0])));
    assert_eq!(0, ring.trace(ring.from_canonical_basis([0, 0, 1])));
    assert_eq!(6, ring.trace(ring.from_canonical_basis([2, 0, 0])));
    assert_eq!(6, ring.trace(ring.from_canonical_basis([2, 1, 0])));
    assert_eq!(6, ring.trace(ring.from_canonical_basis([2, 0, 1])));
}

#[test]
fn test_discriminant() {
    let ring = FreeAlgebraImpl::new(StaticRing::<i64>::RING, 3, [2, 0, 0]);
    assert_eq!(-108, default_implementations::discriminant(ring.get_ring()));

    let ring = FreeAlgebraImpl::new(StaticRing::<i64>::RING, 3, [2, 1, 0]);
    assert_eq!(-104, default_implementations::discriminant(ring.get_ring()));
    
    let ring = FreeAlgebraImpl::new(StaticRing::<i64>::RING, 3, [3, 0, 0]);
    assert_eq!(-243, default_implementations::discriminant(ring.get_ring()));

    let base_ring = DensePolyRing::new(RationalField::new(StaticRing::<i64>::RING), "X");
    let [f] = base_ring.with_wrapped_indeterminate(|X| [X.pow_ref(3) + 1]);
    let ring = FreeAlgebraImpl::new(&base_ring, 2, [f, base_ring.zero()]);
    let [expected] = base_ring.with_wrapped_indeterminate(|X| [4 * X.pow_ref(3) + 4]);
    assert_el_eq!(&base_ring, expected, default_implementations::discriminant(ring.get_ring()));
}

#[test]
fn test_from_canonical_basis_extended() {
    let ring = FreeAlgebraImpl::new(StaticRing::<i64>::RING, 3, [2]);
    let actual = default_implementations::from_canonical_basis_extended(ring.get_ring(), [1, 2, 3, 4, 5, 6, 7]);
    let expected = ring.from_canonical_basis([37, 12, 15]);
    assert_el_eq!(&ring, expected, actual);
}