feanor-math 3.5.18

A library for number theory, providing implementations for arithmetic in various rings and algorithms working on them.
Documentation
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
use std::cmp::min;
use std::fmt::Debug;

use append_only_vec::AppendOnlyVec;

use crate::computation::*;
use crate::delegate::{UnwrapHom, WrapHom};
use crate::divisibility::{DivisibilityRing, DivisibilityRingStore};
use crate::field::Field;
use crate::homomorphism::Homomorphism;
use crate::local::{PrincipalLocalRing, PrincipalLocalRingStore};
use crate::pid::PrincipalIdealRingStore;
use crate::ring::*;
use crate::rings::multivariate::*;
use crate::seq::*;

#[stability::unstable(feature = "enable")]
#[derive(PartialEq, Clone, Eq, Hash)]
pub enum SPoly {
    Standard(usize, usize),
    Nilpotent(
        // poly index
        usize,
        // power-of-p multiplier
        usize,
    ),
}

impl Debug for SPoly {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SPoly::Standard(i, j) => write!(f, "S({}, {})", i, j),
            SPoly::Nilpotent(i, k) => write!(f, "p^{} F({})", k, i),
        }
    }
}

fn term_xlcm<P>(
    ring: P,
    (l_c, l_m): (&PolyCoeff<P>, &PolyMonomial<P>),
    (r_c, r_m): (&PolyCoeff<P>, &PolyMonomial<P>),
) -> (
    (PolyCoeff<P>, PolyMonomial<P>),
    (PolyCoeff<P>, PolyMonomial<P>),
    (PolyCoeff<P>, PolyMonomial<P>),
)
where
    P: RingStore,
    P::Type: MultivariatePolyRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PrincipalLocalRing,
{
    let d_c = ring.base_ring().ideal_gen(l_c, r_c);
    let m_m = ring.monomial_lcm(ring.clone_monomial(l_m), r_m);
    let l_factor = ring.base_ring().checked_div(r_c, &d_c).unwrap();
    let r_factor = ring.base_ring().checked_div(l_c, &d_c).unwrap();
    let m_c = ring
        .base_ring()
        .mul_ref_snd(ring.base_ring().mul_ref_snd(d_c, &r_factor), &l_factor);
    return (
        (
            l_factor,
            ring.monomial_div(ring.clone_monomial(&m_m), l_m).ok().unwrap(),
        ),
        (
            r_factor,
            ring.monomial_div(ring.clone_monomial(&m_m), r_m).ok().unwrap(),
        ),
        (m_c, m_m),
    );
}

fn term_lcm<P>(
    ring: P,
    (l_c, l_m): (&PolyCoeff<P>, &PolyMonomial<P>),
    (r_c, r_m): (&PolyCoeff<P>, &PolyMonomial<P>),
) -> (PolyCoeff<P>, PolyMonomial<P>)
where
    P: RingStore,
    P::Type: MultivariatePolyRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PrincipalLocalRing,
{
    let d_c = ring.base_ring().ideal_gen(l_c, r_c);
    let m_m = ring.monomial_lcm(ring.clone_monomial(l_m), r_m);
    let l_factor = ring.base_ring().checked_div(r_c, &d_c).unwrap();
    let r_factor = ring.base_ring().checked_div(l_c, &d_c).unwrap();
    let m_c = ring
        .base_ring()
        .mul_ref_snd(ring.base_ring().mul_ref_snd(d_c, &r_factor), &l_factor);
    return (m_c, m_m);
}

impl SPoly {
    #[stability::unstable(feature = "enable")]
    pub fn lcm_term<P, O>(&self, ring: P, basis: &[El<P>], order: O) -> (PolyCoeff<P>, PolyMonomial<P>)
    where
        P: RingStore + Copy,
        P::Type: MultivariatePolyRing,
        <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PrincipalLocalRing,
        O: MonomialOrder + Copy,
    {
        match self {
            SPoly::Standard(i, j) => term_lcm(
                &ring,
                ring.LT(&basis[*i], order).unwrap(),
                ring.LT(&basis[*j], order).unwrap(),
            ),
            Self::Nilpotent(i, k) => {
                let (c, m) = ring.LT(&basis[*i], order).unwrap();
                (
                    ring.base_ring().mul_ref_fst(
                        c,
                        ring.base_ring()
                            .pow(ring.base_ring().clone_el(ring.base_ring().max_ideal_gen()), *k),
                    ),
                    ring.clone_monomial(m),
                )
            }
        }
    }

    #[stability::unstable(feature = "enable")]
    pub fn poly<P, O>(&self, ring: P, basis: &[El<P>], order: O) -> El<P>
    where
        P: RingStore + Copy,
        P::Type: MultivariatePolyRing,
        <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PrincipalLocalRing,
        O: MonomialOrder + Copy,
    {
        match self {
            SPoly::Standard(i, j) => {
                let (f1_factor, f2_factor, _) = term_xlcm(
                    &ring,
                    ring.LT(&basis[*i], order).unwrap(),
                    ring.LT(&basis[*j], order).unwrap(),
                );
                let mut f1_scaled = ring.clone_el(&basis[*i]);
                ring.mul_assign_monomial(&mut f1_scaled, f1_factor.1);
                ring.inclusion().mul_assign_map(&mut f1_scaled, f1_factor.0);
                let mut f2_scaled = ring.clone_el(&basis[*j]);
                ring.mul_assign_monomial(&mut f2_scaled, f2_factor.1);
                ring.inclusion().mul_assign_map(&mut f2_scaled, f2_factor.0);
                return ring.sub(f1_scaled, f2_scaled);
            }
            SPoly::Nilpotent(i, k) => {
                let mut result = ring.clone_el(&basis[*i]);
                ring.inclusion().mul_assign_map(
                    &mut result,
                    ring.base_ring()
                        .pow(ring.base_ring().clone_el(ring.base_ring().max_ideal_gen()), *k),
                );
                return result;
            }
        }
    }
}

#[inline(never)]
fn find_reducer<'a, 'b, P, O, I>(
    ring: P,
    f: &El<P>,
    reducers: I,
    order: O,
) -> Option<(usize, &'a El<P>, PolyCoeff<P>, PolyMonomial<P>)>
where
    P: RingStore + Copy,
    P::Type: MultivariatePolyRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: DivisibilityRing,
    O: MonomialOrder + Copy,
    I: Iterator<Item = (&'a El<P>, &'b ExpandedMonomial)>,
{
    if ring.is_zero(f) {
        return None;
    }
    let (f_lc, f_lm) = ring.LT(f, order).unwrap();
    let f_lm_expanded = ring.expand_monomial(f_lm);
    reducers
        .enumerate()
        .filter_map(|(i, (reducer, reducer_lm_expanded))| {
            if (0..ring.indeterminate_count()).all(|j| reducer_lm_expanded[j] <= f_lm_expanded[j]) {
                let (r_lc, r_lm) = ring.LT(reducer, order).unwrap();
                let quo_m = ring.monomial_div(ring.clone_monomial(f_lm), r_lm).ok().unwrap();
                if let Some(quo_c) = ring.base_ring().checked_div(f_lc, r_lc) {
                    return Some((i, reducer, quo_c, quo_m));
                }
            }
            return None;
        })
        .next()
}

#[inline(never)]
fn filter_spoly<P, O>(ring: P, new_spoly: SPoly, basis: &[El<P>], order: O) -> Option<usize>
where
    P: RingStore + Copy,
    P::Type: MultivariatePolyRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PrincipalLocalRing,
    O: MonomialOrder + Copy,
{
    match new_spoly {
        SPoly::Standard(i, k) => {
            assert!(i < k);
            let (bi_c, bi_m) = ring.LT(&basis[i], order).unwrap();
            let (bk_c, bk_m) = ring.LT(&basis[k], order).unwrap();
            let (S_c, S_m) = term_lcm(ring, (bi_c, bi_m), (bk_c, bk_m));
            let S_c_val = ring.base_ring().valuation(&S_c).unwrap();

            if S_c_val == 0
                && order.eq_mon(
                    ring,
                    &ring.monomial_div(ring.clone_monomial(&S_m), bi_m).ok().unwrap(),
                    bk_m,
                )
            {
                return Some(usize::MAX);
            }

            (0..k)
                .filter_map(|j| {
                    if j == i {
                        return None;
                    }
                    // more experiments needed - for some weird reason, replacing "properly divides"
                    // with "divides" (assuming I didn't make a mistake) leads
                    // to terrible performance
                    let (bj_c, bj_m) = ring.LT(&basis[j], order).unwrap();
                    let (f_c, f_m) = term_lcm(ring, (bj_c, bj_m), (bk_c, bk_m));
                    let f_c_val = ring.base_ring().valuation(&f_c).unwrap();

                    if j < i && order.eq_mon(ring, &f_m, &S_m) && f_c_val <= S_c_val {
                        return Some(j);
                    }
                    if let Ok(quo) = ring.monomial_div(ring.clone_monomial(&S_m), &f_m)
                        && f_c_val <= S_c_val
                        && (f_c_val < S_c_val || ring.monomial_deg(&quo) > 0)
                    {
                        return Some(j);
                    }
                    return None;
                })
                .next()
        }
        SPoly::Nilpotent(i, k) => {
            let nilpotent_power = ring.base_ring().nilpotent_power().unwrap();
            let f = &basis[i];

            let mut smallest_elim_coeff_valuation = usize::MAX;
            let mut current = ring.LT(f, order).unwrap();
            while ring.base_ring().valuation(current.0).unwrap() + k >= nilpotent_power {
                smallest_elim_coeff_valuation = min(
                    smallest_elim_coeff_valuation,
                    ring.base_ring().valuation(current.0).unwrap(),
                );
                let next = ring.largest_term_lt(f, order, current.1);
                if next.is_none() {
                    return Some(usize::MAX);
                }
                current = next.unwrap();
            }
            assert!(
                smallest_elim_coeff_valuation == usize::MAX || smallest_elim_coeff_valuation + k >= nilpotent_power
            );
            if smallest_elim_coeff_valuation == usize::MAX || smallest_elim_coeff_valuation + k > nilpotent_power {
                return Some(usize::MAX);
            } else {
                return None;
            }
        }
    }
}

#[stability::unstable(feature = "enable")]
pub fn default_sort_fn<P, O>(ring: P, order: O) -> impl FnMut(&mut [SPoly], &[El<P>])
where
    P: RingStore + Copy,
    P::Type: MultivariatePolyRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PrincipalLocalRing,
    O: MonomialOrder + Copy,
{
    move |open, basis| {
        open.sort_by_key(|spoly| {
            let (lc, lm) = spoly.lcm_term(ring, basis, order);
            (
                -(ring.base_ring().valuation(&lc).unwrap_or(0) as i64),
                -(ring.monomial_deg(&lm) as i64),
            )
        })
    }
}

#[stability::unstable(feature = "enable")]
pub type ExpandedMonomial = Vec<usize>;

fn augment_lm<P, O>(ring: P, f: El<P>, order: O) -> (El<P>, ExpandedMonomial)
where
    P: RingStore + Copy,
    P::Type: MultivariatePolyRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PrincipalLocalRing,
    O: MonomialOrder,
{
    let exponents = ring.expand_monomial(ring.LT(&f, order).unwrap().1);
    return (f, exponents);
}

/// Computes a Groebner basis of the ideal generated by the input basis w.r.t. the given term
/// ordering.
///
/// For a variant of this function that uses sensible defaults for most parameters, see
/// [`buchberger_simple()`].
///
/// The algorithm proceeds F4-style, i.e. reduces multiple S-polynomials before adding them to the
/// basis. When using a fast polynomial ring implementation (e.g.
/// [`crate::rings::multivariate::multivariate_impl::MultivariatePolyRingImpl`]), this makes the
/// algorithm as efficient as standard F4. Furthermore, the behavior can be modified by passing
/// custom functions for `sort_spolys` and `abort_early_if`.
///
/// - `sort_spolys` should permute the given list of S-polynomials w.r.t. the given basis; this can
///   be used to customize in which order S-polynomials are reduced, which can have huge impact on
///   performance. Note that S-polynomials that are supposed to be reduced first should be put at
///   the end of the list.
/// - `abort_early_if` takes the current basis (unfortunately, currently with some additional
///   information that can be ignored), and can return `true` to abort the GB computation, yielding
///   the current basis. In this case, the basis will in general not be a GB, but can still be
///   useful (e.g. `abort_early_if` might decide that a GB up to a fixed degree is sufficient).
///
/// # Explanation of logging output
///
/// If the passed computation controller accepts the logging, it will receive the following symbols:
///  - `-` means an S-polynomial was reduced to zero
///  - `s` means an S-polynomial reduced to a nonzero value and will be added to the basis at the
///    next opportunity
///  - `b(n)` means that the list of all generated basis polynomials has length `n`
///  - `r(n)` means that the current basis of the ideal has length `n`
///  - `S(n)` means that the algorithm still has to reduce `n` more S-polynomials
///  - `f(n)` means that `n` S-polynomials have, in total, been discarded by using the Buchberger
///    criteria
///  - `{n}` means that the algorithm is currently reducing S-polynomials of degree `n`
///  - `!` means that the algorithm decided to discard all current S-polynomial, and restart the
///    computation with the current basis
#[stability::unstable(feature = "enable")]
pub fn buchberger<P, O, Controller, SortFn, AbortFn>(
    ring: P,
    input_basis: Vec<El<P>>,
    order: O,
    mut sort_spolys: SortFn,
    mut abort_early_if: AbortFn,
    controller: Controller,
) -> Result<Vec<El<P>>, Controller::Abort>
where
    P: RingStore + Copy + Send + Sync,
    El<P>: Send + Sync,
    P::Type: MultivariatePolyRing,
    <P::Type as RingExtension>::BaseRing: Sync,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PrincipalLocalRing,
    O: MonomialOrder + Copy + Send + Sync,
    PolyCoeff<P>: Send + Sync,
    Controller: ComputationController,
    SortFn: FnMut(&mut [SPoly], &[El<P>]),
    AbortFn: FnMut(&[(El<P>, ExpandedMonomial)]) -> bool,
{
    controller.run_computation(
        format_args!(
            "buchberger(len={}, vars={})",
            input_basis.len(),
            ring.indeterminate_count()
        ),
        |controller| {
            // this are the basis polynomials we generated; we only append to this, such that the
            // S-polys remain valid
            let input_basis = inter_reduce(
                &ring,
                input_basis.into_iter().map(|f| augment_lm(ring, f, order)).collect(),
                order,
            )
            .into_iter()
            .map(|(f, _)| f)
            .collect::<Vec<_>>();
            debug_assert!(input_basis.iter().all(|f| !ring.is_zero(f)));

            let nilpotent_power = ring
                .base_ring()
                .nilpotent_power()
                .and_then(|e| if e != 0 { Some(e) } else { None });
            assert!(
                nilpotent_power.is_none()
                    || ring.base_ring().is_zero(&ring.base_ring().pow(
                        ring.base_ring().clone_el(ring.base_ring().max_ideal_gen()),
                        nilpotent_power.unwrap()
                    ))
            );

            let sort_reducers = |reducers: &mut [(El<P>, ExpandedMonomial)]| {
                // I have no idea why, but this order seems to give the best results
                reducers.sort_by(|(lf, _), (rf, _)| {
                    order
                        .compare(ring, ring.LT(lf, order).unwrap().1, ring.LT(rf, order).unwrap().1)
                        .then_with(|| ring.terms(lf).count().cmp(&ring.terms(rf).count()))
                })
            };

            // invariant: `(reducers) = (basis)` and there exists a reduction to zero for every `f`
            // in `basis` modulo `reducers`; reducers are always stored with an expanded
            // version of their leading monomial, in order to simplify divisibility checks
            let mut reducers: Vec<(El<P>, ExpandedMonomial)> = input_basis
                .iter()
                .map(|f| augment_lm(ring, ring.clone_el(f), order))
                .collect::<Vec<_>>();
            sort_reducers(&mut reducers);

            let mut open = Vec::new();
            let mut basis = Vec::new();
            update_basis(
                ring,
                input_basis.into_iter(),
                &mut basis,
                &mut open,
                order,
                nilpotent_power,
                &mut 0,
                &mut sort_spolys,
            );

            let mut current_deg = 0;
            let mut filtered_spolys = 0;
            let mut changed = false;
            loop {
                // reduce all known S-polys of minimal lcm degree; in effect, this is the same as
                // the matrix reduction step during F4
                let spolys_to_reduce_index = open
                    .iter()
                    .enumerate()
                    .rev()
                    .find(|(_, spoly)| ring.monomial_deg(&spoly.lcm_term(ring, &basis, order).1) > current_deg)
                    .map(|(i, _)| i + 1)
                    .unwrap_or(0);
                let spolys_to_reduce = &open[spolys_to_reduce_index..];

                let computation = ShortCircuitingComputation::new();
                let new_polys = AppendOnlyVec::new();
                let new_polys_ref = &new_polys;
                let basis_ref = &basis;
                let reducers_ref = &reducers;

                computation
                    .handle(controller.clone())
                    .join_many(spolys_to_reduce.as_fn().map_fn(move |spoly| {
                        move |handle: ShortCircuitingComputationHandle<(), _>| {
                            let mut f = spoly.poly(ring, basis_ref, order);

                            reduce_poly(
                                ring,
                                &mut f,
                                || reducers_ref.iter().chain(new_polys_ref.iter()).map(|(f, lmf)| (f, lmf)),
                                order,
                            );

                            if !ring.is_zero(&f) {
                                log_progress!(handle, "s");
                                _ = new_polys_ref.push(augment_lm(ring, f, order));
                            } else {
                                log_progress!(handle, "-");
                            }

                            checkpoint!(handle);
                            return Ok(None);
                        }
                    }));

                drop(open.drain(spolys_to_reduce_index..));
                let new_polys = new_polys.into_vec();
                _ = computation.finish()?;

                // process the generated new polynomials
                if new_polys.is_empty() && open.is_empty() {
                    if changed {
                        log_progress!(controller, "!");
                        // this seems necessary, as the invariants for `reducers` don't imply that
                        // it already is a GB; more concretely, reducers
                        // contains polys of basis that are reduced with eath other, but the
                        // S-polys between two of them might not have been considered
                        return buchberger::<P, O, _, _, _>(
                            ring,
                            reducers.into_iter().map(|(f, _)| f).collect(),
                            order,
                            sort_spolys,
                            abort_early_if,
                            controller,
                        );
                    } else {
                        return Ok(reducers.into_iter().map(|(f, _)| f).collect());
                    }
                } else if new_polys.is_empty() {
                    current_deg = ring.monomial_deg(&open.last().unwrap().lcm_term(ring, &basis, order).1);
                    log_progress!(controller, "{{{}}}", current_deg);
                } else {
                    changed = true;
                    current_deg = 0;
                    update_basis(
                        ring,
                        new_polys.iter().map(|(f, _)| ring.clone_el(f)),
                        &mut basis,
                        &mut open,
                        order,
                        nilpotent_power,
                        &mut filtered_spolys,
                        &mut sort_spolys,
                    );
                    log_progress!(
                        controller,
                        "(b={})(S={})(f={})",
                        basis.len(),
                        open.len(),
                        filtered_spolys
                    );

                    reducers.extend(new_polys);
                    reducers = inter_reduce(ring, reducers, order);
                    sort_reducers(&mut reducers);
                    log_progress!(controller, "(r={})", reducers.len());
                    if abort_early_if(&reducers) {
                        log_progress!(controller, "(early_abort)");
                        return Ok(reducers.into_iter().map(|(f, _)| f).collect());
                    }
                }

                // less S-polys if we restart from scratch with reducers
                if open.len() + filtered_spolys
                    > reducers.len() * reducers.len() / 2 + reducers.len() * nilpotent_power.unwrap_or(0) + 1
                {
                    log_progress!(controller, "!");
                    return buchberger::<P, O, _, _, _>(
                        ring,
                        reducers.into_iter().map(|(f, _)| f).collect(),
                        order,
                        sort_spolys,
                        abort_early_if,
                        controller,
                    );
                }
            }
        },
    )
}

fn update_basis<I, P, O, SortFn>(
    ring: P,
    new_polys: I,
    basis: &mut Vec<El<P>>,
    open: &mut Vec<SPoly>,
    order: O,
    nilpotent_power: Option<usize>,
    filtered_spolys: &mut usize,
    sort_spolys: &mut SortFn,
) where
    P: RingStore + Copy,
    P::Type: MultivariatePolyRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: PrincipalLocalRing,
    O: MonomialOrder + Copy,
    SortFn: FnMut(&mut [SPoly], &[El<P>]),
    I: Iterator<Item = El<P>>,
{
    for new_poly in new_polys {
        basis.push(new_poly);
        for i in 0..(basis.len() - 1) {
            let spoly = SPoly::Standard(i, basis.len() - 1);
            if filter_spoly(ring, spoly.clone(), &*basis, order).is_none() {
                open.push(spoly);
            } else {
                *filtered_spolys += 1;
            }
        }
        if let Some(e) = nilpotent_power {
            for k in 1..e {
                let spoly = SPoly::Nilpotent(basis.len() - 1, k);
                if filter_spoly(ring, spoly.clone(), &*basis, order).is_none() {
                    open.push(spoly);
                } else {
                    *filtered_spolys += 1;
                }
            }
        }
    }
    sort_spolys(&mut *open, &*basis);
}

fn reduce_poly<'a, 'b, F, I, P, O>(ring: P, to_reduce: &mut El<P>, mut reducers: F, order: O)
where
    P: 'a + RingStore + Copy,
    P::Type: MultivariatePolyRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: DivisibilityRing,
    O: MonomialOrder + Copy,
    F: FnMut() -> I,
    I: Iterator<Item = (&'a El<P>, &'b ExpandedMonomial)>,
{
    while let Some((_, reducer, quo_c, quo_m)) = find_reducer(ring, to_reduce, reducers(), order) {
        let prev_lm = ring.clone_monomial(ring.LT(to_reduce, order).unwrap().1);
        let mut scaled_reducer = ring.clone_el(reducer);
        ring.mul_assign_monomial(&mut scaled_reducer, ring.clone_monomial(&quo_m));
        ring.inclusion().mul_assign_ref_map(&mut scaled_reducer, &quo_c);
        debug_assert!(
            order.compare(
                ring,
                ring.LT(&scaled_reducer, order).unwrap().1,
                ring.LT(to_reduce, order).unwrap().1
            ) == std::cmp::Ordering::Equal
        );
        ring.sub_assign(to_reduce, scaled_reducer);
        debug_assert!(
            ring.is_zero(to_reduce)
                || order.compare(ring, ring.LT(to_reduce, order).unwrap().1, &prev_lm) == std::cmp::Ordering::Less
        );
    }
}

#[stability::unstable(feature = "enable")]
pub fn multivariate_division<'a, P, O, I>(ring: P, mut f: El<P>, reducers: I, order: O) -> El<P>
where
    P: 'a + RingStore + Copy,
    P::Type: MultivariatePolyRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: DivisibilityRing,
    O: MonomialOrder + Copy,
    I: Clone + Iterator<Item = &'a El<P>>,
{
    let lms = reducers
        .clone()
        .map(|f| ring.expand_monomial(ring.LT(f, order).unwrap().1))
        .collect::<Vec<_>>();
    reduce_poly(ring, &mut f, || reducers.clone().zip(lms.iter()), order);
    return f;
}

fn inter_reduce<P, O>(ring: P, mut polys: Vec<(El<P>, ExpandedMonomial)>, order: O) -> Vec<(El<P>, ExpandedMonomial)>
where
    P: RingStore + Copy,
    P::Type: MultivariatePolyRing,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: DivisibilityRing,
    O: MonomialOrder + Copy,
{
    let mut changed = true;
    while changed {
        changed = false;
        let mut i = 0;
        while i < polys.len() {
            let last_i = polys.len() - 1;
            polys.swap(i, last_i);
            let (reducers, to_reduce) = polys.split_at_mut(last_i);
            let to_reduce = &mut to_reduce[0];

            reduce_poly(
                ring,
                &mut to_reduce.0,
                || reducers.iter().map(|(f, lmf)| (f, lmf)),
                order,
            );

            // undo swap so that the outer loop still iterates over every poly
            if !ring.is_zero(&to_reduce.0) {
                to_reduce.1 = ring.expand_monomial(ring.LT(&to_reduce.0, order).unwrap().1);
                polys.swap(i, last_i);
                i += 1;
            } else {
                _ = polys.pop().unwrap();
            }
        }
    }
    return polys;
}

use crate::rings::local::AsLocalPIR;
use crate::rings::multivariate::multivariate_impl::MultivariatePolyRingImpl;

/// Computes a Groebner basis of the ideal generated by the input basis w.r.t. the given term
/// ordering.
///
/// For a variant of this function that allows for more configuration, see [`buchberger()`].
pub fn buchberger_simple<P, O>(ring: P, input_basis: Vec<El<P>>, order: O) -> Vec<El<P>>
where
    P: RingStore + Copy + Send + Sync,
    El<P>: Send + Sync,
    P::Type: MultivariatePolyRing,
    <P::Type as RingExtension>::BaseRing: Sync,
    <<P::Type as RingExtension>::BaseRing as RingStore>::Type: Field,
    O: MonomialOrder + Copy + Send + Sync,
    PolyCoeff<P>: Send + Sync,
{
    let as_local_pir = AsLocalPIR::from_field(ring.base_ring());
    let new_poly_ring = MultivariatePolyRingImpl::new(&as_local_pir, ring.indeterminate_count());
    let from_ring = new_poly_ring.lifted_hom(ring, WrapHom::to_delegate_ring(as_local_pir.get_ring()));
    let result = buchberger::<_, _, _, _, _>(
        &new_poly_ring,
        input_basis.into_iter().map(|f| from_ring.map(f)).collect(),
        order,
        default_sort_fn(&new_poly_ring, order),
        |_| false,
        DontObserve,
    )
    .unwrap_or_else(no_error);
    let to_ring = ring.lifted_hom(&new_poly_ring, UnwrapHom::from_delegate_ring(as_local_pir.get_ring()));
    return result.into_iter().map(|f| to_ring.map(f)).collect();
}

#[cfg(test)]
use crate::integer::BigIntRing;
#[cfg(test)]
use crate::rings::poly::{PolyRingStore, dense_poly};
#[cfg(test)]
use crate::rings::rational::RationalField;
#[cfg(test)]
use crate::rings::zn::zn_static;

#[test]
fn test_buchberger_small() {
    let base = zn_static::F17;
    let ring = MultivariatePolyRingImpl::new(base, 2);

    let f1 = ring.from_terms(
        [
            (1, ring.create_monomial([2, 0])),
            (1, ring.create_monomial([0, 2])),
            (16, ring.create_monomial([0, 0])),
        ]
        .into_iter(),
    );
    let f2 = ring.from_terms([(1, ring.create_monomial([1, 1])), (15, ring.create_monomial([0, 0]))].into_iter());

    let actual = buchberger(
        &ring,
        vec![ring.clone_el(&f1), ring.clone_el(&f2)],
        DegRevLex,
        default_sort_fn(&ring, DegRevLex),
        |_| false,
        TEST_LOG_PROGRESS,
    )
    .unwrap_or_else(no_error);

    let expected = ring.from_terms(
        [
            (16, ring.create_monomial([0, 3])),
            (15, ring.create_monomial([1, 0])),
            (1, ring.create_monomial([0, 1])),
        ]
        .into_iter(),
    );

    assert_eq!(3, actual.len());
    assert_el_eq!(
        ring,
        ring.zero(),
        multivariate_division(&ring, f1, actual.iter(), DegRevLex)
    );
    assert_el_eq!(
        ring,
        ring.zero(),
        multivariate_division(&ring, f2, actual.iter(), DegRevLex)
    );
    assert_el_eq!(
        ring,
        ring.zero(),
        multivariate_division(&ring, expected, actual.iter(), DegRevLex)
    );
}

#[test]
fn test_buchberger_larger() {
    let base = zn_static::F17;
    let ring = MultivariatePolyRingImpl::new(base, 3);

    let f1 = ring.from_terms(
        [
            (1, ring.create_monomial([2, 1, 1])),
            (1, ring.create_monomial([0, 2, 0])),
            (1, ring.create_monomial([1, 0, 1])),
            (2, ring.create_monomial([1, 0, 0])),
            (1, ring.create_monomial([0, 0, 0])),
        ]
        .into_iter(),
    );
    let f2 = ring.from_terms(
        [
            (1, ring.create_monomial([0, 3, 1])),
            (1, ring.create_monomial([0, 0, 3])),
            (1, ring.create_monomial([1, 1, 0])),
        ]
        .into_iter(),
    );
    let f3 = ring.from_terms(
        [
            (1, ring.create_monomial([1, 0, 2])),
            (1, ring.create_monomial([1, 0, 1])),
            (2, ring.create_monomial([0, 1, 1])),
            (7, ring.create_monomial([0, 0, 0])),
        ]
        .into_iter(),
    );

    let actual = buchberger(
        &ring,
        vec![ring.clone_el(&f1), ring.clone_el(&f2), ring.clone_el(&f3)],
        DegRevLex,
        default_sort_fn(&ring, DegRevLex),
        |_| false,
        TEST_LOG_PROGRESS,
    )
    .unwrap_or_else(no_error);

    let g1 = ring.from_terms(
        [
            (1, ring.create_monomial([0, 4, 0])),
            (8, ring.create_monomial([0, 3, 1])),
            (12, ring.create_monomial([0, 1, 3])),
            (6, ring.create_monomial([0, 0, 4])),
            (1, ring.create_monomial([0, 3, 0])),
            (13, ring.create_monomial([0, 2, 1])),
            (11, ring.create_monomial([0, 1, 2])),
            (10, ring.create_monomial([0, 0, 3])),
            (11, ring.create_monomial([0, 2, 0])),
            (12, ring.create_monomial([0, 1, 1])),
            (6, ring.create_monomial([0, 0, 2])),
            (6, ring.create_monomial([0, 1, 0])),
            (13, ring.create_monomial([0, 0, 1])),
            (9, ring.create_monomial([0, 0, 0])),
        ]
        .into_iter(),
    );

    assert_el_eq!(
        ring,
        ring.zero(),
        multivariate_division(&ring, g1, actual.iter(), DegRevLex)
    );
}

#[test]
fn test_generic_computation() {
    let base = zn_static::F17;
    let ring = MultivariatePolyRingImpl::new(base, 6);
    let poly_ring = dense_poly::DensePolyRing::new(&ring, "X");

    let var_i = |i: usize| {
        ring.create_term(
            base.one(),
            ring.create_monomial((0..ring.indeterminate_count()).map(|j| if i == j { 1 } else { 0 })),
        )
    };
    let X1 = poly_ring.mul(
        poly_ring.from_terms([(var_i(0), 0), (ring.one(), 1)].into_iter()),
        poly_ring.from_terms([(var_i(1), 0), (ring.one(), 1)].into_iter()),
    );
    let X2 = poly_ring.mul(
        poly_ring.add(
            poly_ring.clone_el(&X1),
            poly_ring.from_terms([(var_i(2), 0), (var_i(3), 1)].into_iter()),
        ),
        poly_ring.add(
            poly_ring.clone_el(&X1),
            poly_ring.from_terms([(var_i(4), 0), (var_i(5), 1)].into_iter()),
        ),
    );
    let basis = vec![
        ring.sub_ref_snd(ring.int_hom().map(1), poly_ring.coefficient_at(&X2, 0)),
        ring.sub_ref_snd(ring.int_hom().map(1), poly_ring.coefficient_at(&X2, 1)),
        ring.sub_ref_snd(ring.int_hom().map(1), poly_ring.coefficient_at(&X2, 2)),
    ];

    let start = std::time::Instant::now();
    let gb1 = buchberger(
        &ring,
        basis.iter().map(|f| ring.clone_el(f)).collect(),
        DegRevLex,
        default_sort_fn(&ring, DegRevLex),
        |_| false,
        TEST_LOG_PROGRESS,
    )
    .unwrap_or_else(no_error);
    let end = std::time::Instant::now();

    println!("Computed GB in {} ms", (end - start).as_millis());

    assert_eq!(11, gb1.len());
}

#[test]
fn test_gb_local_ring() {
    let base = AsLocalPIR::from_zn(zn_static::Zn::<16>::RING).unwrap();
    let ring: MultivariatePolyRingImpl<_> = MultivariatePolyRingImpl::new(base, 1);

    let f = ring.from_terms(
        [
            (base.int_hom().map(4), ring.create_monomial([1])),
            (base.one(), ring.create_monomial([0])),
        ]
        .into_iter(),
    );
    let gb = buchberger(
        &ring,
        vec![f],
        DegRevLex,
        default_sort_fn(&ring, DegRevLex),
        |_| false,
        TEST_LOG_PROGRESS,
    )
    .unwrap_or_else(no_error);

    assert_eq!(1, gb.len());
    assert_el_eq!(ring, ring.one(), gb[0]);
}

#[test]
fn test_gb_lex() {
    let ZZ = BigIntRing::RING;
    let QQ = AsLocalPIR::from_field(RationalField::new(ZZ));
    let QQYX = MultivariatePolyRingImpl::new(&QQ, 2);
    let [f, g] = QQYX.with_wrapped_indeterminates(|[Y, X]| {
        [
            1 + X.pow_ref(2) + 2 * Y + (1 + X) * Y.pow_ref(2),
            3 + X + (2 + X) * Y + (1 + X + X.pow_ref(2)) * Y.pow_ref(2),
        ]
    });
    let expected = QQYX.with_wrapped_indeterminates(|[Y, X]| {
        [
            X.pow_ref(8) + 2 * X.pow_ref(7) + 3 * X.pow_ref(6)
                - 5 * X.pow_ref(5)
                - 10 * X.pow_ref(4)
                - 7 * X.pow_ref(3)
                + 8 * X.pow_ref(2)
                + 8 * X
                + 4,
            2 * Y + X.pow_ref(6) + 3 * X.pow_ref(5) + 6 * X.pow_ref(4) + X.pow_ref(3) - 7 * X.pow_ref(2) - 12 * X - 2,
        ]
    });

    let mut gb = buchberger_simple(&QQYX, vec![f, g], Lex);

    assert_eq!(2, gb.len());
    gb.sort_unstable_by_key(|f| QQYX.appearing_indeterminates(f).len());
    for (mut f, mut e) in gb.into_iter().zip(expected.into_iter()) {
        let f_lc_inv = QQ.invert(QQYX.LT(&f, Lex).unwrap().0).unwrap();
        QQYX.inclusion().mul_assign_map(&mut f, f_lc_inv);
        let e_lc_inv = QQ.invert(QQYX.LT(&e, Lex).unwrap().0).unwrap();
        QQYX.inclusion().mul_assign_map(&mut e, e_lc_inv);
        assert_el_eq!(QQYX, e, f);
    }
}

#[cfg(test)]
#[cfg(feature = "parallel")]
static TEST_COMPUTATION_CONTROLLER: ExecuteMultithreaded<LogProgress> = RunMultithreadedLogProgress;
#[cfg(test)]
#[cfg(not(feature = "parallel"))]
static TEST_COMPUTATION_CONTROLLER: LogProgress = TEST_LOG_PROGRESS;

#[ignore]
#[test]
fn test_expensive_gb_1() {
    let base = AsLocalPIR::from_zn(zn_static::Zn::<16>::RING).unwrap();
    let ring: MultivariatePolyRingImpl<_> = MultivariatePolyRingImpl::new(base, 12);

    let system = ring.with_wrapped_indeterminates(|[Y0, Y1, Y2, Y3, Y4, Y5, Y6, Y7, Y8, Y9, Y10, Y11]| {
        [
            Y0 * Y1 * Y2 * Y3.pow_ref(2) * Y4.pow_ref(2)
                + 4 * Y0 * Y1 * Y2 * Y3 * Y4 * Y4 * Y8
                + Y0 * Y1 * Y2 * Y5.pow_ref(2) * Y8.pow_ref(2)
                + Y0 * Y2 * Y3 * Y4 * Y6
                + Y0 * Y1 * Y3 * Y4 * Y7
                + Y0 * Y2 * Y5 * Y6 * Y8
                + Y0 * Y1 * Y5 * Y7 * Y8
                + Y0 * Y2 * Y3 * Y5 * Y10
                + Y0 * Y1 * Y3 * Y5 * Y11
                + Y0 * Y6 * Y7
                + Y3 * Y5 * Y9
                - 4,
            2 * Y0 * Y1 * Y2 * Y3.pow_ref(2) * Y4 * Y5
                + 2 * Y0 * Y1 * Y2 * Y3 * Y5.pow_ref(2) * Y8
                + Y0 * Y2 * Y3 * Y5 * Y6
                + Y0 * Y1 * Y3 * Y5 * Y7
                + 8,
            Y0 * Y1 * Y2 * Y3.pow_ref(2) * Y5.pow_ref(2) - 5,
        ]
    });

    let part_of_result =
        ring.with_wrapped_indeterminates(|[_Y0, Y1, Y2, _Y3, _Y4, _Y5, Y6, Y7, _Y8, _Y9, _Y10, _Y11]| {
            [
                4 * Y2.pow_ref(2) * Y6.pow_ref(2) - 4 * Y1.pow_ref(2) * Y7.pow_ref(2),
                8 * Y2 * Y6 + 8 * Y1 * Y7.clone(),
            ]
        });

    let start = std::time::Instant::now();
    let gb = buchberger(
        &ring,
        system.iter().map(|f| ring.clone_el(f)).collect(),
        DegRevLex,
        default_sort_fn(&ring, DegRevLex),
        |_| false,
        TEST_COMPUTATION_CONTROLLER,
    )
    .unwrap_or_else(no_error);
    let end = std::time::Instant::now();

    println!("Computed GB in {} ms", (end - start).as_millis());

    for f in &part_of_result {
        assert!(ring.is_zero(&multivariate_division(&ring, ring.clone_el(f), gb.iter(), DegRevLex)));
    }

    assert_eq!(108, gb.len());
}

#[test]
#[ignore]
fn test_expensive_gb_2() {
    let base = zn_static::Fp::<7>::RING;
    let ring = MultivariatePolyRingImpl::new(base, 7);

    let basis = ring.with_wrapped_indeterminates_dyn(|[X0, X1, X2, X3, X4, X5, X6]| {
        [
            6 + 2 * X5
                + 2 * X4
                + X6
                + 4 * X0
                + 5 * X6 * X5
                + X6 * X4
                + 3 * X0 * X4
                + 6 * X0 * X6
                + 2 * X0 * X3
                + X0 * X2
                + 4 * X0 * X1
                + 2 * X3 * X4 * X5
                + 4 * X0 * X6 * X5
                + 6 * X0 * X2 * X5
                + 5 * X0 * X6 * X4
                + 2 * X0 * X3 * X4
                + 4 * X0 * X1 * X4
                + X0 * X6.pow_ref(2)
                + 3 * X0 * X3 * X6
                + 5 * X0 * X2 * X6
                + 2 * X0 * X1 * X6
                + X0 * X3.pow_ref(2)
                + 2 * X0 * X2 * X3
                + 3 * X0 * X3 * X4 * X5
                + 4 * X0 * X3 * X6 * X5
                + 3 * X0 * X1 * X6 * X5
                + 3 * X0 * X2 * X3 * X5
                + 3 * X0 * X3 * X6 * X4
                + 2 * X0 * X1 * X6 * X4
                + 2 * X0 * X3.pow_ref(2) * X4
                + 2 * X0 * X2 * X3 * X4
                + 3 * X0 * X3.pow_ref(2) * X4 * X5
                + 4 * X0 * X1 * X3 * X4 * X5
                + X0 * X3.pow_ref(2) * X4.pow_ref(2),
            5 + 4 * X0
                + 6 * X4 * X5
                + 3 * X6 * X5
                + 4 * X0 * X4
                + 3 * X0 * X6
                + 6 * X0 * X3
                + 6 * X0 * X2
                + 6 * X6 * X4 * X5
                + 2 * X0 * X4 * X5
                + 4 * X0 * X6 * X5
                + 3 * X0 * X2 * X5
                + 3 * X0 * X6 * X4
                + 5 * X0 * X3 * X4
                + 6 * X0 * X2 * X4
                + 4 * X0 * X6.pow_ref(2)
                + 3 * X0 * X3 * X6
                + 3 * X0 * X2 * X6
                + 2 * X0 * X6 * X4 * X5
                + 6 * X0 * X3 * X4 * X5
                + 5 * X0 * X1 * X4 * X5
                + 6 * X0 * X6.pow_ref(2) * X5
                + 2 * X0 * X3 * X6 * X5
                + 2 * X0 * X2 * X6 * X5
                + 6 * X0 * X1 * X6 * X5
                + 6 * X0 * X2 * X3 * X5
                + 6 * X0 * X3 * X4.pow_ref(2)
                + 4 * X0 * X6.pow_ref(2) * X4
                + 6 * X0 * X3 * X6 * X4
                + 3 * X0 * X2 * X6 * X4
                + 4 * X0 * X3 * X6 * X4 * X5
                + 5 * X0 * X1 * X6 * X4 * X5
                + 6 * X0 * X3.pow_ref(2) * X4 * X5
                + 5 * X0 * X2 * X3 * X4 * X5
                + 3 * X0 * X3 * X6 * X4.pow_ref(2)
                + 6 * X0 * X3.pow_ref(2) * X4.pow_ref(2) * X5.clone(),
            2 + 2 * X0
                + 4 * X0 * X4
                + 2 * X0 * X6
                + 5 * X0 * X4 * X5
                + 2 * X0 * X6 * X5
                + 4 * X0 * X2 * X5
                + 2 * X0 * X4.pow_ref(2)
                + 4 * X0 * X6 * X4
                + 4 * X0 * X6.pow_ref(2)
                + 2 * X6 * X4 * X5.pow_ref(2)
                + 4 * X0 * X6 * X4 * X5
                + X0 * X3 * X4 * X5
                + X0 * X2 * X4 * X5
                + 3 * X0 * X6.pow_ref(2) * X5
                + 2 * X0 * X3 * X6 * X5
                + 4 * X0 * X2 * X6 * X5
                + 2 * X0 * X6 * X4.pow_ref(2)
                + X0 * X6.pow_ref(2) * X4
                + 3 * X0 * X6 * X4 * X5.pow_ref(2)
                + 2 * X0 * X6.pow_ref(2) * X5.pow_ref(2)
                + 3 * X0 * X2 * X6 * X5.pow_ref(2)
                + X0 * X3 * X4.pow_ref(2) * X5
                + X0 * X6.pow_ref(2) * X4 * X5
                + X0 * X3 * X6 * X4 * X5
                + 6 * X0 * X2 * X6 * X4 * X5
                + 4 * X0 * X6.pow_ref(2) * X4.pow_ref(2)
                + 6 * X0 * X3 * X6 * X4 * X5.pow_ref(2)
                + 4 * X0 * X1 * X6 * X4 * X5.pow_ref(2)
                + 4 * X0 * X2 * X3 * X4 * X5.pow_ref(2)
                + 6 * X0 * X3 * X6 * X4.pow_ref(2) * X5
                + 2 * X0 * X3.pow_ref(2) * X4.pow_ref(2) * X5.pow_ref(2),
            4 + 5 * X0 * X4 * X5
                + 6 * X0 * X6 * X5
                + 5 * X0 * X4.pow_ref(2) * X5
                + 3 * X0 * X6 * X4 * X5
                + 3 * X0 * X6.pow_ref(2) * X5
                + 6 * X0 * X6 * X4 * X5.pow_ref(2)
                + 5 * X0 * X2 * X4 * X5.pow_ref(2)
                + X0 * X6.pow_ref(2) * X5.pow_ref(2)
                + 6 * X0 * X2 * X6 * X5.pow_ref(2)
                + 4 * X0 * X6 * X4.pow_ref(2) * X5
                + 2 * X0 * X6.pow_ref(2) * X4 * X5
                + 5 * X0 * X3 * X4.pow_ref(2) * X5.pow_ref(2)
                + 3 * X0 * X6.pow_ref(2) * X4 * X5.pow_ref(2)
                + 5 * X0 * X3 * X6 * X4 * X5.pow_ref(2)
                + 4 * X0 * X2 * X6 * X4 * X5.pow_ref(2)
                + 6 * X0 * X6.pow_ref(2) * X4.pow_ref(2) * X5
                + 4 * X0 * X3 * X6 * X4.pow_ref(2) * X5.pow_ref(2),
            4 + 4 * X0 * X4.pow_ref(2) * X5.pow_ref(2)
                + X0 * X6 * X4 * X5.pow_ref(2)
                + X0 * X6.pow_ref(2) * X5.pow_ref(2)
                + 5 * X0 * X6 * X4.pow_ref(2) * X5.pow_ref(2)
                + 6 * X0 * X6.pow_ref(2) * X4 * X5.pow_ref(2)
                + 3 * X0 * X6.pow_ref(2) * X4 * X5.pow_ref(3)
                + 4 * X0 * X2 * X6 * X4 * X5.pow_ref(3)
                + 6 * X0 * X6.pow_ref(2) * X4.pow_ref(2) * X5.pow_ref(2)
                + 4 * X0 * X3 * X6 * X4.pow_ref(2) * X5.pow_ref(3),
            5 * X0 * X6 * X4.pow_ref(2) * X5.pow_ref(3)
                + 6 * X0 * X6.pow_ref(2) * X4 * X5.pow_ref(3)
                + 5 * X0 * X6.pow_ref(2) * X4.pow_ref(2) * X5.pow_ref(3),
            2 * X0 * X6.pow_ref(2) * X4.pow_ref(2) * X5.pow_ref(4),
        ]
    });

    let start = std::time::Instant::now();
    let gb = buchberger(
        &ring,
        basis,
        DegRevLex,
        default_sort_fn(&ring, DegRevLex),
        |_| false,
        TEST_COMPUTATION_CONTROLLER,
    )
    .unwrap_or_else(no_error);
    let end = std::time::Instant::now();

    println!("Computed GB in {} ms", (end - start).as_millis());

    assert_eq!(130, gb.len());
}

#[test]
#[ignore]
fn test_groebner_cyclic6() {
    let base = zn_static::Fp::<65537>::RING;
    let ring = MultivariatePolyRingImpl::new(base, 6);

    let cyclic6 = ring.with_wrapped_indeterminates_dyn(|[x, y, z, t, u, v]| {
        [
            x + y + z + t + u + v,
            x * y + y * z + z * t + t * u + x * v + u * v,
            x * y * z + y * z * t + z * t * u + x * y * v + x * u * v + t * u * v,
            x * y * z * t + y * z * t * u + x * y * z * v + x * y * u * v + x * t * u * v + z * t * u * v,
            x * y * z * t * u
                + x * y * z * t * v
                + x * y * z * u * v
                + x * y * t * u * v
                + x * z * t * u * v
                + y * z * t * u * v,
            x * y * z * t * u * v - 1,
        ]
    });

    let start = std::time::Instant::now();
    let gb = buchberger(
        &ring,
        cyclic6,
        DegRevLex,
        default_sort_fn(&ring, DegRevLex),
        |_| false,
        TEST_COMPUTATION_CONTROLLER,
    )
    .unwrap_or_else(no_error);
    let end = std::time::Instant::now();

    println!("Computed GB in {} ms", (end - start).as_millis());
    assert_eq!(45, gb.len());
}

#[test]
#[ignore]
fn test_groebner_cyclic7() {
    let base = zn_static::Fp::<65537>::RING;
    let ring = MultivariatePolyRingImpl::new(base, 7);

    let cyclic7 = ring.with_wrapped_indeterminates_dyn(|[x, y, z, t, u, v, w]| {
        [
            x + y + z + t + u + v + w,
            x * y + y * z + z * t + t * u + u * v + x * w + v * w,
            x * y * z + y * z * t + z * t * u + t * u * v + x * y * w + x * v * w + u * v * w,
            x * y * z * t
                + y * z * t * u
                + z * t * u * v
                + x * y * z * w
                + x * y * v * w
                + x * u * v * w
                + t * u * v * w,
            x * y * z * t * u
                + y * z * t * u * v
                + x * y * z * t * w
                + x * y * z * v * w
                + x * y * u * v * w
                + x * t * u * v * w
                + z * t * u * v * w,
            x * y * z * t * u * v
                + x * y * z * t * u * w
                + x * y * z * t * v * w
                + x * y * z * u * v * w
                + x * y * t * u * v * w
                + x * z * t * u * v * w
                + y * z * t * u * v * w,
            x * y * z * t * u * v * w - 1,
        ]
    });

    let start = std::time::Instant::now();
    let gb = buchberger(
        &ring,
        cyclic7,
        DegRevLex,
        default_sort_fn(&ring, DegRevLex),
        |_| false,
        TEST_COMPUTATION_CONTROLLER,
    )
    .unwrap_or_else(no_error);
    let end = std::time::Instant::now();

    println!("Computed GB in {} ms", (end - start).as_millis());
    assert_eq!(209, gb.len());
}

#[test]
#[ignore]
fn test_groebner_cyclic8() {
    let base = zn_static::Fp::<65537>::RING;
    let ring = MultivariatePolyRingImpl::new(base, 8);

    let cyclic7 = ring.with_wrapped_indeterminates_dyn(|[x, y, z, s, t, u, v, w]| {
        [
            x + y + z + s + t + u + v + w,
            x * y + y * z + z * s + s * t + t * u + u * v + x * w + v * w,
            x * y * z + y * z * s + z * s * t + s * t * u + t * u * v + x * y * w + x * v * w + u * v * w,
            x * y * z * s
                + y * z * s * t
                + z * s * t * u
                + s * t * u * v
                + x * y * z * w
                + x * y * v * w
                + x * u * v * w
                + t * u * v * w,
            x * y * z * s * t
                + y * z * s * t * u
                + z * s * t * u * v
                + x * y * z * s * w
                + x * y * z * v * w
                + x * y * u * v * w
                + x * t * u * v * w
                + s * t * u * v * w,
            x * y * z * s * t * u
                + y * z * s * t * u * v
                + x * y * z * s * t * w
                + x * y * z * s * v * w
                + x * y * z * u * v * w
                + x * y * t * u * v * w
                + x * s * t * u * v * w
                + z * s * t * u * v * w,
            x * y * z * s * t * u * v
                + x * y * z * s * t * u * w
                + x * y * z * s * t * v * w
                + x * y * z * s * u * v * w
                + x * y * z * t * u * v * w
                + x * y * s * t * u * v * w
                + x * z * s * t * u * v * w
                + y * z * s * t * u * v * w,
            x * y * z * s * t * u * v * w - 1,
        ]
    });

    let start = std::time::Instant::now();
    let gb = buchberger(
        &ring,
        cyclic7,
        DegRevLex,
        default_sort_fn(&ring, DegRevLex),
        |_| false,
        TEST_COMPUTATION_CONTROLLER,
    )
    .unwrap_or_else(no_error);
    let end = std::time::Instant::now();

    println!("Computed GB in {} ms", (end - start).as_millis());
    assert_eq!(372, gb.len());
}