source: git/kernel/tgb.cc @ 835d83

spielwiese
Last change on this file since 835d83 was 341696, checked in by Hans Schönemann <hannes@…>, 14 years ago
Adding Id property to all files git-svn-id: file:///usr/local/Singular/svn/trunk@12231 2c84dea3-7e68-4137-9b89-c4e89433aadc
  • Property mode set to 100644
File size: 103.6 KB
Line 
1//! \file tgb.cc
2//       multiple rings
3//       shorten_tails und dessen Aufrufe pruefen wlength!!!
4/****************************************
5*  Computer Algebra System SINGULAR     *
6****************************************/
7/* $Id$ */
8/*
9* ABSTRACT: slimgb and F4 implementation
10*/
11//#include <vector>
12//using namespace std;
13
14
15///@TODO: delay nur auf Sugarvergr?erung
16///@TODO: grade aus ecartS, setze dazu strat->honey; und nutze p.ecart
17///@TODO: no tail reductions in syz comp
18#include "mod2.h"
19#include "tgb.h"
20#include "tgb_internal.h"
21#include "tgbgauss.h"
22
23#include "digitech.h"
24#include "gring.h"
25#include "sca.h"
26#include "prCopy.h"
27#include "longrat.h"
28#include "modulop.h"
29#include <stdlib.h>
30#include <stdio.h>
31#include <queue>
32#define BUCKETS_FOR_NORO_RED 1
33#define SR_HDL(A) ((long)(A))
34static const int bundle_size=100;
35static const int bundle_size_noro=10000;
36static const int delay_factor=3;
37int QlogSize(number n);
38#define ADD_LATER_SIZE 500
39#if 1
40static omBin lm_bin=NULL;
41
42static void simplify_poly(poly p, ring r) {
43     assume(r==currRing);
44     if (!rField_is_Zp(r))
45     {
46        pCleardenom(p);
47        pContent(p); //is a duplicate call, but belongs here
48     }
49     else
50       pNorm(p);
51}
52//static const BOOLEAN up_to_radical=TRUE;
53
54int slim_nsize(number n, ring r)
55{
56  if (rField_is_Zp(r))
57  {
58    return 1;
59  }
60  if (rField_is_Q(r))
61  {
62    return QlogSize(n);
63  }
64  else
65  {
66    return n_Size(n,r);
67  }
68}
69static BOOLEAN monomial_root(poly m, ring r){
70    BOOLEAN changed=FALSE;
71    int i;
72    for(i=1;i<=rVar(r);i++){
73        int e=p_GetExp(m,i,r);
74        if (e>1){
75            p_SetExp(m,i,1,r);
76            changed=TRUE;
77        }
78    }
79    if (changed) {
80        p_Setm(m,r);
81    }
82    return changed;
83}
84static BOOLEAN polynomial_root(poly h, ring r){
85  poly got=gcd_of_terms(h,r);
86  BOOLEAN changed=FALSE;
87  if((got!=NULL) &&(TEST_V_UPTORADICAL)) {
88    poly copy=p_Copy(got,r);
89    //p_wrp(got,c->r);
90    changed=monomial_root(got,r);
91    if (changed)
92    {
93         poly div_by=pDivide(copy, got);
94         poly iter=h;
95         while(iter){
96            pExpVectorSub(iter,div_by);
97            pIter(iter);
98         }
99         p_Delete(&div_by, r);
100         if (TEST_OPT_PROT)
101             PrintS("U");
102    }
103    p_Delete(&copy,r);
104  }
105  p_Delete(&got,r);
106  return changed;
107}
108static inline poly p_Init_Special(const ring r)
109{
110  return p_Init(r,lm_bin);
111}
112static inline poly pOne_Special(const ring r=currRing)
113{
114  poly rc = p_Init_Special(r);
115  pSetCoeff0(rc,n_Init(1,r));
116  return rc;
117}
118// zum Initialiseren: in t_rep_gb plazieren:
119
120#endif
121#define LEN_VAR3
122#define degbound(p) assume(pTotaldegree(p)<10)
123//#define inDebug(p) assume((debug_Ideal==NULL)||(kNF(debug_Ideal,NULL,p,0,0)==0))
124
125//die meisten Varianten stossen sich an coef_buckets
126
127
128
129#ifdef LEN_VAR1
130// erste Variante: Laenge: Anzahl der Monome
131inline int pSLength(poly p, int l) {
132  return l; }
133inline int kSBucketLength(kBucket* bucket, poly lm) {return bucket_guess(bucket);}
134#endif
135
136#ifdef LEN_VAR2
137// 2. Variante: Laenge: Platz fuer die Koeff.
138int pSLength(poly p,int l)
139{
140  int s=0;
141  while (p!=NULL) { s+=nSize(pGetCoeff(p));pIter(p); }
142  return s;
143}
144int kSBucketLength(kBucket* b, poly lm)
145{
146  int s=0;
147  int i;
148  for (i=MAX_BUCKET;i>=0;i--)
149  {
150    s+=pSLength(b->buckets[i],0);
151  }
152  return s;
153}
154#endif
155
156
157
158
159
160
161int QlogSize(number n){
162
163    if (SR_HDL(n) & SR_INT){
164       long i=SR_TO_INT(n);
165       if (i==0) return 0;
166
167       unsigned long v;
168       v=(i>=0)?i:-i;
169       int r = 0;
170
171       while (v >>= 1)
172       {
173        r++;
174       }
175       return r+1;
176    }
177    //assume denominator is 0
178    return mpz_sizeinbase(&n->z,2);
179}
180
181
182#ifdef LEN_VAR3
183inline wlen_type pSLength(poly p,int l)
184{
185  wlen_type c;
186  number coef=pGetCoeff(p);
187  if (rField_is_Q(currRing)){
188    c=QlogSize(coef);
189  }
190  else
191    c=nSize(coef);
192  if (!(TEST_V_COEFSTRAT))
193      return (wlen_type)c*(wlen_type)l /*pLength(p)*/;
194  else {
195    wlen_type res=l;
196    res*=c;
197    res*=c;
198    return res;
199  }
200}
201//! TODO CoefBuckets bercksichtigen
202wlen_type kSBucketLength(kBucket* b, poly lm=NULL)
203{
204  int s=0;
205  wlen_type c;
206  number coef;
207  if(lm==NULL)
208    coef=pGetCoeff(kBucketGetLm(b));
209    //c=nSize(pGetCoeff(kBucketGetLm(b)));
210  else
211    coef=pGetCoeff(lm);
212    //c=nSize(pGetCoeff(lm));
213  if (rField_is_Q(currRing)){
214    c=QlogSize(coef);
215  }
216  else
217    c=nSize(coef);
218
219  int i;
220  for (i=b->buckets_used;i>=0;i--)
221  {
222    assume((b->buckets_length[i]==0)||(b->buckets[i]!=NULL));
223    s+=b->buckets_length[i] /*pLength(b->buckets[i])*/;
224  }
225  #ifdef HAVE_COEF_BUCKETS
226  assume(b->buckets[0]==kBucketGetLm(b));
227  if (b->coef[0]!=NULL){
228
229    if (rField_is_Q(currRing)){
230      int modifier=QlogSize(pGetCoeff(b->coef[0]));
231      c+=modifier;
232  }
233    else{
234      int modifier=nSize(pGetCoeff(b->coef[0]));
235      c*=modifier;}
236    }
237  #endif
238  if (!(TEST_V_COEFSTRAT)){
239  return s*c;
240  } else
241  {
242    wlen_type res=s;
243    res*=c;
244    res*=c;
245    return res;
246  }
247}
248#endif
249#ifdef LEN_VAR5
250inline wlen_type pSLength(poly p,int l)
251{
252  int c;
253  number coef=pGetCoeff(p);
254  if (rField_is_Q(currRing)){
255    c=QlogSize(coef);
256  }
257  else
258    c=nSize(coef);
259  wlen_type erg=l;
260  erg*=c;
261  erg*=c;
262  //PrintS("lenvar 5");
263  assume(erg>=0);
264  return erg; /*pLength(p)*/;
265}
266//! TODO CoefBuckets bercksichtigen
267wlen_type kSBucketLength(kBucket* b, poly lm=NULL)
268{
269  wlen_type s=0;
270  int c;
271  number coef;
272  if(lm==NULL)
273    coef=pGetCoeff(kBucketGetLm(b));
274    //c=nSize(pGetCoeff(kBucketGetLm(b)));
275  else
276    coef=pGetCoeff(lm);
277    //c=nSize(pGetCoeff(lm));
278  if (rField_is_Q(currRing)){
279    c=QlogSize(coef);
280  }
281  else
282    c=nSize(coef);
283
284  int i;
285  for (i=b->buckets_used;i>=0;i--)
286  {
287    assume((b->buckets_length[i]==0)||(b->buckets[i]!=NULL));
288    s+=b->buckets_length[i] /*pLength(b->buckets[i])*/;
289  }
290  #ifdef HAVE_COEF_BUCKETS
291  assume(b->buckets[0]==kBucketGetLm(b));
292  if (b->coef[0]!=NULL){
293
294    if (rField_is_Q(currRing)){
295      int modifier=QlogSize(pGetCoeff(b->coef[0]));
296      c+=modifier;
297  }
298    else{
299      int modifier=nSize(pGetCoeff(b->coef[0]));
300      c*=modifier;}
301    }
302  #endif
303  wlen_type erg=s;
304  erg*=c;
305  erg*=c;
306  return erg;
307}
308#endif
309
310#ifdef LEN_VAR4
311// 4.Variante: Laenge: Platz fuer Leitk * (1+Platz fuer andere Koeff.)
312int pSLength(poly p, int l)
313{
314  int s=1;
315  int c=nSize(pGetCoeff(p));
316  pIter(p);
317  while (p!=NULL) { s+=nSize(pGetCoeff(p));pIter(p); }
318  return s*c;
319}
320int kSBucketLength(kBucket* b)
321{
322  int s=1;
323  int c=nSize(pGetCoeff(kBucketGetLm(b)));
324  int i;
325  for (i=MAX_BUCKET;i>0;i--)
326  {
327    if(b->buckets[i]==NULL) continue;
328    s+=pSLength(b->buckets[i],0);
329  }
330  return s*c;
331}
332#endif
333//BUG/TODO this stuff will fail on internal Schreyer orderings
334static BOOLEAN elength_is_normal_length(poly p, slimgb_alg* c){
335    ring r=c->r;
336    if (p_GetComp(p,r)!=0) return FALSE;
337    if (c->lastDpBlockStart<=pVariables){
338        int i;
339        for(i=1;i<c->lastDpBlockStart;i++){
340            if (p_GetExp(p,i,r)!=0){
341                break;
342            }
343        }
344        if (i>=c->lastDpBlockStart) {
345        //wrp(p);
346        //PrintS("\n");
347        return TRUE;
348        }
349        else return FALSE;
350    }else
351    return FALSE;
352}
353
354static BOOLEAN lies_in_last_dp_block(poly p, slimgb_alg* c){
355    ring r=c->r;
356    if (p_GetComp(p,r)!=0) return FALSE;
357    if (c->lastDpBlockStart<=pVariables){
358        int i;
359        for(i=1;i<c->lastDpBlockStart;i++){
360            if (p_GetExp(p,i,r)!=0){
361                break;
362            }
363        }
364        if (i>=c->lastDpBlockStart) {
365        //wrp(p);
366        //PrintS("\n");
367        return TRUE;
368        }
369        else return FALSE;
370    }else
371    return FALSE;
372}
373
374static int get_last_dp_block_start(ring r){
375    //ring r=c->r;
376    int last_block;
377
378    if (rRing_has_CompLastBlock(r)){
379        last_block=rBlocks(r) - 3;
380    }
381    else {last_block=rBlocks(r)-2;}
382    assume(last_block>=0);
383    if (r->order[last_block]==ringorder_dp)
384        return r->block0[last_block];
385    return pVariables+1;
386
387}
388
389static wlen_type do_pELength(poly p, slimgb_alg* c, int dlm=-1){
390
391  if(p==NULL) return 0;
392  wlen_type s=0;
393  poly pi=p;
394  if(dlm<0){
395    dlm=c->pTotaldegree(p);
396    s=1;
397    pi=p->next;
398  }
399
400  while(pi){
401    int d=c->pTotaldegree(pi);
402    if(d>dlm)
403      s+=1+d-dlm;
404    else
405      ++s;
406    pi=pi->next;
407  }
408  return s;
409}
410
411wlen_type pELength(poly p, slimgb_alg* c, ring r){
412  if(p==NULL) return 0;
413  wlen_type s=0;
414  poly pi=p;
415  int dlm;
416    dlm=c->pTotaldegree(p);
417    s=1;
418    pi=p->next;
419
420
421  while(pi){
422    int d=c->pTotaldegree(pi);
423    if(d>dlm)
424      s+=1+d-dlm;
425    else
426      ++s;
427    pi=pi->next;
428  }
429  return s;
430}
431
432wlen_type kEBucketLength(kBucket* b, poly lm,int sugar,slimgb_alg* ca)
433{
434  wlen_type s=0;
435  if(lm==NULL){
436    lm=kBucketGetLm(b);
437  }
438  if(lm==NULL) return 0;
439  if(elength_is_normal_length(lm,ca)) {
440    return bucket_guess(b);
441  }
442  int d=ca->pTotaldegree(lm);
443  #if 0
444  assume(sugar>=d);
445  s=1+(bucket_guess(b)-1)*(sugar-d+1);
446  return s;
447  #else
448
449
450  //int d=pTotaldegree(lm,ca->r);
451  int i;
452  for (i=b->buckets_used;i>=0;i--)
453  {
454    if(b->buckets[i]==NULL) continue;
455
456    if ((ca->pTotaldegree(b->buckets[i])<=d) &&(elength_is_normal_length(b->buckets[i],ca))){
457        s+=b->buckets_length[i];
458    } else
459    {
460    s+=do_pELength(b->buckets[i],ca,d);
461    }
462  }
463  return s;
464  #endif
465}
466
467static inline int pELength(poly p, slimgb_alg* c,int l){
468  if (p==NULL) return 0;
469  if ((l>0) &&(elength_is_normal_length(p,c)))
470    return l;
471  return do_pELength(p,c);
472}
473
474
475
476
477static inline wlen_type pQuality(poly p, slimgb_alg* c, int l=-1){
478
479  if(l<0)
480    l=pLength(p);
481  if(c->isDifficultField) {
482    if(c->eliminationProblem){
483      wlen_type cs;
484      number coef=pGetCoeff(p);
485      if (rField_is_Q(currRing)){
486         cs=QlogSize(coef);
487      }
488      else
489        cs=nSize(coef);
490     wlen_type erg=cs;
491     if(TEST_V_COEFSTRAT)
492        erg*=cs;
493     //erg*=cs;//for quadratic
494     erg*=pELength(p,c,l);
495    //FIXME: not quadratic coeff size
496      //return cs*pELength(p,c,l);
497      return erg;
498    }
499    //PrintS("I am here");
500    wlen_type r=pSLength(p,l);
501    assume(r>=0);
502    return r;
503  }
504  if(c->eliminationProblem) return pELength(p,c,l);
505  return l;
506}
507
508static inline int pTotaldegree_full(poly p){
509  int r=0;
510  while(p){
511    int d=pTotaldegree(p);
512    r=si_max(r,d);
513    pIter(p);
514  }
515  return r;
516}
517
518wlen_type red_object::guess_quality(slimgb_alg* c){
519    //works at the moment only for lenvar 1, because in different
520    //case, you have to look on coefs
521    wlen_type s=0;
522    if (c->isDifficultField){
523      //s=kSBucketLength(bucket,this->p);
524      if(c->eliminationProblem){
525    wlen_type cs;
526    number coef;
527
528    coef=pGetCoeff(kBucketGetLm(bucket));
529    //c=nSize(pGetCoeff(kBucketGetLm(b)));
530
531    //c=nSize(pGetCoeff(lm));
532    if (rField_is_Q(currRing)){
533      cs=QlogSize(coef);
534    }
535    else
536      cs=nSize(coef);
537    #ifdef HAVE_COEF_BUCKETS
538    if (bucket->coef[0]!=NULL){
539      if (rField_is_Q(currRing)){
540        int modifier=QlogSize(pGetCoeff(bucket->coef[0]));
541        cs+=modifier;
542      }
543      else{
544        int modifier=nSize(pGetCoeff(bucket->coef[0]));
545        cs*=modifier;}
546    }
547    #endif
548    //FIXME:not quadratic
549    wlen_type erg=kEBucketLength(this->bucket,this->p,this->sugar,c);
550    //erg*=cs;//for quadratic
551    erg*=cs;
552    if (TEST_V_COEFSTRAT)
553        erg*=cs;
554    //return cs*kEBucketLength(this->bucket,this->p,c);
555    return erg;
556      }
557      s=kSBucketLength(bucket,NULL);
558    }
559    else
560    {
561      if(c->eliminationProblem)
562  //if (false)
563  s=kEBucketLength(this->bucket,this->p,this->sugar,c);
564      else s=bucket_guess(bucket);
565    }
566
567    return s;
568}
569
570
571
572static void finalize_reduction_step(reduction_step* r){
573  delete r;
574}
575static int LObject_better_gen(const void* ap, const void* bp)
576{
577  LObject* a=*(LObject**)ap;
578  LObject* b=*(LObject**)bp;
579  return(pLmCmp(a->p,b->p));
580}
581static int red_object_better_gen(const void* ap, const void* bp)
582{
583
584
585  return(pLmCmp(((red_object*) ap)->p,((red_object*) bp)->p));
586}
587
588
589static int pLmCmp_func_inverted(const void* ap1, const void* ap2){
590    poly p1,p2;
591  p1=*((poly*) ap1);
592  p2=*((poly*)ap2);
593
594  return -pLmCmp(p1,p2);
595}
596
597int tgb_pair_better_gen2(const void* ap,const void* bp){
598  return(-tgb_pair_better_gen(ap,bp));
599}
600int kFindDivisibleByInS_easy(kStrategy strat,const red_object & obj){
601  int i;
602  long not_sev=~obj.sev;
603  poly p=obj.p;
604  for(i=0;i<=strat->sl;i++){
605    if (pLmShortDivisibleBy(strat->S[i],strat->sevS[i],p,not_sev))
606      return i;
607  }
608  return -1;
609}
610int kFindDivisibleByInS_easy(kStrategy strat,poly p, long sev){
611  int i;
612  long not_sev=~sev;
613  for(i=0;i<=strat->sl;i++){
614    if (pLmShortDivisibleBy(strat->S[i],strat->sevS[i],p,not_sev))
615      return i;
616  }
617  return -1;
618}
619static int posInPairs (sorted_pair_node**  p, int pn, sorted_pair_node* qe,slimgb_alg* c,int an=0)
620{
621  if(pn==0) return 0;
622
623  int length=pn-1;
624  int i;
625  //int an = 0;
626  int en= length;
627
628  if (pair_better(qe,p[en],c))
629    return length+1;
630
631  while(1)
632    {
633      //if (an >= en-1)
634      if(en-1<=an)
635      {
636        if (pair_better(p[an],qe,c)) return an;
637        return en;
638      }
639      i=(an+en) / 2;
640        if (pair_better(p[i],qe,c))
641          en=i;
642      else an=i;
643    }
644}
645
646static BOOLEAN  ascending(int* i,int top){
647  if(top<1) return TRUE;
648  if(i[top]<i[top-1]) return FALSE;
649  return ascending(i,top-1);
650}
651
652sorted_pair_node**  spn_merge(sorted_pair_node** p, int pn,sorted_pair_node **q, int qn,slimgb_alg* c){
653  int i;
654  int* a= (int*) omalloc(qn*sizeof(int));
655//   int mc;
656//   PrintS("Debug\n");
657//   for(mc=0;mc<qn;mc++)
658// {
659
660//     wrp(q[mc]->lcm_of_lm);
661//     PrintS("\n");
662// }
663//    PrintS("Debug they are in\n");
664//   for(mc=0;mc<pn;mc++)
665// {
666
667//     wrp(p[mc]->lcm_of_lm);
668//     PrintS("\n");
669// }
670  int lastpos=0;
671  for(i=0;i<qn;i++){
672    lastpos=posInPairs(p,pn,q[i],c, si_max(lastpos-1,0));
673    //   cout<<lastpos<<"\n";
674    a[i]=lastpos;
675
676  }
677  if((pn+qn)>c->max_pairs){
678    p=(sorted_pair_node**) omrealloc(p,2*(pn+qn)*sizeof(sorted_pair_node*));
679    c->max_pairs=2*(pn+qn);
680  }
681  for(i=qn-1;i>=0;i--){
682    size_t size;
683    if(qn-1>i)
684      size=(a[i+1]-a[i])*sizeof(sorted_pair_node*);
685    else
686      size=(pn-a[i])*sizeof(sorted_pair_node*); //as indices begin with 0
687    memmove (p+a[i]+(1+i), p+a[i], size);
688    p[a[i]+i]=q[i];
689  }
690  omfree(a);
691  return p;
692}
693
694
695static BOOLEAN trivial_syzygie(int pos1,int pos2,poly bound,slimgb_alg* c){
696
697
698  poly p1=c->S->m[pos1];
699  poly p2=c->S->m[pos2];
700
701
702  if (pGetComp(p1) > 0 || pGetComp(p2) > 0)
703    return FALSE;
704  int i = 1;
705  poly m=NULL;
706  poly gcd1=c->gcd_of_terms[pos1];
707  poly gcd2=c->gcd_of_terms[pos2];
708
709  if((gcd1!=NULL) && (gcd2!=NULL))
710    {
711      gcd1->next=gcd2; //may ordered incorrect
712      m=gcd_of_terms(gcd1,c->r);
713      gcd1->next=NULL;
714
715    }
716
717  if (m==NULL)
718  {
719     loop
720      {
721  if (pGetExp(p1, i)+ pGetExp(p2, i) > pGetExp(bound,i))   return FALSE;
722  if (i == pVariables){
723    //PrintS("trivial");
724    return TRUE;
725  }
726  i++;
727      }
728  }
729  else
730  {
731    loop
732      {
733  if (pGetExp(p1, i)-pGetExp(m,i) + pGetExp(p2, i) > pGetExp(bound,i))  {
734    pDelete(&m);
735    return FALSE;}
736  if (i == pVariables){
737    pDelete(&m);
738    //PrintS("trivial");
739    return TRUE;
740  }
741  i++;
742      }
743  }
744
745
746
747
748}
749
750//! returns position sets w as weight
751int find_best(red_object* r,int l, int u, wlen_type &w, slimgb_alg* c){
752  int best=l;
753  int i;
754  w=r[l].guess_quality(c);
755  for(i=l+1;i<=u;i++){
756    wlen_type w2=r[i].guess_quality(c);
757    if(w2<w){
758      w=w2;
759      best=i;
760    }
761
762  }
763 return best;
764}
765
766
767void red_object::canonicalize(){
768  kBucketCanonicalize(bucket);
769
770
771}
772BOOLEAN good_has_t_rep(int i, int j,slimgb_alg* c){
773  assume(i>=0);
774    assume(j>=0);
775  if (has_t_rep(i,j,c)) return TRUE;
776  //poly lm=pOne();
777  assume (c->tmp_lm!=NULL);
778  poly lm=c->tmp_lm;
779
780  pLcm(c->S->m[i], c->S->m[j], lm);
781  pSetm(lm);
782  assume(lm!=NULL);
783  //int deciding_deg= pTotaldegree(lm);
784  int* i_con =make_connections(i,j,lm,c);
785  //p_Delete(&lm,c->r);
786
787
788  for (int n=0;((n<c->n) && (i_con[n]>=0));n++){
789    if (i_con[n]==j){
790      now_t_rep(i,j,c);
791      omfree(i_con);
792
793      return TRUE;
794    }
795  }
796  omfree(i_con);
797
798  return FALSE;
799}
800BOOLEAN lenS_correct(kStrategy strat){
801  int i;
802  for(i=0;i<=strat->sl;i++){
803    if (strat->lenS[i]!=pLength(strat->S[i]))
804      return FALSE;
805  }
806  return TRUE;
807}
808
809
810static void cleanS(kStrategy strat, slimgb_alg* c){
811  int i=0;
812  LObject P;
813  while(i<=strat->sl)
814  {
815    P.p=strat->S[i];
816    P.sev=strat->sevS[i];
817    int dummy=strat->sl;
818    //if(kFindDivisibleByInS(strat,&dummy,&P)!=i)
819    if (kFindDivisibleByInS_easy(strat,P.p,P.sev)!=i)
820    {
821      deleteInS(i,strat);
822      //remember destroying poly
823      BOOLEAN found=FALSE;
824      int j;
825      for(j=0;j<c->n;j++)
826      {
827        if(c->S->m[j]==P.p)
828        {
829          found=TRUE;
830          break;
831        }
832      }
833      if (!found)
834  pDelete(&P.p);
835      //remember additional reductors
836    }
837    else i++;
838  }
839}
840static int bucket_guess(kBucket* bucket){
841  int sum=0;
842  int i;
843  for (i=bucket->buckets_used;i>=0;i--){
844    if(bucket->buckets[i])
845       sum+=bucket->buckets_length[i];
846  }
847  return sum;
848}
849
850
851
852
853
854
855static int add_to_reductors(slimgb_alg* c, poly h, int len, int ecart, BOOLEAN simplified){
856  //inDebug(h);
857  assume(lenS_correct(c->strat));
858  assume(len==pLength(h));
859  int i;
860//   if (c->isDifficultField)
861//        i=simple_posInS(c->strat,h,pSLength(h,len),c->isDifficultField);
862//   else
863//     i=simple_posInS(c->strat,h,len,c->isDifficultField);
864
865  LObject P; memset(&P,0,sizeof(P));
866  P.tailRing=c->r;
867  P.p=h; /*p_Copy(h,c->r);*/
868  P.ecart=ecart;
869  P.FDeg=pFDeg(P.p,c->r);
870  if (!(simplified)){
871      if (!rField_is_Zp(c->r)){
872        pCleardenom(P.p);
873        pContent(P.p); //is a duplicate call, but belongs here
874
875      }
876      else
877        pNorm(P.p);
878    pNormalize(P.p);
879  }
880  wlen_type pq=pQuality(h,c,len);
881  i=simple_posInS(c->strat,h,len,pq);
882  c->strat->enterS(P,i,c->strat,-1);
883
884
885
886  c->strat->lenS[i]=len;
887  assume(pLength(c->strat->S[i])==c->strat->lenS[i]);
888  if(c->strat->lenSw!=NULL)
889    c->strat->lenSw[i]=pq;
890
891  return i;
892
893}
894static void length_one_crit(slimgb_alg* c, int pos, int len)
895{
896  if (c->nc)
897    return;
898  if (len==1)
899  {
900    int i;
901    for ( i=0;i<pos;i++)
902    {
903      if (c->lengths[i]==1)
904        c->states[pos][i]=HASTREP;
905    }
906    for ( i=pos+1;i<c->n;i++){
907      if (c->lengths[i]==1)
908        c->states[i][pos]=HASTREP;
909    }
910    if (!c->nc)
911      shorten_tails(c,c->S->m[pos]);
912  }
913}
914
915
916static void move_forward_in_S(int old_pos, int new_pos,kStrategy strat)
917{
918  assume(old_pos>=new_pos);
919  poly p=strat->S[old_pos];
920  int ecart=strat->ecartS[old_pos];
921  long sev=strat->sevS[old_pos];
922  int s_2_r=strat->S_2_R[old_pos];
923  int length=strat->lenS[old_pos];
924  assume(length==pLength(strat->S[old_pos]));
925  wlen_type length_w;
926  if(strat->lenSw!=NULL)
927    length_w=strat->lenSw[old_pos];
928  int i;
929  for (i=old_pos; i>new_pos; i--)
930  {
931    strat->S[i] = strat->S[i-1];
932    strat->ecartS[i] = strat->ecartS[i-1];
933    strat->sevS[i] = strat->sevS[i-1];
934    strat->S_2_R[i] = strat->S_2_R[i-1];
935  }
936  if (strat->lenS!=NULL)
937    for (i=old_pos; i>new_pos; i--)
938      strat->lenS[i] = strat->lenS[i-1];
939  if (strat->lenSw!=NULL)
940    for (i=old_pos; i>new_pos; i--)
941      strat->lenSw[i] = strat->lenSw[i-1];
942
943  strat->S[new_pos]=p;
944  strat->ecartS[new_pos]=ecart;
945  strat->sevS[new_pos]=sev;
946  strat->S_2_R[new_pos]=s_2_r;
947  strat->lenS[new_pos]=length;
948  if(strat->lenSw!=NULL)
949    strat->lenSw[new_pos]=length_w;
950  //assume(lenS_correct(strat));
951}
952
953static void move_backward_in_S(int old_pos, int new_pos,kStrategy strat)
954{
955  assume(old_pos<=new_pos);
956  poly p=strat->S[old_pos];
957  int ecart=strat->ecartS[old_pos];
958  long sev=strat->sevS[old_pos];
959  int s_2_r=strat->S_2_R[old_pos];
960  int length=strat->lenS[old_pos];
961  assume(length==pLength(strat->S[old_pos]));
962  wlen_type length_w;
963  if(strat->lenSw!=NULL)
964    length_w=strat->lenSw[old_pos];
965  int i;
966  for (i=old_pos; i<new_pos; i++)
967  {
968    strat->S[i] = strat->S[i+1];
969    strat->ecartS[i] = strat->ecartS[i+1];
970    strat->sevS[i] = strat->sevS[i+1];
971    strat->S_2_R[i] = strat->S_2_R[i+1];
972  }
973  if (strat->lenS!=NULL)
974    for (i=old_pos; i<new_pos; i++)
975      strat->lenS[i] = strat->lenS[i+1];
976  if (strat->lenSw!=NULL)
977    for (i=old_pos; i<new_pos; i++)
978      strat->lenSw[i] = strat->lenSw[i+1];
979
980  strat->S[new_pos]=p;
981  strat->ecartS[new_pos]=ecart;
982  strat->sevS[new_pos]=sev;
983  strat->S_2_R[new_pos]=s_2_r;
984  strat->lenS[new_pos]=length;
985  if(strat->lenSw!=NULL)
986    strat->lenSw[new_pos]=length_w;
987  //assume(lenS_correct(strat));
988}
989
990static int* make_connections(int from, int to, poly bound, slimgb_alg* c)
991{
992  ideal I=c->S;
993  int* cans=(int*) omalloc(c->n*sizeof(int));
994  int* connected=(int*) omalloc(c->n*sizeof(int));
995  cans[0]=to;
996  int cans_length=1;
997  connected[0]=from;
998  int last_cans_pos=-1;
999  int connected_length=1;
1000  long neg_bounds_short= ~p_GetShortExpVector(bound,c->r);
1001
1002  int not_yet_found=cans_length;
1003  int con_checked=0;
1004  int pos;
1005
1006  while(TRUE){
1007    if ((con_checked<connected_length)&& (not_yet_found>0)){
1008      pos=connected[con_checked];
1009      for(int i=0;i<cans_length;i++){
1010        if (cans[i]<0) continue;
1011        //FIXME: triv. syz. does not hold on noncommutative, check it for modules
1012        if ((has_t_rep(pos,cans[i],c)) ||((!rIsPluralRing(c->r))&&(trivial_syzygie(pos,cans[i],bound,c))))
1013{
1014
1015          connected[connected_length]=cans[i];
1016          connected_length++;
1017          cans[i]=-1;
1018          --not_yet_found;
1019
1020          if (connected[connected_length-1]==to){
1021            if (connected_length<c->n){
1022              connected[connected_length]=-1;
1023            }
1024            omfree(cans);
1025            return connected;
1026          }
1027        }
1028      }
1029      con_checked++;
1030    }
1031    else
1032    {
1033      for(last_cans_pos++;last_cans_pos<=c->n;last_cans_pos++){
1034        if (last_cans_pos==c->n){
1035          if (connected_length<c->n){
1036            connected[connected_length]=-1;
1037          }
1038          omfree(cans);
1039          return connected;
1040        }
1041        if ((last_cans_pos==from)||(last_cans_pos==to))
1042          continue;
1043        if(p_LmShortDivisibleBy(I->m[last_cans_pos],c->short_Exps[last_cans_pos],bound,neg_bounds_short,c->r)){
1044          cans[cans_length]=last_cans_pos;
1045          cans_length++;
1046          break;
1047        }
1048      }
1049      not_yet_found++;
1050      for (int i=0;i<con_checked;i++){
1051        if (has_t_rep(connected[i],last_cans_pos,c)){
1052
1053          connected[connected_length]=last_cans_pos;
1054          connected_length++;
1055          cans[cans_length-1]=-1;
1056
1057          --not_yet_found;
1058          if (connected[connected_length-1]==to){
1059            if (connected_length<c->n){
1060              connected[connected_length]=-1;
1061            }
1062
1063            omfree(cans);
1064            return connected;
1065          }
1066          break;
1067        }
1068      }
1069    }
1070  }
1071  if (connected_length<c->n){
1072    connected[connected_length]=-1;
1073  }
1074
1075  omfree(cans);
1076  return connected;
1077}
1078#ifdef HEAD_BIN
1079static inline poly p_MoveHead(poly p, omBin b)
1080{
1081  poly np;
1082  omTypeAllocBin(poly, np, b);
1083  memmove(np, p, b->sizeW*sizeof(long));
1084  omFreeBinAddr(p);
1085  return np;
1086}
1087#endif
1088
1089static void replace_pair(int & i, int & j,slimgb_alg* c)
1090{
1091  if (i<0) return;
1092  c->soon_free=NULL;
1093  int syz_deg;
1094  poly lm=pOne();
1095
1096  pLcm(c->S->m[i], c->S->m[j], lm);
1097  pSetm(lm);
1098
1099  int* i_con =make_connections(i,j,lm,c);
1100
1101  for (int n=0;((n<c->n) && (i_con[n]>=0));n++){
1102    if (i_con[n]==j){
1103      now_t_rep(i,j,c);
1104      omfree(i_con);
1105      p_Delete(&lm,c->r);
1106      return;
1107    }
1108  }
1109
1110  int* j_con =make_connections(j,i,lm,c);
1111
1112//   if(c->n>1){
1113//     if (i_con[1]>=0)
1114//       i=i_con[1];
1115//     else {
1116//       if (j_con[1]>=0)
1117//         j=j_con[1];
1118//     }
1119 // }
1120
1121  int sugar=c->pTotaldegree(lm);
1122  p_Delete(&lm, c->r);
1123    if(c->T_deg_full)//Sugar
1124    {
1125      int t_i=c->T_deg_full[i]-c->T_deg[i];
1126      int t_j=c->T_deg_full[j]-c->T_deg[j];
1127      sugar+=si_max(t_i,t_j);
1128      //Print("\n max: %d\n",max(t_i,t_j));
1129    }
1130
1131
1132
1133
1134
1135  for (int m=0;((m<c->n) && (i_con[m]>=0));m++){
1136    if(c->T_deg_full!=NULL){
1137        int s1=c->T_deg_full[i_con[m]]+syz_deg-c->T_deg[i_con[m]];
1138        if (s1>sugar) continue;
1139    }
1140    if (c->weighted_lengths[i_con[m]]<c->weighted_lengths[i])
1141        i=i_con[m];
1142    }
1143    for (int m=0;((m<c->n) && (j_con[m]>=0));m++){
1144        if (c->T_deg_full!=NULL){
1145        int s1=c->T_deg_full[j_con[m]]+syz_deg-c->T_deg[j_con[m]];
1146        if (s1>sugar) continue;}
1147        if (c->weighted_lengths[j_con[m]]<c->weighted_lengths[j])
1148            j=j_con[m];
1149    }
1150
1151     //can also try dependend search
1152  omfree(i_con);
1153  omfree(j_con);
1154  return;
1155}
1156
1157
1158static void add_later(poly p, const char* prot, slimgb_alg* c)
1159{
1160    int i=0;
1161    //check, if it is already in the queue
1162
1163
1164    while(c->add_later->m[i]!=NULL)
1165    {
1166        if (p_LmEqual(c->add_later->m[i],p,c->r))
1167            return;
1168        i++;
1169    }
1170    if (TEST_OPT_PROT)
1171        PrintS(prot);
1172    c->add_later->m[i]=p;
1173}
1174static int simple_posInS (kStrategy strat, poly p,int len, wlen_type wlen)
1175{
1176
1177
1178  if(strat->sl==-1) return 0;
1179  if (strat->lenSw) return pos_helper(strat,p,(wlen_type) wlen,(wlen_set) strat->lenSw,strat->S);
1180  return pos_helper(strat,p,len,strat->lenS,strat->S);
1181
1182}
1183
1184/*2
1185 *if the leading term of p
1186 *divides the leading term of some S[i] it will be canceled
1187 */
1188static inline void clearS (poly p, unsigned long p_sev,int l, int* at, int* k,
1189                           kStrategy strat)
1190{
1191  assume(p_sev == pGetShortExpVector(p));
1192  if (!pLmShortDivisibleBy(p,p_sev, strat->S[*at], ~ strat->sevS[*at])) return;
1193  if (l>=strat->lenS[*at]) return;
1194  if (TEST_OPT_PROT)
1195    PrintS("!");
1196  mflush();
1197  //pDelete(&strat->S[*at]);
1198  deleteInS((*at),strat);
1199  (*at)--;
1200  (*k)--;
1201//  assume(lenS_correct(strat));
1202}
1203
1204
1205
1206static int iq_crit(const void* ap,const void* bp){
1207
1208  sorted_pair_node* a=*((sorted_pair_node**)ap);
1209  sorted_pair_node* b=*((sorted_pair_node**)bp);
1210  assume(a->i>a->j);
1211  assume(b->i>b->j);
1212
1213
1214  if (a->deg<b->deg) return -1;
1215  if (a->deg>b->deg) return 1;
1216  int comp=pLmCmp(a->lcm_of_lm, b->lcm_of_lm);
1217  if(comp!=0)
1218    return comp;
1219  if (a->expected_length<b->expected_length) return -1;
1220  if (a->expected_length>b->expected_length) return 1;
1221  if (a->j>b->j) return 1;
1222  if (a->j<b->j) return -1;
1223  return 0;
1224}
1225static wlen_type coeff_mult_size_estimate(int s1, int s2, ring r){
1226    if (rField_is_Q(r)) return s1+s2;
1227    else return s1*s2;
1228}
1229static wlen_type pair_weighted_length(int i, int j, slimgb_alg* c){
1230    if ((c->isDifficultField) && (c->eliminationProblem))  {
1231        int c1=slim_nsize(p_GetCoeff(c->S->m[i],c->r),c->r);
1232        int c2=slim_nsize(p_GetCoeff(c->S->m[j],c->r),c->r);
1233        wlen_type el1=c->weighted_lengths[i]/c1;
1234        assume(el1!=0);
1235        assume(c->weighted_lengths[i] %c1==0);
1236        wlen_type el2=c->weighted_lengths[j]/c2;
1237        assume(el2!=0);
1238        assume(c->weighted_lengths[j] %c2==0);
1239        //should be * for function fields
1240        //return (c1+c2) * (el1+el2-2);
1241        wlen_type res=coeff_mult_size_estimate(c1,c2,c->r);
1242        res*=el1+el2-2;
1243        return res;
1244
1245    }
1246    if (c->isDifficultField) {
1247        //int cs=slim_nsize(p_GetCoeff(c->S->m[i],c->r),c->r)+
1248        //    slim_nsize(p_GetCoeff(c->S->m[j],c->r),c->r);
1249        if(!(TEST_V_COEFSTRAT)){
1250        wlen_type cs=
1251            coeff_mult_size_estimate(
1252                slim_nsize(p_GetCoeff(c->S->m[i],c->r),c->r),
1253                slim_nsize(p_GetCoeff(c->S->m[j],c->r),c->r),c->r);
1254        return (wlen_type)(c->lengths[i]+c->lengths[j]-2)*
1255            (wlen_type)cs;}
1256            else {
1257
1258            wlen_type cs=
1259            coeff_mult_size_estimate(
1260                slim_nsize(p_GetCoeff(c->S->m[i],c->r),c->r),
1261                slim_nsize(p_GetCoeff(c->S->m[j],c->r),c->r),c->r);
1262            cs*=cs;
1263        return (wlen_type)(c->lengths[i]+c->lengths[j]-2)*
1264            (wlen_type)cs;
1265            }
1266    }
1267    if (c->eliminationProblem) {
1268
1269        return (c->weighted_lengths[i]+c->weighted_lengths[j]-2);
1270    }
1271    return c->lengths[i]+c->lengths[j]-2;
1272
1273}
1274sorted_pair_node** add_to_basis_ideal_quotient(poly h, slimgb_alg* c, int* ip)
1275{
1276  p_Test(h,c->r);
1277  assume(h!=NULL);
1278  poly got=gcd_of_terms(h,c->r);
1279  if((got!=NULL) &&(TEST_V_UPTORADICAL)) {
1280    poly copy=p_Copy(got,c->r);
1281    //p_wrp(got,c->r);
1282    BOOLEAN changed=monomial_root(got,c->r);
1283    if (changed)
1284    {
1285         poly div_by=pDivide(copy, got);
1286         poly iter=h;
1287         while(iter){
1288            pExpVectorSub(iter,div_by);
1289            pIter(iter);
1290         }
1291         p_Delete(&div_by, c->r);
1292         PrintS("U");
1293    }
1294    p_Delete(&copy,c->r);
1295  }
1296
1297#define ENLARGE(pointer, type) pointer=(type*) omrealloc(pointer, c->array_lengths*sizeof(type))
1298//  BOOLEAN corr=lenS_correct(c->strat);
1299  BOOLEAN R_found=FALSE;
1300  void* hp;
1301  int sugar;
1302  int ecart=0;
1303  ++(c->n);
1304  ++(c->S->ncols);
1305  int i,j;
1306  i=c->n-1;
1307  sorted_pair_node** nodes=(sorted_pair_node**) omalloc(sizeof(sorted_pair_node*)*i);
1308  int spc=0;
1309  if(c->n>c->array_lengths){
1310    c->array_lengths=c->array_lengths*2;
1311    assume(c->array_lengths>=c->n);
1312    ENLARGE(c->T_deg, int);
1313    ENLARGE(c->tmp_pair_lm,poly);
1314    ENLARGE(c->tmp_spn,sorted_pair_node*);
1315
1316    ENLARGE(c->short_Exps,long);
1317    ENLARGE(c->lengths,int);
1318    #ifndef HAVE_BOOST
1319    #ifndef USE_STDVECBOOL
1320
1321    ENLARGE(c->states, char*);
1322    #endif
1323    #endif
1324    ENLARGE(c->gcd_of_terms,poly);
1325    //if (c->weighted_lengths!=NULL) {
1326    ENLARGE(c->weighted_lengths,wlen_type);
1327    //}
1328    //ENLARGE(c->S->m,poly);
1329
1330  }
1331  pEnlargeSet(&c->S->m,c->n-1,1);
1332  if (c->T_deg_full)
1333    ENLARGE(c->T_deg_full,int);
1334  sugar=c->T_deg[i]=c->pTotaldegree(h);
1335  if(c->T_deg_full){
1336    sugar=c->T_deg_full[i]=c->pTotaldegree_full(h);
1337    ecart=sugar-c->T_deg[i];
1338    assume(ecart>=0);
1339  }
1340
1341
1342  c->tmp_pair_lm[i]=pOne_Special(c->r);
1343
1344
1345  c->tmp_spn[i]=(sorted_pair_node*) omalloc(sizeof(sorted_pair_node));
1346
1347
1348  c->lengths[i]=pLength(h);
1349
1350  //necessary for correct weighted length
1351
1352   if (!rField_is_Zp(c->r)){
1353    pCleardenom(h);
1354    pContent(h); //is a duplicate call, but belongs here
1355
1356  }
1357  else
1358    pNorm(h);
1359  pNormalize(h);
1360
1361  c->weighted_lengths[i]=pQuality(h, c, c->lengths[i]);
1362  c->gcd_of_terms[i]=got;
1363  #ifdef HAVE_BOOST
1364    c->states.push_back(dynamic_bitset<>(i));
1365
1366  #else
1367  #ifdef USE_STDVECBOOL
1368
1369    c->states.push_back(vector<bool>(i));
1370
1371
1372  #else
1373  if (i>0)
1374    c->states[i]=(char*)  omalloc(i*sizeof(char));
1375  else
1376    c->states[i]=NULL;
1377  #endif
1378  #endif
1379
1380  c->S->m[i]=h;
1381  c->short_Exps[i]=p_GetShortExpVector(h,c->r);
1382
1383#undef ENLARGE
1384  if (p_GetComp(h,currRing)<=c->syz_comp){
1385  for (j=0;j<i;j++){
1386
1387
1388    #ifndef HAVE_BOOST
1389    c->states[i][j]=UNCALCULATED;
1390    #endif
1391    assume(p_LmDivisibleBy(c->S->m[i],c->S->m[j],c->r)==
1392     p_LmShortDivisibleBy(c->S->m[i],c->short_Exps[i],c->S->m[j],~(c->short_Exps[j]),c->r));
1393
1394
1395    if (_p_GetComp(c->S->m[i],c->r)!=_p_GetComp(c->S->m[j],c->r)){
1396      //c->states[i][j]=UNCALCULATED;
1397      //WARNUNG: be careful
1398      continue;
1399    } else
1400    if ((!c->nc) && (c->lengths[i]==1) && (c->lengths[j]==1)){
1401      c->states[i][j]=HASTREP;
1402
1403      }
1404    else if (( (!c->nc) || (c->is_homog && rIsSCA(c->r) ) ) &&  (pHasNotCF(c->S->m[i],c->S->m[j])))
1405//     else if ((!(c->nc)) &&  (pHasNotCF(c->S->m[i],c->S->m[j])))
1406    {
1407      c->easy_product_crit++;
1408      c->states[i][j]=HASTREP;
1409      continue;
1410    }
1411    else if(extended_product_criterion(c->S->m[i],c->gcd_of_terms[i],c->S->m[j],c->gcd_of_terms[j],c))
1412    {
1413      c->states[i][j]=HASTREP;
1414      c->extended_product_crit++;
1415
1416      //PrintS("E");
1417    }
1418      //  if (c->states[i][j]==UNCALCULATED){
1419
1420    if ((TEST_V_FINDMONOM) &&(!c->nc)) {
1421        //PrintS("COMMU");
1422       //  if (c->lengths[i]==c->lengths[j]){
1423//             poly short_s=ksCreateShortSpoly(c->S->m[i],c->S->m[j],c->r);
1424//             if (short_s==NULL){
1425//                 c->states[i][j]=HASTREP;
1426//             } else
1427//             {
1428//                 p_Delete(&short_s, currRing);
1429//             }
1430//         }
1431        if (c->lengths[i]+c->lengths[j]==3){
1432
1433
1434             poly short_s=ksCreateShortSpoly(c->S->m[i],c->S->m[j],c->r);
1435            if (short_s==NULL)
1436            {
1437                c->states[i][j]=HASTREP;
1438            }
1439            else
1440            {
1441                assume(pLength(short_s)==1);
1442                if (TEST_V_UPTORADICAL)
1443                   monomial_root(short_s,c->r);
1444                int iS=
1445                   kFindDivisibleByInS_easy(c->strat,short_s, p_GetShortExpVector(short_s,c->r));
1446                if (iS<0)
1447                {
1448                    //PrintS("N");
1449                    if (TRUE)
1450                    {
1451                      c->states[i][j]=HASTREP;
1452                      add_later(short_s,"N",c);
1453                    }
1454                    else
1455                      p_Delete(&short_s,currRing);
1456                }
1457                else
1458                {
1459                    if (c->strat->lenS[iS]>1){
1460                        //PrintS("O");
1461                        if (TRUE) {
1462                        c->states[i][j]=HASTREP;
1463                        add_later(short_s,"O",c);
1464                        } else p_Delete(&short_s,currRing);
1465                    }
1466                    else
1467                     p_Delete(&short_s, currRing);
1468                     c->states[i][j]=HASTREP;
1469                }
1470
1471
1472            }
1473        }
1474    }
1475      //    if (short_s)
1476      //    {
1477    assume(spc<=j);
1478    sorted_pair_node* s=c->tmp_spn[spc];//(sorted_pair_node*) omalloc(sizeof(sorted_pair_node));
1479    s->i=si_max(i,j);
1480    s->j=si_min(i,j);
1481    assume(s->j==j);
1482    s->expected_length=pair_weighted_length(i,j,c);//c->lengths[i]+c->lengths[j]-2;
1483
1484    poly lm=c->tmp_pair_lm[spc];//=pOne_Special();
1485
1486    pLcm(c->S->m[i], c->S->m[j], lm);
1487    pSetm(lm);
1488    p_Test(lm,c->r);
1489    s->deg=c->pTotaldegree(lm);
1490
1491    if(c->T_deg_full)//Sugar
1492    {
1493      int t_i=c->T_deg_full[s->i]-c->T_deg[s->i];
1494      int t_j=c->T_deg_full[s->j]-c->T_deg[s->j];
1495      s->deg+=si_max(t_i,t_j);
1496      //Print("\n max: %d\n",max(t_i,t_j));
1497    }
1498    p_Test(lm,c->r);
1499    s->lcm_of_lm=lm;
1500    //          pDelete(&short_s);
1501    //assume(lm!=NULL);
1502    nodes[spc]=s;
1503    spc++;
1504
1505  // }
1506  //else
1507  //{
1508        //c->states[i][j]=HASTREP;
1509  //}
1510  }
1511  }//if syz_comp end
1512
1513
1514
1515
1516  assume(spc<=i);
1517  //now ideal quotient crit
1518  qsort(nodes,spc,sizeof(sorted_pair_node*),iq_crit);
1519
1520    sorted_pair_node** nodes_final=(sorted_pair_node**) omalloc(sizeof(sorted_pair_node*)*i);
1521  int spc_final=0;
1522  j=0;
1523  while(j<spc)
1524  {
1525    int lower=j;
1526    int upper;
1527    BOOLEAN has=FALSE;
1528    for(upper=lower+1;upper<spc;upper++)
1529    {
1530
1531      if(!pLmEqual(nodes[lower]->lcm_of_lm,nodes[upper]->lcm_of_lm))
1532      {
1533  break;
1534      }
1535      if (has_t_rep(nodes[upper]->i,nodes[upper]->j,c))
1536  has=TRUE;
1537
1538    }
1539    upper=upper-1;
1540    int z;
1541    assume(spc_final<=j);
1542    for(z=0;z<spc_final;z++)
1543    {
1544      if(p_LmDivisibleBy(nodes_final[z]->lcm_of_lm,nodes[lower]->lcm_of_lm,c->r))
1545      {
1546  has=TRUE;
1547  break;
1548      }
1549    }
1550
1551    if(has)
1552    {
1553      for(;lower<=upper;lower++)
1554      {
1555  //free_sorted_pair_node(nodes[lower],c->r);
1556  //omfree(nodes[lower]);
1557  nodes[lower]=NULL;
1558      }
1559      j=upper+1;
1560      continue;
1561    }
1562    else
1563    {
1564      p_Test(nodes[lower]->lcm_of_lm,c->r);
1565      nodes[lower]->lcm_of_lm=pCopy(nodes[lower]->lcm_of_lm);
1566      assume(_p_GetComp(c->S->m[nodes[lower]->i],c->r)==_p_GetComp(c->S->m[nodes[lower]->j],c->r));
1567      nodes_final[spc_final]=(sorted_pair_node*) omalloc(sizeof(sorted_pair_node));
1568
1569      *(nodes_final[spc_final++])=*(nodes[lower]);
1570      //c->tmp_spn[nodes[lower]->j]=(sorted_pair_node*) omalloc(sizeof(sorted_pair_node));
1571      nodes[lower]=NULL;
1572      for(lower=lower+1;lower<=upper;lower++)
1573      {
1574  //  free_sorted_pair_node(nodes[lower],c->r);
1575  //omfree(nodes[lower]);
1576  nodes[lower]=NULL;
1577      }
1578      j=upper+1;
1579      continue;
1580    }
1581  }
1582
1583  //  Print("i:%d,spc_final:%d",i,spc_final);
1584
1585
1586
1587
1588  assume(spc_final<=spc);
1589  omfree(nodes);
1590  nodes=NULL;
1591
1592  add_to_reductors(c, h, c->lengths[c->n-1], ecart,TRUE);
1593  //i=posInS(c->strat,c->strat->sl,h,0 ecart);
1594  if (!(c->nc)){
1595    if (c->lengths[c->n-1]==1)
1596      shorten_tails(c,c->S->m[c->n-1]);
1597  }
1598  //you should really update c->lengths, c->strat->lenS, and the oder of polys in strat if you sort after lengths
1599
1600  //for(i=c->strat->sl; i>0;i--)
1601  //  if(c->strat->lenS[i]<c->strat->lenS[i-1]) printf("fehler bei %d\n",i);
1602  if (c->Rcounter>50) {
1603    c->Rcounter=0;
1604    cleanS(c->strat,c);
1605  }
1606
1607#ifdef HAVE_PLURAL
1608  // for SCA:
1609  // here write at the end of nodes_final[spc_final,...,spc_final+lmdeg-1]
1610  if(rIsSCA(c->r))
1611  {
1612    const poly pNext = pNext(h);
1613
1614    if(pNext != NULL)
1615    {
1616      // for additional polynomials
1617      const unsigned int m_iFirstAltVar = scaFirstAltVar(c->r);
1618      const unsigned int m_iLastAltVar  = scaLastAltVar(c->r);
1619
1620      int N = // c->r->N;
1621              m_iLastAltVar - m_iFirstAltVar + 1; // should be enough
1622      // TODO: but we may also use got = gcd({m}_{m\in f}))!
1623
1624       poly* array_arg=(poly*)omalloc(N*sizeof(poly)); // !
1625       int j = 0;
1626
1627
1628      for( unsigned short v = m_iFirstAltVar; v <= m_iLastAltVar; v++ )
1629      // for all x_v | Ann(lm(h))
1630      if( p_GetExp(h, v, c->r) ) // TODO: use 'got' here!
1631      {
1632        assume(p_GetExp(h, v, c->r)==1);
1633
1634        poly p = sca_pp_Mult_xi_pp(v, pNext, c->r); // x_v * h;
1635
1636        if(p != NULL) // if (x_v * h != 0)
1637          array_arg[j++] = p;
1638      } // for all x_v | Ann(lm(h))
1639
1640      c->introduceDelayedPairs(array_arg, j);
1641
1642      omfree(array_arg); // !!!
1643    }
1644//     PrintS("Saturation - done!!!\n");
1645  }
1646#endif // if SCAlgebra
1647
1648
1649  if(!ip){
1650    qsort(nodes_final,spc_final,sizeof(sorted_pair_node*),tgb_pair_better_gen2);
1651
1652
1653    c->apairs=spn_merge(c->apairs,c->pair_top+1,nodes_final,spc_final,c);
1654    c->pair_top+=spc_final;
1655    clean_top_of_pair_list(c);
1656    omfree(nodes_final);
1657    return NULL;
1658  }
1659  {
1660    *ip=spc_final;
1661    return nodes_final;
1662  }
1663
1664
1665
1666}
1667
1668
1669static poly redNF2 (poly h,slimgb_alg* c , int &len, number&  m,int n)
1670{
1671  m=nInit(1);
1672  if (h==NULL) return NULL;
1673
1674  assume(len==pLength(h));
1675  kStrategy strat=c->strat;
1676  if (0 > strat->sl)
1677  {
1678    return h;
1679  }
1680  int j;
1681
1682  LObject P(h);
1683  P.SetShortExpVector();
1684  P.bucket = kBucketCreate(currRing);
1685  // BOOLEAN corr=lenS_correct(strat);
1686  kBucketInit(P.bucket,P.p,len /*pLength(P.p)*/);
1687  //wlen_set lenSw=(wlen_set) c->strat->lenS;
1688  //FIXME: plainly wrong
1689  //strat->lenS;
1690  //if (strat->lenSw!=NULL)
1691  //  lenSw=strat->lenSw;
1692  //int max_pos=simple_posInS(strat,P.p);
1693  loop
1694  {
1695      int dummy=strat->sl;
1696      j=kFindDivisibleByInS_easy(strat,P.p,P.sev);
1697      //j=kFindDivisibleByInS(strat,&dummy,&P);
1698      if ((j>=0) && ((!n)||
1699        ((strat->lenS[j]<=n) &&
1700         ((strat->lenSw==NULL)||
1701         (strat->lenSw[j]<=n)))))
1702      {
1703        nNormalize(pGetCoeff(P.p));
1704#ifdef KDEBUG
1705        if (TEST_OPT_DEBUG)
1706        {
1707          PrintS("red:");
1708          wrp(h);
1709          PrintS(" with ");
1710          wrp(strat->S[j]);
1711        }
1712#endif
1713
1714        number coef=kBucketPolyRed(P.bucket,strat->S[j],
1715                                   strat->lenS[j]/*pLength(strat->S[j])*/,
1716                                   strat->kNoether);
1717  number m2=nMult(m,coef);
1718  nDelete(&m);
1719  m=m2;
1720        nDelete(&coef);
1721        h = kBucketGetLm(P.bucket);
1722
1723  if (h==NULL) {
1724    len=0;
1725    kBucketDestroy(&P.bucket);
1726    return
1727    NULL;}
1728        P.p=h;
1729        P.t_p=NULL;
1730        P.SetShortExpVector();
1731#ifdef KDEBUG
1732        if (TEST_OPT_DEBUG)
1733        {
1734          PrintS("\nto:");
1735          wrp(h);
1736          PrintLn();
1737        }
1738#endif
1739      }
1740      else
1741      {
1742        kBucketClear(P.bucket,&(P.p),&len);
1743        kBucketDestroy(&P.bucket);
1744        pNormalize(P.p);
1745  assume(len==(pLength(P.p)));
1746        return P.p;
1747      }
1748    }
1749}
1750
1751
1752
1753static poly redTailShort(poly h, kStrategy strat){
1754  if (h==NULL) return NULL;//n_Init(1,currRing);
1755  if (TEST_V_MODPSOLVSB){
1756    bit_reduce(pNext(h), strat->tailRing);
1757  }
1758  int sl=strat->sl;
1759  int i;
1760  int len=pLength(h);
1761  for(i=0;i<=strat->sl;i++){
1762    if((strat->lenS[i]>2) || ((strat->lenSw!=NULL) && (strat->lenSw[i]>2)))
1763      break;
1764  }
1765  return(redNFTail(h,i-1,strat, len));
1766}
1767
1768static void line_of_extended_prod(int fixpos,slimgb_alg* c){
1769    if (c->gcd_of_terms[fixpos]==NULL)
1770  {
1771    c->gcd_of_terms[fixpos]=gcd_of_terms(c->S->m[fixpos],c->r);
1772    if (c->gcd_of_terms[fixpos])
1773    {
1774      int i;
1775      for(i=0;i<fixpos;i++)
1776        if((c->states[fixpos][i]!=HASTREP)&& (extended_product_criterion(c->S->m[fixpos],c->gcd_of_terms[fixpos], c->S->m[i],c->gcd_of_terms[i],c)))
1777{
1778          c->states[fixpos][i]=HASTREP;
1779    c->extended_product_crit++;
1780}
1781      for(i=fixpos+1;i<c->n;i++)
1782        if((c->states[i][fixpos]!=HASTREP)&& (extended_product_criterion(c->S->m[fixpos],c->gcd_of_terms[fixpos], c->S->m[i],c->gcd_of_terms[i],c)))
1783  {        c->states[i][fixpos]=HASTREP;
1784  c->extended_product_crit++;
1785  }
1786    }
1787  }
1788}
1789static void c_S_element_changed_hook(int pos, slimgb_alg* c){
1790  length_one_crit(c,pos, c->lengths[pos]);
1791  if (!c->nc)
1792    line_of_extended_prod(pos,c);
1793}
1794class poly_tree_node {
1795public:
1796  poly p;
1797  poly_tree_node* l;
1798  poly_tree_node* r;
1799  int n;
1800  poly_tree_node(int sn):l(NULL),r(NULL),n(sn){}
1801};
1802class exp_number_builder{
1803public:
1804  poly_tree_node* top_level;
1805  int n;
1806  int get_n(poly p);
1807  exp_number_builder():top_level(0),n(0){}
1808};
1809int exp_number_builder::get_n(poly p){
1810  poly_tree_node** node=&top_level;
1811  while(*node!=NULL){
1812    int c=pLmCmp(p,(*node)->p);
1813    if (c==0) return (*node)->n;
1814    if (c==-1) node=&((*node)->r);
1815    else
1816      node=&((*node)->l);
1817  }
1818  (*node)= new poly_tree_node(n);
1819  n++;
1820  (*node)->p=pLmInit(p);
1821  return (*node)->n;
1822}
1823
1824//mac_polys exp are smaller iff they are greater by monomial ordering
1825//corresponding to solving linear equations notation
1826
1827//! obsolete
1828struct int_poly_pair{
1829  poly p;
1830  int n;
1831};
1832
1833
1834//! obsolete
1835void t2ippa_rec(poly* ip,int* ia, poly_tree_node* k, int &offset){
1836    if(!k) return;
1837    t2ippa_rec(ip,ia,k->l,offset);
1838    ip[offset]=k->p;
1839    ia[k->n]=offset;
1840    ++offset;
1841
1842    t2ippa_rec(ip,ia,k->r,offset);
1843    delete k;
1844  }
1845
1846//! obsolete
1847void t2ippa(poly* ip,int* ia,exp_number_builder & e){
1848
1849  int o=0;
1850  t2ippa_rec(ip,ia,e.top_level,o);
1851}
1852int anti_poly_order(const void* a, const void* b){
1853  return -pLmCmp(((int_poly_pair*) a)->p,((int_poly_pair*) b)->p );
1854}
1855
1856BOOLEAN is_valid_ro(red_object & ro){
1857  red_object r2=ro;
1858  ro.validate();
1859  if ((r2.p!=ro.p)||(r2.sev!=ro.sev)) return FALSE;
1860  return TRUE;
1861}
1862int terms_sort_crit(const void* a, const void* b){
1863  return -pLmCmp(*((poly*) a),*((poly*) b));
1864}
1865static void unify_terms(poly* terms,int & sum){
1866  if (sum==0) return;
1867  int last=0;
1868  int curr=1;
1869  while(curr<sum){
1870    if (!(pLmEqual(terms[curr],terms[last]))){
1871      terms[++last]=terms[curr];
1872    }
1873    ++curr;
1874  }
1875  sum=last+1;
1876}
1877static void export_mat(number* number_array,int pn, int tn,const char* format_str, int mat_nr){
1878  char matname[20];
1879  sprintf(matname,format_str,mat_nr);
1880  FILE* out=fopen(matname,"w");
1881  int i,j;
1882  fprintf(out,"mat=[\n");
1883  for(i=0;i<pn;i++){
1884    fprintf(out,"[\n");
1885    for(j=0;j<tn;j++)
1886    {
1887      if (j>0)
1888      {
1889        fprintf(out,", ");
1890      }
1891      fprintf(out,"%i",npInt(number_array[i*tn+j],currRing));
1892    }
1893    if (i<pn-1)
1894      fprintf(out,"],\n");
1895    else
1896      fprintf(out,"],\n");
1897  }
1898  fprintf(out,"]\n");
1899  fclose(out);
1900}
1901//typedef unsigned short number_type;
1902
1903
1904#ifdef USE_NORO
1905#ifndef NORO_CACHE
1906static void linalg_step_modp(poly *p, poly* p_out, int& pn, poly* terms,int tn, slimgb_alg* c){
1907  static int export_n=0;
1908  assume(terms[tn-1]!=NULL);
1909  assume(rField_is_Zp(c->r));
1910  //I don't do deletes, copies of number_types ...
1911  const number_type zero=0;//npInit(0);
1912  int array_size=pn*tn;
1913  number_type* number_array=(number_type*) omalloc(pn*tn*sizeof(number_type));
1914  int i;
1915  for(i=0;i<array_size;i++){
1916    number_array[i]=zero;
1917  }
1918  for(i=0;i<pn;i++){
1919    poly h=p[i];
1920    //int base=tn*i;
1921    write_poly_to_row(number_array+tn*i,h,terms,tn,c->r);
1922
1923  }
1924#if 0
1925  //export matrix
1926  export_mat(number_array,pn,tn,"mat%i.py",++export_n);
1927#endif
1928  int rank=pn;
1929  simplest_gauss_modp(number_array,rank,tn);
1930  int act_row=0;
1931  int p_pos=0;
1932  for(i=0;i<pn;i++){
1933    poly h=NULL;
1934    int j;
1935    int base=tn*i;
1936    number* row=number_array+base;
1937    h=row_to_poly(row,terms,tn,c->r);
1938
1939   if (h!=NULL)
1940   {
1941     p_out[p_pos++]=h;
1942   }
1943  }
1944  pn=p_pos;
1945  //assert(p_pos==rank)
1946  while(p_pos<pn){
1947    p_out[p_pos++]=NULL;
1948  }
1949#if 0
1950  export_mat(number_array,pn,tn,"mat%i.py",++export_n);
1951#endif
1952}
1953#endif
1954#endif
1955static void mass_add(poly* p, int pn,slimgb_alg* c){
1956    int j;
1957    int* ibuf=(int*) omalloc(pn*sizeof(int));
1958    sorted_pair_node*** sbuf=(sorted_pair_node***) omalloc(pn*sizeof(sorted_pair_node**));
1959    for(j=0;j<pn;j++){
1960      p_Test(p[j],c->r);
1961      sbuf[j]=add_to_basis_ideal_quotient(p[j],c,ibuf+j);
1962    }
1963    int sum=0;
1964    for(j=0;j<pn;j++){
1965      sum+=ibuf[j];
1966    }
1967    sorted_pair_node** big_sbuf=(sorted_pair_node**) omalloc(sum*sizeof(sorted_pair_node*));
1968    int partsum=0;
1969    for(j=0;j<pn;j++)
1970    {
1971      memmove(big_sbuf+partsum, sbuf[j],ibuf[j]*sizeof(sorted_pair_node*));
1972      omfree(sbuf[j]);
1973      partsum+=ibuf[j];
1974    }
1975
1976    qsort(big_sbuf,sum,sizeof(sorted_pair_node*),tgb_pair_better_gen2);
1977    c->apairs=spn_merge(c->apairs,c->pair_top+1,big_sbuf,sum,c);
1978    c->pair_top+=sum;
1979    clean_top_of_pair_list(c);
1980    omfree(big_sbuf);
1981    omfree(sbuf);
1982    omfree(ibuf);
1983    //omfree(buf);
1984  #ifdef TGB_DEBUG
1985    int z;
1986    for(z=1;z<=c->pair_top;z++)
1987    {
1988      assume(pair_better(c->apairs[z],c->apairs[z-1],c));
1989    }
1990  #endif
1991
1992}
1993
1994#ifdef NORO_CACHE
1995#ifndef NORO_NON_POLY
1996void NoroCache::evaluateRows(){
1997  //after that can evaluate placeholders
1998  int i;
1999  buffer=(number*) omalloc(nIrreducibleMonomials*sizeof(number));
2000  for(i=0;i<root.branches_len;i++){
2001    evaluateRows(1,root.branches[i]);
2002  }
2003  omfree(buffer);
2004  buffer=NULL;
2005}
2006void NoroCache::evaluateRows(int level, NoroCacheNode* node){
2007  assume(level>=0);
2008  if (node==NULL) return;
2009  if (level<pVariables){
2010    int i,sum;
2011    for(i=0;i<node->branches_len;i++){
2012      evaluateRows(level+1,node->branches[i]);
2013    }
2014  } else {
2015    DataNoroCacheNode* dn=(DataNoroCacheNode*) node;
2016    if (dn->value_len!=backLinkCode){
2017      poly p=dn->value_poly;
2018      #ifndef NORO_SPARSE_ROWS_PRE
2019      dn->row=new DenseRow();
2020      DenseRow* row=dn->row;
2021      memset(buffer,0,sizeof(number)*nIrreducibleMonomials);
2022
2023      if (p==NULL) {row->array=NULL;row->begin=0;row->end=0; return;}
2024      int i=0;
2025      int idx;
2026      number* a=buffer;
2027      while(p){
2028        DataNoroCacheNode* ref=getCacheReference(p);
2029
2030        idx=ref->term_index;
2031        assume(idx>=0);
2032        a[idx]=p_GetCoeff(p,currRing);
2033        if (i==0) row->begin=idx;
2034        i++;
2035        pIter(p);
2036      }
2037      row->end=idx+1;
2038      assume(row->end>row->begin);
2039      int len=row->end-row->begin;
2040      row->array=(number*) omalloc((len)*sizeof(number));
2041      memcpy(row->array,a+row->begin,len*sizeof(number));
2042      #else
2043      assume(dn->value_len==pLength(dn->value_poly));
2044      dn->row=new SparseRow(dn->value_len);
2045      SparseRow* row=dn->row;
2046      int i=0;
2047      while(p){
2048        DataNoroCacheNode* ref=getCacheReference(p);
2049
2050        int idx=ref->term_index;
2051        assume(idx>=0);
2052        row->idx_array[i]=idx;
2053        row->coef_array[i]=p_GetCoeff(p,currRing);
2054
2055        i++;
2056        pIter(p);
2057      }
2058      if (i!=dn->value_len){
2059        PrintS("F4 calc wrong, as poly len was wrong\n");
2060      }
2061      assume(i==dn->value_len);
2062      #endif
2063
2064    }
2065  }
2066}
2067
2068void NoroCache::evaluatePlaceHolder(number* row,std::vector<NoroPlaceHolder>& place_holders){
2069  int i;
2070  int s=place_holders.size();
2071  for(i=0;i<s;i++){
2072    DataNoroCacheNode* ref=place_holders[i].ref;
2073    number coef=place_holders[i].coef;
2074    if (ref->value_len==backLinkCode){
2075      row[ref->term_index]=npAddM(row[ref->term_index],coef);
2076    } else {
2077      #ifndef NORO_SPARSE_ROWS_PRE
2078      DenseRow* ref_row=ref->row;
2079      if (ref_row==NULL) continue;
2080      number* ref_begin=ref_row->array;
2081      number* ref_end=ref_row->array+(ref_row->end-ref_row->begin);
2082      number* my_pos=row+ref_row->begin;
2083      //TODO npisOne distinction
2084      if (!(npIsOne(coef))){
2085        while(ref_begin!=ref_end){
2086
2087          *my_pos=npAddM(*my_pos,npMult(coef,*ref_begin));
2088          ++ref_begin;
2089          ++my_pos;
2090        }
2091      }
2092      else{
2093        while(ref_begin!=ref_end){
2094
2095          *my_pos=npAddM(*my_pos,*ref_begin);
2096          ++ref_begin;
2097          ++my_pos;
2098        }
2099      }
2100
2101
2102
2103    #else
2104    SparseRow* ref_row=ref->row;
2105    if (ref_row==NULL) continue;
2106    int n=ref_row->len;
2107    int j;
2108    int* idx_array=ref_row->idx_array;
2109    number* coef_array=ref_row->coef_array;
2110    for(j=0;j<n;j++){
2111      int idx=idx_array[j];
2112      number ref_coef=coef_array[j];
2113      row[idx]=npAddM(row[idx],npMult(coef,ref_coef));
2114    }
2115    #endif
2116  }
2117  }
2118
2119}
2120#endif
2121
2122
2123
2124//poly noro_red_non_unique(poly p, int &len, NoroCache* cache,slimgb_alg* c);
2125
2126
2127#ifndef NORO_NON_POLY
2128MonRedRes noro_red_mon(poly t, BOOLEAN force_unique, NoroCache* cache,slimgb_alg* c){
2129  MonRedRes res_holder;
2130
2131  //wrp(t);
2132  res_holder.changed=TRUE;
2133  if (force_unique){
2134    DataNoroCacheNode* ref=cache->getCacheReference(t);
2135    if (ref!=NULL){
2136      res_holder.len=ref->value_len;
2137      if (res_holder.len==NoroCache::backLinkCode){
2138        res_holder.len=1;
2139
2140
2141      }
2142      res_holder.coef=p_GetCoeff(t,c->r);
2143      res_holder.p=ref->value_poly;
2144      res_holder.ref=ref;
2145      res_holder.onlyBorrowed=TRUE;
2146      res_holder.changed=TRUE;
2147      p_Delete(&t,c->r);
2148      return res_holder;
2149    }
2150  } else{
2151    BOOLEAN succ;
2152    poly cache_lookup=cache->lookup(t,succ, res_holder.len);//don't own this yet
2153    if (succ){
2154      if (cache_lookup==t){
2155      //know they are equal
2156      //res_holder.len=1;
2157
2158        res_holder.changed=FALSE;
2159        res_holder.p=t;
2160        res_holder.coef=npInit(1);
2161
2162        res_holder.onlyBorrowed=FALSE;
2163        return res_holder;
2164      }
2165
2166      res_holder.coef=p_GetCoeff(t,c->r);
2167      p_Delete(&t,c->r);
2168
2169      res_holder.p=cache_lookup;
2170
2171      res_holder.onlyBorrowed=TRUE;
2172      return res_holder;
2173
2174    }
2175  }
2176
2177  unsigned long sev=p_GetShortExpVector(t,currRing);
2178  int i=kFindDivisibleByInS_easy(c->strat,t,sev);
2179  if (i>=0)
2180  {
2181    number coef_bak=p_GetCoeff(t,c->r);
2182
2183    p_SetCoeff(t,npInit(1),c->r);
2184    assume(npIsOne(p_GetCoeff(c->strat->S[i],c->r)));
2185    number coefstrat=p_GetCoeff(c->strat->S[i],c->r);
2186
2187      //poly t_copy_mon=p_Copy(t,c->r);
2188    poly exp_diff=cache->temp_term;
2189    p_ExpVectorDiff(exp_diff,t,c->strat->S[i],c->r);
2190    p_SetCoeff(exp_diff,npNeg(nInvers(coefstrat)),c->r); 
2191      // nInvers may be npInvers or nvInvers
2192    p_Setm(exp_diff,c->r);
2193    assume(c->strat->S[i]!=NULL);
2194      //poly t_to_del=t;
2195    poly res;
2196    res=pp_Mult_mm(pNext(c->strat->S[i]),exp_diff,c->r);
2197
2198    res_holder.len=c->strat->lenS[i]-1;
2199    res=noro_red_non_unique(res,res_holder.len,cache,c);
2200
2201    DataNoroCacheNode* ref=cache->insert(t,res,res_holder.len);
2202    p_Delete(&t,c->r);
2203      //p_Delete(&t_copy_mon,c->r);
2204      //res=pMult_nn(res,coef_bak);
2205
2206    res_holder.changed=TRUE;
2207    res_holder.p=res;
2208    res_holder.coef=coef_bak;
2209    res_holder.onlyBorrowed=TRUE;
2210    res_holder.ref=ref;
2211    return res_holder;
2212
2213  } else {
2214    number coef_bak=p_GetCoeff(t,c->r);
2215    number one=npInit(1);
2216    p_SetCoeff(t,one,c->r);
2217    res_holder.len=1;
2218    if (!(force_unique)){
2219      res_holder.ref=cache->insert(t,t,res_holder.len);
2220      p_SetCoeff(t,coef_bak,c->r);
2221      //return t;
2222
2223      //we need distinction
2224      res_holder.changed=FALSE;
2225      res_holder.p=t;
2226
2227      res_holder.coef=npInit(1);
2228      res_holder.onlyBorrowed=FALSE;
2229      return res_holder;
2230    } else {
2231      res_holder.ref=cache->insertAndTransferOwnerShip(t,c->r);
2232      res_holder.coef=coef_bak;
2233      res_holder.onlyBorrowed=TRUE;
2234      res_holder.changed=FALSE;
2235      res_holder.p=t;
2236      return res_holder;
2237    }
2238  }
2239
2240}
2241#endif
2242//SparseRow* noro_red_to_non_poly(poly p, int &len, NoroCache* cache,slimgb_alg* c);
2243#ifndef NORO_NON_POLY
2244//len input and out: Idea: reverse addition
2245poly noro_red_non_unique(poly p, int &len, NoroCache* cache,slimgb_alg* c){
2246  assume(len==pLength(p));
2247  poly orig_p=p;
2248  if (p==NULL) {
2249    len=0;
2250    return NULL;
2251  }
2252  kBucket_pt bucket=kBucketCreate(currRing);
2253  kBucketInit(bucket,NULL,0);
2254  poly unchanged_head=NULL;
2255  poly unchanged_tail=NULL;
2256  int unchanged_size=0;
2257
2258  while(p){
2259    poly t=p;
2260    pIter(p);
2261    pNext(t)=NULL;
2262#ifndef NDEBUG
2263    number coef_debug=p_GetCoeff(t,currRing);
2264#endif
2265    MonRedRes red=noro_red_mon(t,FALSE,cache,c);
2266    if ((!(red.changed))&&(!(red.onlyBorrowed))){
2267      unchanged_size++;
2268      assume(npIsOne(red.coef));
2269      assume(p_GetCoeff(red.p,currRing)==coef_debug);
2270      if (unchanged_head){
2271        pNext(unchanged_tail)=red.p;
2272        pIter(unchanged_tail);
2273      } else{
2274        unchanged_tail=red.p;
2275        unchanged_head=red.p;
2276      }
2277    } else{
2278      assume(red.len==pLength(red.p));
2279      if (red.onlyBorrowed){
2280        if (npIsOne(red.coef)){
2281          t=p_Copy(red.p,currRing);
2282        }else
2283        t=pp_Mult_nn(red.p,red.coef,currRing);
2284      } else {
2285        if (npIsOne(red.coef))
2286        t=red.p;
2287        else
2288         t=p_Mult_nn(red.p,red.coef,currRing);
2289      }
2290      kBucket_Add_q(bucket,t,&red.len);
2291    }
2292  }
2293  poly res=NULL;
2294  len=0;
2295  kBucket_Add_q(bucket,unchanged_head,&unchanged_size);
2296  kBucketClear(bucket,&res,&len);
2297  kBucketDestroy(&bucket);
2298
2299
2300
2301
2302  return res;
2303}
2304#endif
2305#ifdef NORO_SPARSE_ROWS_PRE
2306//len input and out: Idea: reverse addition
2307
2308/*template <class number_type> SparseRow<number_type>* noro_red_to_non_poly(poly p, int &len, NoroCache<number_type>* cache,slimgb_alg* c){
2309  if (npPrimeM<255){
2310    return noro_red_to_non_poly_t<tgb_uint8>(p,len,cache,c);
2311  } else {
2312    if (npPrimeM<65000){
2313      return noro_red_to_non_poly_t<tgb_uint16>(p,len,cache,c);
2314    } else{
2315      return noro_red_to_non_poly_t<tgb_uint32>(p,len,cache,c);
2316    }
2317  }
2318}*/
2319#endif
2320//len input and out: Idea: reverse addition
2321#ifndef NORO_NON_POLY
2322std::vector<NoroPlaceHolder> noro_red(poly p, int &len, NoroCache* cache,slimgb_alg* c){
2323  std::vector<NoroPlaceHolder> res;
2324   while(p){
2325      poly t=p;
2326      pIter(p);
2327      pNext(t)=NULL;
2328
2329      MonRedRes red=noro_red_mon(t,TRUE,cache,c);
2330      assume(red.onlyBorrowed);
2331      assume(red.coef);
2332      assume(red.ref);
2333      NoroPlaceHolder h;
2334      h.ref=red.ref;
2335      h.coef=red.coef;
2336      assume(!((h.ref->value_poly==NULL) &&(h.ref->value_len!=0)));
2337      if (h.ref->value_poly)
2338        res.push_back(h);
2339    }
2340    return res;
2341}
2342#endif
2343
2344
2345
2346
2347
2348#endif
2349#ifdef USE_NORO
2350#ifndef NORO_CACHE
2351void noro_step(poly*p,int &pn,slimgb_alg* c){
2352  poly* reduced=(poly*) omalloc(pn*sizeof(poly));
2353  int j;
2354  int* reduced_len=(int*) omalloc(pn*sizeof(int));
2355  int reduced_c=0;
2356  //if (TEST_OPT_PROT)
2357  //  PrintS("reduced system:\n");
2358#ifdef NORO_CACHE
2359  NoroCache cache;
2360#endif
2361  for(j=0;j<pn;j++){
2362
2363    poly h=p[j];
2364    int h_len=pLength(h);
2365
2366    number coef;
2367#ifndef NORO_CACHE
2368    h=redNF2(p_Copy(h,c->r),c,h_len,coef,0);
2369#else
2370    h=noro_red(p_Copy(h,c->r),h_len,&cache,c);
2371    assume(pLength(h)==h_len);
2372#endif
2373    if (h!=NULL){
2374#ifndef NORO_CACHE
2375
2376      h=redNFTail(h,c->strat->sl,c->strat,h_len);
2377      h_len=pLength(h);
2378#endif
2379
2380
2381      reduced[reduced_c]=h;
2382      reduced_len[reduced_c]=h_len;
2383      reduced_c++;
2384      if (TEST_OPT_PROT)
2385        Print("%d ",h_len);
2386    }
2387  }
2388  int reduced_sum=0;
2389  for(j=0;j<reduced_c;j++){
2390    reduced_sum+=reduced_len[j];
2391  }
2392  poly* terms=(poly*) omalloc(reduced_sum*sizeof(poly));
2393  int tc=0;
2394  for(j=0;j<reduced_c;j++){
2395    poly h=reduced[j];
2396
2397    while(h!=NULL){
2398      terms[tc++]=h;
2399      pIter(h);
2400      assume(tc<=reduced_sum);
2401    }
2402  }
2403  assume(tc==reduced_sum);
2404  qsort(terms,reduced_sum,sizeof(poly),terms_sort_crit);
2405  int nterms=reduced_sum;
2406  //if (TEST_OPT_PROT)
2407  //Print("orig estimation:%i\n",reduced_sum);
2408  unify_terms(terms,nterms);
2409  //if (TEST_OPT_PROT)
2410  //    Print("actual number of columns:%i\n",nterms);
2411  int rank=reduced_c;
2412  linalg_step_modp(reduced, p,rank,terms,nterms,c);
2413  omfree(terms);
2414
2415  pn=rank;
2416  omfree(reduced);
2417
2418  if (TEST_OPT_PROT)
2419    PrintS("\n");
2420}
2421#else
2422
2423
2424
2425#endif
2426#endif
2427static void go_on (slimgb_alg* c){
2428  //set limit of 1000 for multireductions, at the moment for
2429  //programming reasons
2430  #ifdef USE_NORO
2431  //Print("module rank%d\n",c->S->rank);
2432    const BOOLEAN use_noro=c->use_noro;
2433  #else
2434  const BOOLEAN use_noro=FALSE;
2435  #endif
2436  int i=0;
2437  c->average_length=0;
2438  for(i=0;i<c->n;i++){
2439    c->average_length+=c->lengths[i];
2440  }
2441  c->average_length=c->average_length/c->n;
2442  i=0;
2443  int max_pairs=bundle_size;
2444
2445  #ifdef USE_NORO
2446  if ((use_noro)||(c->use_noro_last_block))
2447    max_pairs=bundle_size_noro;
2448  #endif
2449  poly* p=(poly*) omalloc((max_pairs+1)*sizeof(poly));//nullterminated
2450
2451  int curr_deg=-1;
2452  while(i<max_pairs){
2453    sorted_pair_node* s=top_pair(c);//here is actually chain criterium done
2454
2455
2456    if (!s) break;
2457
2458    if(curr_deg>=0){
2459      if (s->deg >curr_deg) break;
2460    }
2461
2462    else curr_deg=s->deg;
2463    quick_pop_pair(c);
2464    if(s->i>=0){
2465      //be careful replace_pair use createShortSpoly which is not noncommutative
2466      now_t_rep(s->i,s->j,c);
2467    replace_pair(s->i,s->j,c);
2468
2469    if(s->i==s->j) {
2470      free_sorted_pair_node(s,c->r);
2471      continue;
2472    }
2473    now_t_rep(s->i,s->j,c);
2474    }
2475    poly h;
2476    if(s->i>=0)
2477    {
2478#ifdef HAVE_PLURAL
2479      if (c->nc){
2480        h= nc_CreateSpoly(c->S->m[s->i], c->S->m[s->j]/*, NULL*/, c->r);
2481
2482        if (h!=NULL)
2483          pCleardenom(h);
2484      }
2485      else
2486#endif
2487        h=ksOldCreateSpoly(c->S->m[s->i], c->S->m[s->j], NULL, c->r);
2488    p_Test(h,c->r);
2489    }
2490    else{
2491      h=s->lcm_of_lm;
2492      p_Test(h,c->r);
2493  }
2494    // if(s->i>=0)
2495//       now_t_rep(s->j,s->i,c);
2496    number coef;
2497    int mlen=pLength(h);
2498    p_Test(h,c->r);
2499    if ((!c->nc)&(!(use_noro))){
2500      h=redNF2(h,c,mlen,coef,2);
2501      redTailShort(h,c->strat);
2502      nDelete(&coef);
2503    }
2504    p_Test(h,c->r);
2505    free_sorted_pair_node(s,c->r);
2506    if(!h) continue;
2507    int len=pLength(h);
2508    p[i]=h;
2509
2510    i++;
2511  }
2512  p[i]=NULL;
2513//  pre_comp(p,i,c);
2514  if(i==0){
2515    omfree(p);
2516    return;
2517  }
2518  #ifdef TGB_RESORT_PAIRS
2519  c->replaced=new bool[c->n];
2520  c->used_b=FALSE;
2521  #endif
2522
2523  c->normal_forms+=i;
2524  int j;
2525#ifdef USE_NORO
2526  //if ((!(c->nc))&&(rField_is_Zp(c->r))){
2527  if (use_noro){
2528    int pn=i;
2529    if (pn==0) {omfree(p);return;}
2530
2531    {
2532
2533      if (npPrimeM<255){
2534        noro_step<tgb_uint8>(p,pn,c);
2535      } else {
2536        if (npPrimeM<65000){
2537          noro_step<tgb_uint16>(p,pn,c);
2538        } else{
2539          noro_step<tgb_uint32>(p,pn,c);
2540        }
2541      }
2542
2543
2544
2545    }
2546
2547    //if (TEST_OPT_PROT){
2548    //  Print("reported rank:%i\n",pn);
2549    //}
2550    mass_add(p,pn,c);
2551    omfree(p);
2552    return;
2553    /*if (TEST_OPT_PROT)
2554      for(j=0;j<pn;j++){
2555        p_wrp(p[j],c->r);
2556      }*/
2557  }
2558#endif
2559  red_object* buf=(red_object*) omalloc(i*sizeof(red_object));
2560  for(j=0;j<i;j++){
2561    p_Test(p[j],c->r);
2562    buf[j].p=p[j];
2563    buf[j].sev=pGetShortExpVector(p[j]);
2564    buf[j].bucket = kBucketCreate(currRing);
2565    p_Test(p[j],c->r);
2566    if (c->eliminationProblem){
2567        buf[j].sugar=c->pTotaldegree_full(p[j]);
2568    }
2569    int len=pLength(p[j]);
2570    kBucketInit(buf[j].bucket,buf[j].p,len);
2571    buf[j].initial_quality=buf[j].guess_quality(c);
2572    assume(buf[j].initial_quality>=0);
2573  }
2574  omfree(p);
2575  qsort(buf,i,sizeof(red_object),red_object_better_gen);
2576//    Print("\ncurr_deg:%i\n",curr_deg);
2577  if (TEST_OPT_PROT)
2578  {
2579    Print("%dM[%d,",curr_deg,i);
2580  }
2581
2582  multi_reduction(buf, i, c);
2583  #ifdef TGB_RESORT_PAIRS
2584  if (c->used_b) {
2585    if (TEST_OPT_PROT)
2586        PrintS("B");
2587    int e;
2588    for(e=0;e<=c->pair_top;e++){
2589        if(c->apairs[e]->i<0) continue;
2590        assume(c->apairs[e]->j>=0);
2591        if ((c->replaced[c->apairs[e]->i])||(c->replaced[c->apairs[e]->j])) {
2592            sorted_pair_node* s=c->apairs[e];
2593            s->expected_length=pair_weighted_length(s->i,s->j,c);
2594        }
2595    }
2596    qsort(c->apairs,c->pair_top+1,sizeof(sorted_pair_node*),tgb_pair_better_gen2);
2597  }
2598  #endif
2599#ifdef TGB_DEBUG
2600 {
2601   int k;
2602   for(k=0;k<i;k++)
2603   {
2604     assume(kFindDivisibleByInS_easy(c->strat,buf[k])<0);
2605     int k2;
2606     for(k2=0;k2<i;k2++)
2607     {
2608       if(k==k2) continue;
2609       assume((!(p_LmDivisibleBy(buf[k].p,buf[k2].p,c->r)))||(wrp(buf[k].p),Print(" k %d k2 %d ",k,k2),wrp(buf[k2].p),FALSE));
2610     }
2611   }
2612 }
2613#endif
2614  //resort S
2615
2616  if (TEST_OPT_PROT)
2617      Print("%i]",i);
2618
2619  poly* add_those=(poly*) omalloc(i*sizeof(poly));
2620  for(j=0;j<i;j++)
2621  {
2622    int len;
2623    poly p;
2624    buf[j].flatten();
2625    kBucketClear(buf[j].bucket,&p, &len);
2626    kBucketDestroy(&buf[j].bucket);
2627    p_Test(p,c->r);
2628    //if (!c->nc) {
2629      if ((c->tailReductions) ||(lies_in_last_dp_block(p,c))){
2630      p=redNFTail(p,c->strat->sl,c->strat, 0);
2631      } else {
2632      p=redTailShort(p, c->strat);
2633      }
2634      //}
2635      p_Test(p,c->r);
2636      add_those[j]=p;
2637
2638    //sbuf[j]=add_to_basis(p,-1,-1,c,ibuf+j);
2639  }
2640  mass_add(add_those,i,c);
2641  omfree(add_those);
2642  omfree(buf);
2643
2644
2645
2646
2647
2648
2649
2650  if (TEST_OPT_PROT)
2651      Print("(%d)",c->pair_top+1);
2652  //TODO: implement that while(!(idIs0(c->add_later)))
2653  #ifdef TGB_RESORT_PAIRS
2654  delete c->replaced;
2655  c->replaced=NULL;
2656  c->used_b=FALSE;
2657  #endif
2658  return;
2659}
2660
2661
2662
2663#ifdef REDTAIL_S
2664
2665static poly redNFTail (poly h,const int sl,kStrategy strat, int len)
2666{
2667  BOOLEAN nc=rIsPluralRing(currRing);
2668  if (h==NULL) return NULL;
2669  pTest(h);
2670  if (0 > sl)
2671    return h;
2672  if (pNext(h)==NULL) return h;
2673
2674  int j;
2675  poly res=h;
2676  poly act=res;
2677  LObject P(pNext(h));
2678  pNext(res)=NULL;
2679  P.bucket = kBucketCreate(currRing);
2680  len--;
2681  h=P.p;
2682  if (len <=0) len=pLength(h);
2683  kBucketInit(P.bucket,h /*P.p*/,len /*pLength(P.p)*/);
2684  pTest(h);
2685  loop
2686  {
2687      P.p=h;
2688      P.t_p=NULL;
2689      P.SetShortExpVector();
2690      loop
2691      {
2692          int dummy=strat->sl;
2693          j=kFindDivisibleByInS_easy(strat,P.p,P.sev);//kFindDivisibleByInS(strat,&dummy,&P);
2694          if (j>=0)
2695          {
2696#ifdef REDTAIL_PROT
2697            PrintS("r");
2698#endif
2699            nNormalize(pGetCoeff(P.p));
2700#ifdef KDEBUG
2701            if (TEST_OPT_DEBUG)
2702            {
2703              PrintS("red tail:");
2704              wrp(h);
2705              PrintS(" with ");
2706              wrp(strat->S[j]);
2707            }
2708#endif
2709            number coef;
2710            pTest(strat->S[j]);
2711#ifdef HAVE_PLURAL
2712            if (nc){
2713              nc_BucketPolyRed_Z(P.bucket, strat->S[j], &coef);
2714            } else
2715#endif
2716              coef=kBucketPolyRed(P.bucket,strat->S[j],
2717                                strat->lenS[j]/*pLength(strat->S[j])*/,strat->kNoether);
2718            pMult_nn(res,coef);
2719            nDelete(&coef);
2720            h = kBucketGetLm(P.bucket);
2721            pTest(h);
2722            if (h==NULL)
2723            {
2724#ifdef REDTAIL_PROT
2725              PrintS(" ");
2726#endif
2727        kBucketDestroy(&P.bucket);
2728              return res;
2729            }
2730            pTest(h);
2731            P.p=h;
2732            P.t_p=NULL;
2733            P.SetShortExpVector();
2734#ifdef KDEBUG
2735            if (TEST_OPT_DEBUG)
2736            {
2737              PrintS("\nto tail:");
2738              wrp(h);
2739              PrintLn();
2740            }
2741#endif
2742          }
2743          else
2744          {
2745#ifdef REDTAIL_PROT
2746            PrintS("n");
2747#endif
2748            break;
2749          }
2750      } /* end loop current mon */
2751      //   poly tmp=pHead(h /*kBucketGetLm(P.bucket)*/);
2752      //act->next=tmp;pIter(act);
2753      act->next=kBucketExtractLm(P.bucket);pIter(act);
2754      h = kBucketGetLm(P.bucket);
2755      if (h==NULL)
2756      {
2757#ifdef REDTAIL_PROT
2758        PrintS(" ");
2759#endif
2760  kBucketDestroy(&P.bucket);
2761        return res;
2762      }
2763      pTest(h);
2764  }
2765}
2766#endif
2767
2768
2769//try to fill, return FALSE iff queue is empty
2770
2771//transfers ownership of m to mat
2772void init_with_mac_poly(tgb_sparse_matrix* mat, int row, mac_poly m){
2773  assume(mat->mp[row]==NULL);
2774  mat->mp[row]=m;
2775#ifdef TGB_DEBUG
2776  mac_poly r=m;
2777  while(r){
2778    assume(r->exp<mat->columns);
2779    r=r->next;
2780  }
2781#endif
2782}
2783poly free_row_to_poly(tgb_sparse_matrix* mat, int row, poly* monoms, int monom_index){
2784  poly p=NULL;
2785  poly* set_this=&p;
2786  mac_poly r=mat->mp[row];
2787  mat->mp[row]=NULL;
2788  while(r)
2789  {
2790    (*set_this)=pLmInit(monoms[monom_index-1-r->exp]);
2791    pSetCoeff((*set_this),r->coef);
2792    set_this=&((*set_this)->next);
2793    mac_poly old=r;
2794    r=r->next;
2795    delete old;
2796
2797  }
2798  return p;
2799
2800}
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812static int poly_crit(const void* ap1, const void* ap2){
2813  poly p1,p2;
2814  p1=*((poly*) ap1);
2815  p2=*((poly*)ap2);
2816
2817  int c=pLmCmp(p1,p2);
2818  if (c !=0) return c;
2819  int l1=pLength(p1);
2820  int l2=pLength(p2);
2821  if (l1<l2) return -1;
2822  if (l1>l2) return 1;
2823  return 0;
2824}
2825void slimgb_alg::introduceDelayedPairs(poly* pa,int s){
2826    if (s==0) return;
2827    sorted_pair_node** si_array=(sorted_pair_node**) omalloc(s* sizeof(sorted_pair_node*));
2828
2829    for( unsigned int i = 0; i < s; i++ )
2830    {
2831        sorted_pair_node* si=(sorted_pair_node*) omalloc(sizeof(sorted_pair_node));
2832        si->i=-1;
2833        si->j=-2;
2834        poly p=pa[i];
2835        simplify_poly(p,r);
2836        si->expected_length=pQuality(p,this,pLength(p));
2837        p_Test(p,r);
2838        si->deg=this->pTotaldegree_full(p);
2839        /*if (!rField_is_Zp(r)){
2840          pContent(p);
2841          pCleardenom(p);
2842        }*/
2843
2844        si->lcm_of_lm=p;
2845
2846        //      c->apairs[n-1-i]=si;
2847        si_array[i]=si;
2848
2849  }
2850
2851  qsort(si_array,s,sizeof(sorted_pair_node*),tgb_pair_better_gen2);
2852    apairs=spn_merge(apairs,pair_top+1,si_array,s,this);
2853  pair_top+=s;
2854  omfree(si_array);
2855}
2856slimgb_alg::slimgb_alg(ideal I, int syz_comp,BOOLEAN F4,int deg_pos){
2857  this->deg_pos=deg_pos;
2858  lastCleanedDeg=-1;
2859  completed=FALSE;
2860  this->syz_comp=syz_comp;
2861  r=currRing;
2862  nc=rIsPluralRing(r);
2863  this->lastDpBlockStart=get_last_dp_block_start(r);
2864  //Print("last dp Block start: %i\n", this->lastDpBlockStart);
2865  is_homog=TRUE;
2866  {
2867    int hzz;
2868    for(hzz=0;hzz<IDELEMS(I);hzz++){
2869      assume(I->m[hzz]!=NULL);
2870      int d=this->pTotaldegree(I->m[hzz]);
2871      poly t=I->m[hzz]->next;
2872      while(t)
2873      {
2874        if (d!=this->pTotaldegree(t))
2875        {
2876          is_homog=FALSE;
2877          break;
2878        }
2879        t=t->next;
2880      }
2881      if(!(is_homog)) break;
2882    }
2883  }
2884  eliminationProblem=((!(is_homog))&&((pLexOrder)||(I->rank>1)));
2885  tailReductions=((is_homog)||((TEST_OPT_REDTAIL)&&(!(I->rank>1))));
2886  //  Print("is homog:%d",c->is_homog);
2887  void* h;
2888  poly hp;
2889  int i,j;
2890  to_destroy=NULL;
2891  easy_product_crit=0;
2892  extended_product_crit=0;
2893  if (rField_is_Zp(r))
2894    isDifficultField=FALSE;
2895  else
2896    isDifficultField=TRUE;
2897  //not fully correct
2898  //(rChar()==0);
2899  F4_mode=F4;
2900
2901  reduction_steps=0;
2902  last_index=-1;
2903
2904  F=NULL;
2905  F_minus=NULL;
2906
2907  Rcounter=0;
2908
2909  soon_free=NULL;
2910
2911  tmp_lm=pOne();
2912
2913  normal_forms=0;
2914  current_degree=1;
2915
2916  max_pairs=5*IDELEMS(I);
2917
2918  apairs=(sorted_pair_node**) omalloc(sizeof(sorted_pair_node*)*max_pairs);
2919  pair_top=-1;
2920
2921  int n=IDELEMS(I);
2922  array_lengths=n;
2923
2924
2925  i=0;
2926  this->n=0;
2927  T_deg=(int*) omalloc(n*sizeof(int));
2928  if(eliminationProblem)
2929    T_deg_full=(int*) omalloc(n*sizeof(int));
2930  else
2931    T_deg_full=NULL;
2932  tmp_pair_lm=(poly*) omalloc(n*sizeof(poly));
2933  tmp_spn=(sorted_pair_node**) omalloc(n*sizeof(sorted_pair_node*));
2934  lm_bin=omGetSpecBin(POLYSIZE + (r->ExpL_Size)*sizeof(long));
2935#ifdef HEAD_BIN
2936  HeadBin=omGetSpecBin(POLYSIZE + (currRing->ExpL_Size)*sizeof(long));
2937#endif
2938  /* omUnGetSpecBin(&(c->HeadBin)); */
2939  #ifndef HAVE_BOOST
2940  #ifdef USE_STDVECBOOL
2941  #else
2942  h=omalloc(n*sizeof(char*));
2943
2944  states=(char**) h;
2945  #endif
2946  #endif
2947  h=omalloc(n*sizeof(int));
2948  lengths=(int*) h;
2949  weighted_lengths=(wlen_type*)omalloc(n*sizeof(wlen_type));
2950  gcd_of_terms=(poly*) omalloc(n*sizeof(poly));
2951
2952  short_Exps=(long*) omalloc(n*sizeof(long));
2953  if (F4_mode)
2954    S=idInit(n,I->rank);
2955  else
2956    S=idInit(1,I->rank);
2957  strat=new skStrategy;
2958  if (eliminationProblem)
2959    strat->honey=TRUE;
2960  strat->syzComp = 0;
2961  initBuchMoraCrit(strat);
2962  initBuchMoraPos(strat);
2963  strat->initEcart = initEcartBBA;
2964  strat->tailRing=r;
2965  strat->enterS = enterSBba;
2966  strat->sl = -1;
2967  i=n;
2968  i=1;//some strange bug else
2969  /* initS(c->S,NULL,c->strat); */
2970  /* intS start: */
2971  // i=((i+IDELEMS(c->S)+15)/16)*16;
2972  strat->ecartS=(intset)omAlloc(i*sizeof(int)); /*initec(i);*/
2973  strat->sevS=(unsigned long*)omAlloc0(i*sizeof(unsigned long));
2974  /*initsevS(i);*/
2975  strat->S_2_R=(int*)omAlloc0(i*sizeof(int));/*initS_2_R(i);*/
2976  strat->fromQ=NULL;
2977  strat->Shdl=idInit(1,1);
2978  strat->S=strat->Shdl->m;
2979  strat->lenS=(int*)omAlloc0(i*sizeof(int));
2980  if((isDifficultField)||(eliminationProblem))
2981    strat->lenSw=(wlen_type*)omAlloc0(i*sizeof(wlen_type));
2982  else
2983    strat->lenSw=NULL;
2984  sorted_pair_node* si;
2985  assume(n>0);
2986  add_to_basis_ideal_quotient(I->m[0],this,NULL);
2987
2988  assume(strat->sl==IDELEMS(strat->Shdl)-1);
2989  if(!(F4_mode))
2990  {
2991        poly* array_arg=I->m;
2992        array_arg++;
2993        introduceDelayedPairs(array_arg,n-1);
2994        /*
2995    for (i=1;i<n;i++)//the 1 is wanted, because first element is added to basis
2996    {
2997      //     add_to_basis(I->m[i],-1,-1,c);
2998      si=(sorted_pair_node*) omalloc(sizeof(sorted_pair_node));
2999      si->i=-1;
3000      si->j=-2;
3001      si->expected_length=pQuality(I->m[i],this,pLength(I->m[i]));
3002      si->deg=pTotaldegree(I->m[i]);
3003      if (!rField_is_Zp(r)){
3004        pCleardenom(I->m[i]);
3005      }
3006      si->lcm_of_lm=I->m[i];
3007
3008      //      c->apairs[n-1-i]=si;
3009      apairs[n-i-1]=si;
3010      ++(pair_top);
3011    }*/
3012  }
3013  else
3014  {
3015    for (i=1;i<n;i++)//the 1 is wanted, because first element is added to basis
3016      add_to_basis_ideal_quotient(I->m[i],this,NULL);
3017  }
3018  for(i=0;i<IDELEMS(I);i++)
3019  {
3020    I->m[i]=NULL;
3021  }
3022  idDelete(&I);
3023  add_later=idInit(ADD_LATER_SIZE,S->rank);
3024  #ifdef USE_NORO
3025  use_noro=((!(nc))&&(S->rank<=1)&&(rField_is_Zp(r)) &&(!(eliminationProblem))&&(npPrimeM<=32003));
3026  use_noro_last_block=false;
3027  if ((!(use_noro))&&(lastDpBlockStart<=pVariables)){
3028      use_noro_last_block=((!(nc))&&(S->rank<=1)&&(rField_is_Zp(r)) &&(npPrimeM<=32003));
3029  }
3030  #else
3031  use_noro=false;
3032  use_noro_last_block=false;
3033  #endif
3034  //Print("NORO last block %i",use_noro_last_block);
3035  memset(add_later->m,0,ADD_LATER_SIZE*sizeof(poly));
3036}
3037slimgb_alg::~slimgb_alg(){
3038
3039  if (!(completed)){
3040      poly* add=(poly*) omalloc((pair_top+2)*sizeof(poly));
3041      int piter;
3042      int pos=0;
3043      for(piter=0;piter<=pair_top;piter++){
3044        sorted_pair_node* s=apairs[piter];
3045        if (s->i<0){
3046            //delayed element
3047            if (s->lcm_of_lm!=NULL){
3048                add[pos]=s->lcm_of_lm;
3049                pos++;
3050
3051            }
3052        }
3053
3054        free_sorted_pair_node(s,r);
3055        apairs[piter]=NULL;
3056      }
3057      pair_top=-1;
3058      add[pos]=NULL;
3059      pos=0;
3060      while(add[pos]!=NULL){
3061        add_to_basis_ideal_quotient(add[pos],this,NULL);
3062        pos++;
3063      }
3064      for(piter=0;piter<=pair_top;piter++){
3065        sorted_pair_node* s=apairs[piter];
3066        assume(s->i>=0);
3067        free_sorted_pair_node(s,r);
3068        apairs[piter]=NULL;
3069      }
3070      pair_top=-1;
3071  }
3072  id_Delete(&add_later,r);
3073  int i,j;
3074  slimgb_alg* c=this;
3075  while(c->to_destroy)
3076  {
3077    pDelete(&(c->to_destroy->p));
3078    poly_list_node* old=c->to_destroy;
3079    c->to_destroy=c->to_destroy->next;
3080    omfree(old);
3081  }
3082  while(c->F)
3083  {
3084    for(i=0;i<c->F->size;i++){
3085      pDelete(&(c->F->mp[i].m));
3086    }
3087    omfree(c->F->mp);
3088    c->F->mp=NULL;
3089    mp_array_list* old=c->F;
3090    c->F=c->F->next;
3091    omfree(old);
3092  }
3093  while(c->F_minus)
3094  {
3095    for(i=0;i<c->F_minus->size;i++){
3096      pDelete(&(c->F_minus->p[i]));
3097    }
3098    omfree(c->F_minus->p);
3099    c->F_minus->p=NULL;
3100    poly_array_list* old=c->F_minus;
3101    c->F_minus=c->F_minus->next;
3102    omfree(old);
3103  }
3104  #ifndef HAVE_BOOST
3105  #ifndef USE_STDVECBOOL
3106  for(int z=1 /* zero length at 0 */;z<c->n;z++){
3107    omfree(c->states[z]);
3108  }
3109  omfree(c->states);
3110  #endif
3111  #endif
3112
3113  omfree(c->lengths);
3114  omfree(c->weighted_lengths);
3115  for(int z=0;z<c->n;z++)
3116  {
3117    pDelete(&c->tmp_pair_lm[z]);
3118    omfree(c->tmp_spn[z]);
3119  }
3120  omfree(c->tmp_pair_lm);
3121  omfree(c->tmp_spn);
3122
3123  omfree(c->T_deg);
3124  if(c->T_deg_full)
3125    omfree(c->T_deg_full);
3126
3127  omFree(c->strat->ecartS);
3128  omFree(c->strat->sevS);
3129//   initsevS(i);
3130  omFree(c->strat->S_2_R);
3131
3132
3133  omFree(c->strat->lenS);
3134
3135  if(c->strat->lenSw)  omFree(c->strat->lenSw);
3136
3137
3138
3139
3140  for(i=0;i<c->n;i++){
3141    if(c->gcd_of_terms[i])
3142      pDelete(&(c->gcd_of_terms[i]));
3143  }
3144  omfree(c->gcd_of_terms);
3145
3146  omfree(c->apairs);
3147  if (TEST_OPT_PROT)
3148  {
3149    //Print("calculated %d NFs\n",c->normal_forms);
3150      Print("\nNF:%i product criterion:%i, ext_product criterion:%i \n", c->normal_forms, c->easy_product_crit, c->extended_product_crit);
3151
3152
3153  }
3154  int deleted_form_c_s=0;
3155
3156  for(i=0;i<=c->strat->sl;i++){
3157    if (!c->strat->S[i]) continue;
3158    BOOLEAN found=FALSE;
3159    for(j=0;j<c->n;j++){
3160      if (c->S->m[j]==c->strat->S[i]){
3161        found=TRUE;
3162        break;
3163      }
3164    }
3165    if(!found) pDelete(&c->strat->S[i]);
3166  }
3167//   for(i=0;i<c->n;i++){
3168//     if (c->rep[i]!=i){
3169// //       for(j=0;j<=c->strat->sl;j++){
3170// //   if(c->strat->S[j]==c->S->m[i]){
3171// //     c->strat->S[j]=NULL;
3172// //     break;
3173// //   }
3174// //       }
3175// //      PrintS("R_delete");
3176//       pDelete(&c->S->m[i]);
3177//     }
3178//   }
3179
3180  if (completed){
3181  for(i=0;i<c->n;i++)
3182  {
3183    assume(c->S->m[i]!=NULL);
3184    if (p_GetComp(c->S->m[i],currRing)>this->syz_comp) continue;
3185    for(j=0;j<c->n;j++)
3186    {
3187      if((c->S->m[j]==NULL)||(i==j))
3188        continue;
3189      assume(p_LmShortDivisibleBy(c->S->m[j],c->short_Exps[j],
3190             c->S->m[i],~c->short_Exps[i],
3191             c->r)==p_LmDivisibleBy(c->S->m[j],
3192             c->S->m[i],
3193             c->r));
3194      if (p_LmShortDivisibleBy(c->S->m[j],c->short_Exps[j],
3195          c->S->m[i],~c->short_Exps[i],
3196          c->r))
3197      {
3198        pDelete(&c->S->m[i]);
3199        break;
3200      }
3201    }
3202  }
3203  }
3204  omfree(c->short_Exps);
3205
3206
3207  ideal I=c->S;
3208
3209  IDELEMS(I)=c->n;
3210
3211  idSkipZeroes(I);
3212  for(i=0;i<=c->strat->sl;i++)
3213    c->strat->S[i]=NULL;
3214  id_Delete(&c->strat->Shdl,c->r);
3215  pDelete(&c->tmp_lm);
3216  omUnGetSpecBin(&lm_bin);
3217  delete c->strat;
3218}
3219ideal t_rep_gb(ring r,ideal arg_I, int syz_comp, BOOLEAN F4_mode){
3220
3221    assume(r==currRing);
3222    ring orig_ring=r;
3223    int pos;
3224    ring new_ring=rAssure_TDeg(orig_ring,1,rVar(orig_ring),pos);
3225
3226
3227    ideal s_h;
3228    if (orig_ring != new_ring)
3229    {
3230        rChangeCurrRing(new_ring);
3231        s_h=idrCopyR_NoSort(arg_I,orig_ring);
3232        idTest(s_h);
3233        /*int i;
3234
3235        for(i=0;i<IDELEMS(s_h);i++){
3236            poly p=s_h->m[i];
3237            while(p){
3238                p_Setm(p,new_ring);
3239                pIter(p);
3240            }
3241        }*/
3242    }
3243    else
3244    {
3245        s_h = id_Copy(arg_I,orig_ring);
3246    }
3247
3248    ideal s_result=do_t_rep_gb(new_ring,s_h,syz_comp,F4_mode,pos);
3249    ideal result;
3250    if(orig_ring != new_ring)
3251    {
3252
3253        idTest(s_result);
3254        rChangeCurrRing(orig_ring);
3255        result = idrMoveR_NoSort(s_result, new_ring);
3256
3257        idTest(result);
3258        //rChangeCurrRing(new_ring);
3259        rKill(new_ring);
3260        //rChangeCurrRing(orig_ring);
3261    }
3262    else
3263        result=s_result;
3264    idTest(result);
3265    return result;
3266}
3267
3268
3269
3270ideal do_t_rep_gb(ring r,ideal arg_I, int syz_comp, BOOLEAN F4_mode,int deg_pos){
3271
3272  //  Print("QlogSize(0) %d, QlogSize(1) %d,QlogSize(-2) %d, QlogSize(5) %d\n", QlogSize(nlInit(0)),QlogSize(nlInit(1)),QlogSize(nlInit(-2)),QlogSize(nlInit(5)));
3273
3274  if (TEST_OPT_PROT)
3275    if (F4_mode)
3276      PrintS("F4 Modus \n");
3277
3278  //debug_Ideal=arg_debug_Ideal;
3279  //if (debug_Ideal) PrintS("DebugIdeal received\n");
3280  // Print("Idelems %i \n----------\n",IDELEMS(arg_I));
3281  ideal I=arg_I;
3282  idCompactify(I);
3283  if (idIs0(I)) return I;
3284  int i;
3285  for(i=0;i<IDELEMS(I);i++)
3286  {
3287    assume(I->m[i]!=NULL);
3288    simplify_poly(I->m[i],currRing);
3289  }
3290
3291
3292  qsort(I->m,IDELEMS(I),sizeof(poly),poly_crit);
3293  //Print("Idelems %i \n----------\n",IDELEMS(I));
3294  //slimgb_alg* c=(slimgb_alg*) omalloc(sizeof(slimgb_alg));
3295  //int syz_comp=arg_I->rank;
3296  slimgb_alg* c=new slimgb_alg(I, syz_comp,F4_mode,deg_pos);
3297
3298
3299  while ((c->pair_top>=0) && ((!(TEST_OPT_DEGBOUND)) || (c->apairs[c->pair_top]->deg<=Kstd1_deg)))
3300  {
3301    #ifdef HAVE_F4
3302    if(F4_mode)
3303      go_on_F4(c);
3304
3305    else
3306    #endif
3307      go_on(c);
3308  }
3309  if (c->pair_top<0)
3310    c->completed=TRUE;
3311  I=c->S;
3312  delete c;
3313  if (TEST_OPT_REDSB)
3314  {
3315    ideal erg=kInterRed(I,NULL);
3316    assume(I!=erg);
3317    id_Delete(&I, currRing);
3318    return erg;
3319  }
3320  //qsort(I->m, IDELEMS(I),sizeof(poly),pLmCmp_func);
3321  assume(I->rank>=idRankFreeModule(I));
3322  return(I);
3323}
3324void now_t_rep(const int & arg_i, const int & arg_j, slimgb_alg* c){
3325  int i,j;
3326  if (arg_i==arg_j){
3327    return;
3328  }
3329  if (arg_i>arg_j){
3330    i=arg_j;
3331    j=arg_i;
3332  } else {
3333    i=arg_i;
3334    j=arg_j;
3335  }
3336  c->states[j][i]=HASTREP;
3337}
3338
3339static BOOLEAN has_t_rep(const int & arg_i, const  int & arg_j, slimgb_alg* state){
3340  assume(0<=arg_i);
3341  assume(0<=arg_j);
3342  assume(arg_i<state->n);
3343  assume(arg_j<state->n);
3344  if (arg_i==arg_j)
3345  {
3346    return (TRUE);
3347  }
3348  if (arg_i>arg_j)
3349  {
3350    return (state->states[arg_i][arg_j]==HASTREP);
3351  } else
3352  {
3353    return (state->states[arg_j][arg_i]==HASTREP);
3354  }
3355}
3356static int pLcmDeg(poly a, poly b)
3357{
3358  int i;
3359  int n=0;
3360  for (i=pVariables; i; i--)
3361  {
3362    n+=si_max( pGetExp(a,i), pGetExp(b,i));
3363  }
3364  return n;
3365
3366}
3367
3368
3369
3370static void shorten_tails(slimgb_alg* c, poly monom)
3371{
3372  return;
3373// BOOLEAN corr=lenS_correct(c->strat);
3374  for(int i=0;i<c->n;i++)
3375  {
3376    //enter tail
3377
3378    if (c->S->m[i]==NULL) continue;
3379    poly tail=c->S->m[i]->next;
3380    poly prev=c->S->m[i];
3381    BOOLEAN did_something=FALSE;
3382    while((tail!=NULL)&& (pLmCmp(tail, monom)>=0))
3383    {
3384      if (p_LmDivisibleBy(monom,tail,c->r))
3385      {
3386        did_something=TRUE;
3387        prev->next=tail->next;
3388        tail->next=NULL;
3389        p_Delete(& tail,c->r);
3390        tail=prev;
3391        //PrintS("Shortened");
3392        c->lengths[i]--;
3393      }
3394      prev=tail;
3395      tail=tail->next;
3396    }
3397    if (did_something)
3398    {
3399      int new_pos;
3400      wlen_type q;
3401      q=pQuality(c->S->m[i],c,c->lengths[i]);
3402      new_pos=simple_posInS(c->strat,c->S->m[i],c->lengths[i],q);
3403
3404      int old_pos=-1;
3405      //assume new_pos<old_pos
3406      for (int z=0;z<=c->strat->sl;z++)
3407      {
3408        if (c->strat->S[z]==c->S->m[i])
3409        {
3410          old_pos=z;
3411          break;
3412        }
3413      }
3414      if (old_pos== -1)
3415        for (int z=new_pos-1;z>=0;z--)
3416        {
3417          if (c->strat->S[z]==c->S->m[i])
3418          {
3419            old_pos=z;
3420            break;
3421          }
3422        }
3423      assume(old_pos>=0);
3424      assume(new_pos<=old_pos);
3425      assume(pLength(c->strat->S[old_pos])==c->lengths[i]);
3426      c->strat->lenS[old_pos]=c->lengths[i];
3427      if (c->strat->lenSw)
3428        c->strat->lenSw[old_pos]=q;
3429
3430      if (new_pos<old_pos)
3431        move_forward_in_S(old_pos,new_pos,c->strat);
3432
3433      length_one_crit(c,i,c->lengths[i]);
3434    }
3435  }
3436}
3437static sorted_pair_node* pop_pair(slimgb_alg* c){
3438  clean_top_of_pair_list(c);
3439
3440  if(c->pair_top<0) return NULL;
3441  else return (c->apairs[c->pair_top--]);
3442}
3443void slimgb_alg::cleanDegs(int lower, int upper){
3444  assume(is_homog);
3445  int deg;
3446  if (TEST_OPT_PROT){
3447    PrintS("C");
3448  }
3449  for(deg=lower;deg<=upper;deg++){
3450    int i;
3451    for(i=0;i<n;i++){
3452      if (T_deg[i]==deg){
3453          poly h;
3454          h=S->m[i];
3455          h=redNFTail(h,strat->sl,strat,lengths[i]);
3456          if (!rField_is_Zp(r))
3457          {
3458            pCleardenom(h);
3459            pContent(h);
3460
3461          } else pNorm(h);
3462          //TODO:GCD of TERMS
3463          poly got=::gcd_of_terms(h,r);
3464          p_Delete(&gcd_of_terms[i],r);
3465          gcd_of_terms[i]=got;
3466          int len=pLength(h);
3467          wlen_type wlen=pQuality(h,this,len);
3468          if (weighted_lengths)
3469            weighted_lengths[i]=wlen;
3470          lengths[i]=len;
3471          assume(h==S->m[i]);
3472          int j;
3473          for(j=0;j<=strat->sl;j++){
3474            if (h==strat->S[j]){
3475              int new_pos=simple_posInS(strat, h,len, wlen);
3476              if (strat->lenS){
3477                strat->lenS[j]=len;
3478              }
3479              if (strat->lenSw){
3480                strat->lenSw[j]=wlen;
3481              }
3482              if (new_pos<j){
3483                move_forward_in_S(j,new_pos,strat);
3484              }else{
3485                if (new_pos>j)
3486                 new_pos=new_pos-1;//is identical with one element
3487                if (new_pos>j)
3488                  move_backward_in_S(j,new_pos,strat);
3489              }
3490              break;
3491            }
3492          }
3493        }
3494
3495    }
3496
3497  }
3498  {
3499    int i,j;
3500    for(i=0;i<this->n;i++){
3501      for(j=0;j<i;j++){
3502        if (T_deg[i]+T_deg[j]<=upper){
3503          now_t_rep(i,j,this);
3504        }
3505      }
3506    }
3507  }
3508  //TODO resort and update strat->S,strat->lenSw
3509  //TODO mark pairs
3510}
3511sorted_pair_node* top_pair(slimgb_alg* c){
3512  while(c->pair_top>=0){
3513    super_clean_top_of_pair_list(c);//yeah, I know, it's odd that I use a different proc here
3514    if ((c->is_homog)&&(c->pair_top>=0)&&(c->apairs[c->pair_top]->deg>=c->lastCleanedDeg+2)){
3515      int upper=c->apairs[c->pair_top]->deg-1;
3516      c->cleanDegs(c->lastCleanedDeg+1,upper);
3517      c->lastCleanedDeg=upper;
3518    } else{
3519      break;
3520    }
3521
3522  }
3523
3524
3525  if(c->pair_top<0) return NULL;
3526  else return (c->apairs[c->pair_top]);
3527}
3528sorted_pair_node* quick_pop_pair(slimgb_alg* c){
3529  if(c->pair_top<0) return NULL;
3530  else return (c->apairs[c->pair_top--]);
3531}
3532
3533
3534
3535static void super_clean_top_of_pair_list(slimgb_alg* c){
3536  while((c->pair_top>=0)
3537  && (c->apairs[c->pair_top]->i>=0)
3538  && (good_has_t_rep(c->apairs[c->pair_top]->j, c->apairs[c->pair_top]->i,c)))
3539  {
3540
3541    free_sorted_pair_node(c->apairs[c->pair_top],c->r);
3542    c->pair_top--;
3543
3544  }
3545}
3546void clean_top_of_pair_list(slimgb_alg* c){
3547  while((c->pair_top>=0) && (c->apairs[c->pair_top]->i>=0) && (!state_is(UNCALCULATED,c->apairs[c->pair_top]->j, c->apairs[c->pair_top]->i,c))){
3548
3549    free_sorted_pair_node(c->apairs[c->pair_top],c->r);
3550    c->pair_top--;
3551
3552  }
3553}
3554static BOOLEAN state_is(calc_state state, const int & arg_i, const  int & arg_j, slimgb_alg* c){
3555  assume(0<=arg_i);
3556  assume(0<=arg_j);
3557  assume(arg_i<c->n);
3558  assume(arg_j<c->n);
3559  if (arg_i==arg_j)
3560  {
3561    return (TRUE);
3562  }
3563  if (arg_i>arg_j)
3564  {
3565    return (c->states[arg_i][arg_j]==state);
3566  }
3567  else return(c->states[arg_j][arg_i]==state);
3568}
3569
3570
3571void free_sorted_pair_node(sorted_pair_node* s, ring r){
3572  if (s->i>=0)
3573    p_Delete(&s->lcm_of_lm,r);
3574  omfree(s);
3575}
3576static BOOLEAN pair_better(sorted_pair_node* a,sorted_pair_node* b, slimgb_alg* c){
3577  if (a->deg<b->deg) return TRUE;
3578  if (a->deg>b->deg) return FALSE;
3579
3580
3581  int comp=pLmCmp(a->lcm_of_lm, b->lcm_of_lm);
3582  if (comp==1) return FALSE;
3583  if (-1==comp) return TRUE;
3584  if (a->expected_length<b->expected_length) return TRUE;
3585  if (a->expected_length>b->expected_length) return FALSE;
3586  if (a->i+a->j<b->i+b->j) return TRUE;
3587   if (a->i+a->j>b->i+b->j) return FALSE;
3588  if (a->i<b->i) return TRUE;
3589  if (a->i>b->i) return FALSE;
3590  return TRUE;
3591}
3592
3593static int tgb_pair_better_gen(const void* ap,const void* bp){
3594
3595  sorted_pair_node* a=*((sorted_pair_node**)ap);
3596  sorted_pair_node* b=*((sorted_pair_node**)bp);
3597  assume((a->i>a->j) || (a->i < 0));
3598  assume((b->i>b->j) || (b->i < 0));
3599  if (a->deg<b->deg) return -1;
3600  if (a->deg>b->deg) return 1;
3601
3602
3603
3604 int comp=pLmCmp(a->lcm_of_lm, b->lcm_of_lm);
3605
3606  if (comp==1) return 1;
3607  if (-1==comp) return -1;
3608   if (a->expected_length<b->expected_length) return -1;
3609  if (a->expected_length>b->expected_length) return 1;
3610  if (a->i+a->j<b->i+b->j) return -1;
3611   if (a->i+a->j>b->i+b->j) return 1;
3612  if (a->i<b->i) return -1;
3613   if (a->i>b->i) return 1;
3614  return 0;
3615}
3616
3617
3618static poly gcd_of_terms(poly p, ring r){
3619  int max_g_0=0;
3620  assume(p!=NULL);
3621  int i;
3622  poly m=pOne();
3623  poly t;
3624  for (i=pVariables; i; i--)
3625  {
3626      pSetExp(m,i, pGetExp(p,i));
3627      if (max_g_0==0)
3628  if (pGetExp(m,i)>0)
3629    max_g_0=i;
3630  }
3631
3632  t=p->next;
3633  while (t!=NULL){
3634
3635    if (max_g_0==0) break;
3636    for (i=max_g_0; i; i--)
3637    {
3638      pSetExp(m,i, si_min(pGetExp(t,i),pGetExp(m,i)));
3639      if (max_g_0==i)
3640  if (pGetExp(m,i)==0)
3641    max_g_0=0;
3642      if ((max_g_0==0) && (pGetExp(m,i)>0)){
3643  max_g_0=i;
3644      }
3645    }
3646    t=t->next;
3647  }
3648  p_Setm(m,r);
3649  if (max_g_0>0)
3650    return m;
3651  pDelete(&m);
3652  return NULL;
3653}
3654static inline BOOLEAN pHasNotCFExtended(poly p1, poly p2, poly m)
3655{
3656
3657  if (pGetComp(p1) > 0 || pGetComp(p2) > 0)
3658    return FALSE;
3659  int i = 1;
3660  loop
3661  {
3662    if ((pGetExp(p1, i)-pGetExp(m,i) >0) && (pGetExp(p2, i) -pGetExp(m,i)> 0))   return FALSE;
3663    if (i == pVariables)                                return TRUE;
3664    i++;
3665  }
3666}
3667
3668
3669//for impl reasons may return false if the the normal product criterion matches
3670static inline BOOLEAN extended_product_criterion(poly p1, poly gcd1, poly p2, poly gcd2, slimgb_alg* c){
3671  if (c->nc)
3672    return FALSE;
3673  if(gcd1==NULL) return FALSE;
3674        if(gcd2==NULL) return FALSE;
3675        gcd1->next=gcd2; //may ordered incorrect
3676        poly m=gcd_of_terms(gcd1,c->r);
3677        gcd1->next=NULL;
3678        if (m==NULL) return FALSE;
3679
3680        BOOLEAN erg=pHasNotCFExtended(p1,p2,m);
3681        pDelete(&m);
3682        return erg;
3683}
3684static poly kBucketGcd(kBucket* b, ring r)
3685{
3686  int s=0;
3687  int i;
3688  poly m, n;
3689  BOOLEAN initialized=FALSE;
3690  for (i=MAX_BUCKET-1;i>=0;i--)
3691  {
3692    if (b->buckets[i]!=NULL){
3693      if (!initialized){
3694  m=gcd_of_terms(b->buckets[i],r);
3695  initialized=TRUE;
3696  if (m==NULL) return NULL;
3697      }
3698      else
3699  {
3700    n=gcd_of_terms(b->buckets[i],r);
3701    if (n==NULL) {
3702      pDelete(&m);
3703      return NULL;
3704    }
3705    n->next=m;
3706    poly t=gcd_of_terms(n,r);
3707    n->next=NULL;
3708    pDelete(&m);
3709    pDelete(&n);
3710    m=t;
3711    if (m==NULL) return NULL;
3712
3713  }
3714    }
3715  }
3716  return m;
3717}
3718
3719
3720
3721
3722static inline wlen_type quality_of_pos_in_strat_S(int pos, slimgb_alg* c){
3723  if (c->strat->lenSw!=NULL) return c->strat->lenSw[pos];
3724  return c->strat->lenS[pos];
3725}
3726#ifdef HAVE_PLURAL
3727static inline wlen_type quality_of_pos_in_strat_S_mult_high(int pos, poly high, slimgb_alg* c)
3728  //meant only for nc
3729{
3730  poly m=pOne();
3731  pExpVectorDiff(m,high ,c->strat->S[pos]);
3732  poly product = nc_mm_Mult_pp(m, c->strat->S[pos], c->r);
3733  wlen_type erg=pQuality(product,c);
3734  pDelete(&m);
3735  pDelete(&product);
3736  return erg;
3737}
3738#endif
3739
3740static void multi_reduction_lls_trick(red_object* los, int losl,slimgb_alg* c,find_erg & erg){
3741  erg.expand=NULL;
3742  BOOLEAN swap_roles; //from reduce_by, to_reduce_u if fromS
3743  if(erg.fromS){
3744    if(pLmEqual(c->strat->S[erg.reduce_by],los[erg.to_reduce_u].p))
3745    {
3746      int i;
3747      wlen_type quality_a=quality_of_pos_in_strat_S(erg.reduce_by,c);
3748      int best=erg.to_reduce_u+1;
3749/*
3750      for (i=erg.to_reduce_u;i>=erg.to_reduce_l;i--){
3751  int qc=los[i].guess_quality(c);
3752  if (qc<quality_a){
3753    best=i;
3754    quality_a=qc;
3755  }
3756      }
3757      if(best!=erg.to_reduce_u+1){*/
3758      wlen_type qc;
3759      best=find_best(los,erg.to_reduce_l,erg.to_reduce_u,qc,c);
3760      if(qc<quality_a){
3761  los[best].flatten();
3762  int b_pos=kBucketCanonicalize(los[best].bucket);
3763  los[best].p=los[best].bucket->buckets[b_pos];
3764  qc=pQuality(los[best].bucket->buckets[b_pos],c);
3765  if(qc<quality_a){
3766    red_object h=los[erg.to_reduce_u];
3767    los[erg.to_reduce_u]=los[best];
3768    los[best]=h;
3769    swap_roles=TRUE;
3770  }
3771  else
3772    swap_roles=FALSE;
3773      }
3774      else{
3775
3776  swap_roles=FALSE;
3777      }
3778
3779    }
3780      else
3781    {
3782      if (erg.to_reduce_u>erg.to_reduce_l){
3783
3784  int i;
3785  wlen_type quality_a=quality_of_pos_in_strat_S(erg.reduce_by,c);
3786  #ifdef HAVE_PLURAL
3787  if ((c->nc) && (!(rIsSCA(c->r))))
3788    quality_a=quality_of_pos_in_strat_S_mult_high(erg.reduce_by, los[erg.to_reduce_u].p, c);
3789  #endif
3790  int best=erg.to_reduce_u+1;
3791  wlen_type qc;
3792  best=find_best(los,erg.to_reduce_l,erg.to_reduce_u,qc,c);
3793  assume(qc==los[best].guess_quality(c));
3794  if(qc<quality_a){
3795    los[best].flatten();
3796    int b_pos=kBucketCanonicalize(los[best].bucket);
3797    los[best].p=los[best].bucket->buckets[b_pos];
3798    qc==pQuality(los[best].bucket->buckets[b_pos],c);
3799    //(best!=erg.to_reduce_u+1)
3800    if(qc<quality_a){
3801    red_object h=los[erg.to_reduce_u];
3802    los[erg.to_reduce_u]=los[best];
3803    los[best]=h;
3804    erg.reduce_by=erg.to_reduce_u;
3805    erg.fromS=FALSE;
3806    erg.to_reduce_u--;
3807    }
3808  }
3809      }
3810      else
3811      {
3812  assume(erg.to_reduce_u==erg.to_reduce_l);
3813  wlen_type quality_a=
3814        quality_of_pos_in_strat_S(erg.reduce_by,c);
3815  wlen_type qc=los[erg.to_reduce_u].guess_quality(c);
3816  if (qc<0) PrintS("Wrong wlen_type");
3817  if(qc<quality_a){
3818    int best=erg.to_reduce_u;
3819    los[best].flatten();
3820    int b_pos=kBucketCanonicalize(los[best].bucket);
3821    los[best].p=los[best].bucket->buckets[b_pos];
3822    qc=pQuality(los[best].bucket->buckets[b_pos],c);
3823    assume(qc>=0);
3824    if(qc<quality_a){
3825      BOOLEAN exp=FALSE;
3826      if(qc<=2){
3827         //Print("\n qc is %lld \n",qc);
3828         exp=TRUE;
3829      }
3830
3831      else {
3832         if (qc<quality_a/2)
3833          exp=TRUE;
3834         else
3835       if(erg.reduce_by<c->n/4)
3836          exp=TRUE;
3837      }
3838      if (exp){
3839        poly clear_into;
3840        los[erg.to_reduce_u].flatten();
3841        kBucketClear(los[erg.to_reduce_u].bucket,&clear_into,&erg.expand_length);
3842        erg.expand=pCopy(clear_into);
3843        kBucketInit(los[erg.to_reduce_u].bucket,clear_into,erg.expand_length);
3844        if (TEST_OPT_PROT)
3845    PrintS("e");
3846
3847      }
3848    }
3849  }
3850
3851
3852      }
3853
3854      swap_roles=FALSE;
3855      return;
3856      }
3857
3858  }
3859  else{
3860    if(erg.reduce_by>erg.to_reduce_u){
3861      //then lm(rb)>= lm(tru) so =
3862      assume(erg.reduce_by==erg.to_reduce_u+1);
3863      int best=erg.reduce_by;
3864      wlen_type quality_a=los[erg.reduce_by].guess_quality(c);
3865      wlen_type qc;
3866      best=find_best(los,erg.to_reduce_l,erg.to_reduce_u,qc,c);
3867
3868      int i;
3869      if(qc<quality_a){
3870    red_object h=los[erg.reduce_by];
3871    los[erg.reduce_by]=los[best];
3872    los[best]=h;
3873  }
3874  swap_roles=FALSE;
3875  return;
3876
3877
3878    }
3879    else
3880    {
3881      assume(!pLmEqual(los[erg.reduce_by].p,los[erg.to_reduce_l].p));
3882      assume(erg.to_reduce_u==erg.to_reduce_l);
3883      //further assume, that reduce_by is the above all other polys
3884      //with same leading term
3885      int il=erg.reduce_by;
3886      wlen_type quality_a =los[erg.reduce_by].guess_quality(c);
3887      wlen_type qc;
3888      while((il>0) && pLmEqual(los[il-1].p,los[il].p)){
3889  il--;
3890  qc=los[il].guess_quality(c);
3891  if (qc<quality_a){
3892    quality_a=qc;
3893    erg.reduce_by=il;
3894  }
3895      }
3896      swap_roles=FALSE;
3897    }
3898
3899  }
3900  if(swap_roles)
3901  {
3902    if (TEST_OPT_PROT)
3903      PrintS("b");
3904    poly clear_into;
3905    int dummy_len;
3906    int new_length;
3907    int bp=erg.to_reduce_u;//bucket_positon
3908    //kBucketClear(los[bp].bucket,&clear_into,&new_length);
3909    new_length=los[bp].clear_to_poly();
3910    clear_into=los[bp].p;
3911    poly p=c->strat->S[erg.reduce_by];
3912    int j=erg.reduce_by;
3913    int old_length=c->strat->lenS[j];// in view of S
3914    los[bp].p=p;
3915    if (c->eliminationProblem){
3916        los[bp].sugar=c->pTotaldegree_full(p);
3917    }
3918    kBucketInit(los[bp].bucket,p,old_length);
3919    wlen_type qal=pQuality(clear_into,c,new_length);
3920    int pos_in_c=-1;
3921    int z;
3922    int new_pos;
3923    new_pos=simple_posInS(c->strat,clear_into,new_length, qal);
3924    assume(new_pos<=j);
3925    for (z=c->n;z;z--)
3926    {
3927      if(p==c->S->m[z-1])
3928      {
3929  pos_in_c=z-1;
3930  break;
3931      }
3932    }
3933
3934    int tdeg_full=-1;
3935    int tdeg=-1;
3936    if(pos_in_c>=0)
3937    {
3938      #ifdef TGB_RESORT_PAIRS
3939      c->used_b=TRUE;
3940      c->replaced[pos_in_c]=TRUE;
3941      #endif
3942      tdeg=c->T_deg[pos_in_c];
3943      c->S->m[pos_in_c]=clear_into;
3944      c->lengths[pos_in_c]=new_length;
3945      c->weighted_lengths[pos_in_c]=qal;
3946      if (c->gcd_of_terms[pos_in_c]==NULL)
3947        c->gcd_of_terms[pos_in_c]=gcd_of_terms(clear_into,c->r);
3948      if (c->T_deg_full)
3949        tdeg_full=c->T_deg_full[pos_in_c]=c->pTotaldegree_full(clear_into);
3950      else tdeg_full=tdeg;
3951      c_S_element_changed_hook(pos_in_c,c);
3952    } else {
3953      if (c->eliminationProblem){
3954        tdeg_full=c->pTotaldegree_full(clear_into);
3955        tdeg=c->pTotaldegree(clear_into);
3956      }
3957    }
3958    c->strat->S[j]=clear_into;
3959    c->strat->lenS[j]=new_length;
3960
3961    assume(pLength(clear_into)==new_length);
3962    if(c->strat->lenSw!=NULL)
3963      c->strat->lenSw[j]=qal;
3964    if (!rField_is_Zp(c->r))
3965    {
3966      pCleardenom(clear_into);//should be unnecessary
3967      pContent(clear_into);
3968
3969    }
3970    else
3971      pNorm(clear_into);
3972#ifdef FIND_DETERMINISTIC
3973    erg.reduce_by=j;
3974    //resort later see diploma thesis, find_in_S must be deterministic
3975    //during multireduction if spolys are only in the span of the
3976    //input polys
3977#else
3978
3979    if (new_pos<j)
3980    {
3981      if (c->strat->honey) c->strat->ecartS[j]=tdeg_full-tdeg;
3982      move_forward_in_S(j,new_pos,c->strat);
3983      erg.reduce_by=new_pos;
3984    }
3985#endif
3986  }
3987}
3988static int fwbw(red_object* los, int i){
3989   int i2=i;
3990   int step=1;
3991
3992   BOOLEAN bw=FALSE;
3993   BOOLEAN incr=TRUE;
3994
3995   while(1)
3996   {
3997     if(!bw)
3998     {
3999       step=si_min(i2,step);
4000       if (step==0) break;
4001       i2-=step;
4002
4003       if(!pLmEqual(los[i].p,los[i2].p))
4004       {
4005   bw=TRUE;
4006   incr=FALSE;
4007       }
4008       else
4009       {
4010   if ((!incr) &&(step==1)) break;
4011       }
4012
4013
4014     }
4015     else
4016     {
4017
4018       step=si_min(i-i2,step);
4019       if (step==0) break;
4020       i2+=step;
4021       if(pLmEqual(los[i].p,los[i2].p)){
4022   if(step==1) break;
4023   else
4024   {
4025     bw=FALSE;
4026   }
4027       }
4028
4029     }
4030     if (incr)
4031       step*=2;
4032     else
4033     {
4034       if (step%2==1)
4035   step=(step+1)/2;
4036       else
4037   step/=2;
4038
4039     }
4040   }
4041   return i2;
4042}
4043static void canonicalize_region(red_object* los, int l, int u,slimgb_alg* c){
4044    assume(l<=u+1);
4045    int i;
4046    for(i=l;i<=u;i++){
4047        kBucketCanonicalize(los[i].bucket);
4048    }
4049
4050}
4051static void multi_reduction_find(red_object* los, int losl,slimgb_alg* c,int startf,find_erg & erg){
4052  kStrategy strat=c->strat;
4053
4054  assume(startf<=losl);
4055  assume((startf==losl-1)||(pLmCmp(los[startf].p,los[startf+1].p)==-1));
4056  int i=startf;
4057
4058  int j;
4059  while(i>=0){
4060    assume((i==losl-1)||(pLmCmp(los[i].p,los[i+1].p)<=0));
4061    assume(is_valid_ro(los[i]));
4062    assume((!(c->eliminationProblem))||(los[i].sugar>=c->pTotaldegree(los[i].p)));
4063    j=kFindDivisibleByInS_easy(strat,los[i]);
4064    if(j>=0){
4065
4066      erg.to_reduce_u=i;
4067      erg.reduce_by=j;
4068      erg.fromS=TRUE;
4069      int i2=fwbw(los,i);
4070      assume(pLmEqual(los[i].p,los[i2].p));
4071      assume((i2==0)||(!pLmEqual(los[i2].p,los[i2-1].p)));
4072      assume(i>=i2);
4073
4074
4075      erg.to_reduce_l=i2;
4076      assume((i==losl-1)||(pLmCmp(los[i].p,los[i+1].p)==-1));
4077      canonicalize_region(los,erg.to_reduce_u+1,startf,c);
4078      return;
4079    }
4080    if (j<0){
4081
4082      //not reduceable, try to use this for reducing higher terms
4083      int i2=fwbw(los,i);
4084      assume(pLmEqual(los[i].p,los[i2].p));
4085      assume((i2==0)||(!pLmEqual(los[i2].p,los[i2-1].p)));
4086      assume(i>=i2);
4087      if(i2!=i){
4088
4089
4090  erg.to_reduce_u=i-1;
4091  erg.to_reduce_l=i2;
4092  erg.reduce_by=i;
4093  erg.fromS=FALSE;
4094  assume((i==losl-1)||(pLmCmp(los[i].p,los[i+1].p)==-1));
4095  canonicalize_region(los,erg.to_reduce_u+1,startf,c);
4096  return;
4097      }
4098
4099      i--;
4100    }
4101  }
4102  erg.reduce_by=-1;//error code
4103  return;
4104}
4105
4106 //  nicht reduzierbare eintraege in ergebnisliste schreiben
4107//   nullen loeschen
4108//   while(finde_groessten leitterm reduzierbar(c,erg)){
4109
4110static int multi_reduction_clear_zeroes(red_object* los, int  losl, int l, int u)
4111{
4112
4113
4114  int deleted=0;
4115  int  i=l;
4116  int last=-1;
4117  while(i<=u)
4118  {
4119
4120    if(los[i].p==NULL){
4121      kBucketDestroy(&los[i].bucket);
4122//      delete los[i];//here we assume los are constructed with new
4123      //destroy resources, must be added here
4124     if (last>=0)
4125     {
4126       memmove(los+(int)(last+1-deleted),los+(last+1),sizeof(red_object)*(i-1-last));
4127     }
4128     last=i;
4129     deleted++;
4130    }
4131    i++;
4132  }
4133  if((last>=0)&&(last!=losl-1))
4134      memmove(los+(int)(last+1-deleted),los+last+1,sizeof(red_object)*(losl-1-last));
4135  return deleted;
4136
4137}
4138int search_red_object_pos(red_object* a, int top, red_object* key ){
4139
4140    int an = 0;
4141    int en= top;
4142    if (top==-1) return 0;
4143    if (pLmCmp(key->p,a[top].p)==1)
4144      return top+1;
4145    int i;
4146    loop
4147    {
4148      if (an >= en-1)
4149      {
4150        if (pLmCmp(key->p,a[an].p)==-1)
4151           return an;
4152        return en;
4153      }
4154      i=(an+en) / 2;
4155      if (pLmCmp(key->p,a[i].p)==-1)
4156        en=i;
4157      else
4158        an=i;
4159    }
4160
4161}
4162static void sort_region_down(red_object* los, int l, int u, slimgb_alg* c)
4163{
4164  int r_size=u-l+1;
4165  qsort(los+l,r_size,sizeof(red_object),red_object_better_gen);
4166  int i;
4167  int * new_indices=(int*) omalloc((r_size)*sizeof(int));
4168  int bound=0;
4169  BOOLEAN at_end=FALSE;
4170  for(i=l;i<=u;i++){
4171    if (!(at_end)){
4172      bound=new_indices[i-l]=bound+search_red_object_pos(los+bound,l-bound-1,los+i);
4173      if (bound==l) at_end=TRUE;
4174    }
4175    else{
4176      new_indices[i-l]=l;
4177    }
4178  }
4179  red_object* los_region=(red_object*) omalloc(sizeof(red_object)*(u-l+1));
4180  for (int i=0;i<r_size;i++){
4181    new_indices[i]+=i;
4182    los_region[i]=los[l+i];
4183    assume((i==0)||(new_indices[i]>new_indices[i-1]));
4184
4185  }
4186
4187  i=r_size-1;
4188  int j=u;
4189  int j2=l-1;
4190  while(i>=0){
4191    if (new_indices[i]==j){
4192      los[j]=los_region[i];
4193      i--;
4194      j--;
4195    } else{
4196      assume(new_indices[i]<j);
4197      los[j]=los[j2];
4198      assume(j2>=0);
4199      j2--;
4200      j--;
4201    }
4202  }
4203  omfree(los_region);
4204
4205  omfree(new_indices);
4206
4207}
4208
4209//assume that los is ordered ascending by leading term, all non zero
4210static void multi_reduction(red_object* los, int & losl, slimgb_alg* c)
4211{
4212  poly* delay=(poly*) omalloc(losl*sizeof(poly));
4213  int delay_s=0;
4214  //initialize;
4215  assume(c->strat->sl>=0);
4216  assume(losl>0);
4217  int i;
4218  wlen_type max_initial_quality=0;
4219
4220  for(i=0;i<losl;i++){
4221    los[i].sev=pGetShortExpVector(los[i].p);
4222//SetShortExpVector();
4223    los[i].p=kBucketGetLm(los[i].bucket);
4224    if (los[i].initial_quality>max_initial_quality)
4225        max_initial_quality=los[i].initial_quality;
4226    // else
4227//         Print("init2_qal=%lld;", los[i].initial_quality);
4228//     Print("initial_quality=%lld;",max_initial_quality);
4229  }
4230
4231  kStrategy strat=c->strat;
4232  int curr_pos=losl-1;
4233
4234
4235//  nicht reduzierbare eintrï¿œe in ergebnisliste schreiben
4236  // nullen loeschen
4237  while(curr_pos>=0){
4238    if ((c->use_noro_last_block)&&(lies_in_last_dp_block(los[curr_pos].p,c))){
4239        int pn_noro=curr_pos+1;
4240        poly* p_noro=(poly*) omalloc(pn_noro*sizeof(poly));
4241        for(i=0;i<pn_noro;i++){
4242            int dummy_len;
4243            poly p;
4244            los[i].p=NULL;
4245            kBucketClear(los[i].bucket,&p,&dummy_len);
4246            p_noro[i]=p;
4247        }
4248
4249
4250        if (npPrimeM<255){
4251          noro_step<tgb_uint8>(p_noro,pn_noro,c);
4252        } else {
4253          if (npPrimeM<65000){
4254            noro_step<tgb_uint16>(p_noro,pn_noro,c);
4255          } else{
4256            noro_step<tgb_uint32>(p_noro,pn_noro,c);
4257          }
4258        }
4259        for(i=0;i<pn_noro;i++){
4260            los[i].p=p_noro[i];
4261            los[i].sev=pGetShortExpVector(los[i].p);
4262            //ignore quality
4263            kBucketInit(los[i].bucket,los[i].p,pLength(los[i].p));
4264
4265        }
4266        qsort(los,pn_noro,sizeof(red_object),red_object_better_gen);
4267        int deleted=multi_reduction_clear_zeroes(los, losl, pn_noro, curr_pos);
4268        losl -= deleted;
4269        curr_pos -= deleted;
4270        break;
4271    }
4272    find_erg erg;
4273
4274    multi_reduction_find(los, losl,c,curr_pos,erg);//last argument should be curr_pos
4275    if(erg.reduce_by<0) break;
4276
4277
4278
4279    erg.expand=NULL;
4280    int d=erg.to_reduce_u-erg.to_reduce_l+1;
4281
4282
4283    multi_reduction_lls_trick(los,losl,c,erg);
4284
4285
4286    int i;
4287    int len;
4288    //    wrp(los[erg.to_reduce_u].p);
4289    //PrintLn();
4290    multi_reduce_step(erg,los,c);
4291
4292
4293    if(!K_TEST_OPT_REDTHROUGH){
4294  for(i=erg.to_reduce_l;i<=erg.to_reduce_u;i++){
4295     if  (los[i].p!=NULL)  //the check (los[i].p!=NULL) might be invalid
4296     {
4297         //
4298         assume(los[i].initial_quality>0);
4299
4300               if(los[i].guess_quality(c)
4301                  >1.5*delay_factor*max_initial_quality){
4302                       if (TEST_OPT_PROT)
4303                           PrintS("v");
4304                       los[i].canonicalize();
4305                       if(los[i].guess_quality(c)
4306                           >delay_factor*max_initial_quality){
4307                               if (TEST_OPT_PROT)
4308                                   PrintS(".");
4309                               los[i].clear_to_poly();
4310                               //delay.push_back(los[i].p);
4311                               delay[delay_s]=los[i].p;
4312                               delay_s++;
4313
4314                               los[i].p=NULL;
4315
4316                      }
4317                  }
4318
4319            }
4320     }
4321  }
4322    int deleted=multi_reduction_clear_zeroes(los, losl, erg.to_reduce_l, erg.to_reduce_u);
4323    if(erg.fromS==FALSE)
4324      curr_pos=si_max(erg.to_reduce_u,erg.reduce_by);
4325    else
4326      curr_pos=erg.to_reduce_u;
4327    losl -= deleted;
4328    curr_pos -= deleted;
4329
4330    //Print("deleted %i \n",deleted);
4331    if ((TEST_V_UPTORADICAL) &&(!(erg.fromS)))
4332        sort_region_down(los,si_min(erg.to_reduce_l,erg.reduce_by),(si_max(erg.to_reduce_u,erg.reduce_by))-deleted,c);
4333    else
4334    sort_region_down(los, erg.to_reduce_l, erg.to_reduce_u-deleted, c);
4335
4336
4337    if(erg.expand)
4338    {
4339#ifdef FIND_DETERMINISTIC
4340      int i;
4341      for(i=0;c->expandS[i];i++);
4342      c->expandS=(poly*) omrealloc(c->expandS,(i+2)*sizeof(poly));
4343      c->expandS[i]=erg.expand;
4344      c->expandS[i+1]=NULL;
4345#else
4346      int ecart=0;
4347      if (c->eliminationProblem){
4348        ecart=c->pTotaldegree_full(erg.expand)-c->pTotaldegree(erg.expand);
4349      }
4350      add_to_reductors(c,erg.expand,erg.expand_length,ecart);
4351#endif
4352    }
4353
4354  }
4355
4356
4357  //sorted_pair_node** pairs=(sorted_pair_node**)
4358  //  omalloc(delay_s*sizeof(sorted_pair_node*));
4359  c->introduceDelayedPairs(delay,delay_s);
4360  /*
4361  for(i=0;i<delay_s;i++){
4362
4363      poly p=delay[i];
4364      //if (rPar(c->r)==0)
4365      simplify_poly(p,c->r);
4366      sorted_pair_node* si=(sorted_pair_node*) omalloc(sizeof(sorted_pair_node));
4367      si->i=-1;
4368      si->j=-1;
4369       if (!rField_is_Zp(c->r)){
4370        if (!c->nc)
4371            p=redTailShort(p, c->strat);
4372        pCleardenom(p);
4373        pContent(p);
4374      }
4375      si->expected_length=pQuality(p,c,pLength(p));
4376      si->deg=pTotaldegree(p);
4377
4378      si->lcm_of_lm=p;
4379      pairs[i]=si;
4380  }
4381  qsort(pairs,delay_s,sizeof(sorted_pair_node*),tgb_pair_better_gen2);
4382  c->apairs=spn_merge(c->apairs,c->pair_top+1,pairs,delay_s,c);
4383  c->pair_top+=delay_s;*/
4384  omfree(delay);
4385  //omfree(pairs);
4386  return;
4387}
4388void red_object::flatten(){
4389  assume(p==kBucketGetLm(bucket));
4390}
4391void red_object::validate(){
4392  p=kBucketGetLm(bucket);
4393  if(p)
4394    sev=pGetShortExpVector(p);
4395}
4396int red_object::clear_to_poly(){
4397  flatten();
4398  int l;
4399  kBucketClear(bucket,&p,&l);
4400  return l;
4401}
4402
4403
4404
4405
4406
4407void reduction_step::reduce(red_object* r, int l, int u){}
4408void simple_reducer::do_reduce(red_object & ro)
4409{
4410  number coef;
4411#ifdef HAVE_PLURAL
4412  if (c->nc)
4413    nc_BucketPolyRed_Z(ro.bucket, p, &coef);
4414  else
4415#endif
4416    coef=kBucketPolyRed(ro.bucket,p,
4417       p_len,
4418       c->strat->kNoether);
4419  nDelete(&coef);
4420}
4421
4422
4423void simple_reducer::reduce(red_object* r, int l, int u){
4424  this->pre_reduce(r,l,u);
4425  int i;
4426//debug start
4427  int im;
4428
4429
4430  if(c->eliminationProblem){
4431    assume(p_LmEqual(r[l].p,r[u].p,c->r));
4432    /*int lm_deg=pTotaldegree(r[l].p);
4433    reducer_deg=lm_deg+pTotaldegree_full(p)-pTotaldegree(p);*/
4434  }
4435
4436  for(i=l;i<=u;i++){
4437
4438
4439
4440    this->do_reduce(r[i]);
4441    if (c->eliminationProblem){
4442        r[i].sugar=si_max(r[i].sugar,reducer_deg);
4443    }
4444  }
4445  for(i=l;i<=u;i++){
4446
4447    kBucketSimpleContent(r[i].bucket);
4448    r[i].validate();
4449    #ifdef TGB_DEBUG
4450    #endif
4451  }
4452}
4453reduction_step::~reduction_step(){}
4454simple_reducer::~simple_reducer(){
4455  if(fill_back!=NULL)
4456  {
4457    kBucketInit(fill_back,p,p_len);
4458  }
4459  fill_back=NULL;
4460
4461}
4462
4463void multi_reduce_step(find_erg & erg, red_object* r, slimgb_alg* c){
4464  static int id=0;
4465  id++;
4466  unsigned long sev;
4467    BOOLEAN lt_changed=FALSE;
4468  int rn=erg.reduce_by;
4469  poly red;
4470  int red_len;
4471  simple_reducer* pointer;
4472  BOOLEAN work_on_copy=FALSE;
4473  if(erg.fromS){
4474    red=c->strat->S[rn];
4475    red_len=c->strat->lenS[rn];
4476    assume(red_len==pLength(red));
4477  }
4478  else
4479  {
4480    r[rn].flatten();
4481    kBucketClear(r[rn].bucket,&red,&red_len);
4482
4483    if (!rField_is_Zp(c->r))
4484    {
4485      pCleardenom(red);//should be unnecessary
4486      pContent(red);
4487
4488
4489    }
4490    pNormalize(red);
4491    if (c->eliminationProblem){
4492        r[rn].sugar=c->pTotaldegree_full(red);
4493    }
4494
4495    if ((!(erg.fromS))&&(TEST_V_UPTORADICAL)){
4496
4497         if (polynomial_root(red,c->r))
4498            lt_changed=TRUE;
4499            sev=p_GetShortExpVector(red,c->r);}
4500    red_len=pLength(red);
4501  }
4502  if (((TEST_V_MODPSOLVSB)&&(red_len>1))||((c->nc)||(erg.to_reduce_u-erg.to_reduce_l>5))){
4503    work_on_copy=TRUE;
4504    // poly m=pOne();
4505    poly m=c->tmp_lm;
4506    pSetCoeff(m,nInit(1));
4507    pSetComp(m,0);
4508    for(int i=1;i<=pVariables;i++)
4509      pSetExp(m,i,(pGetExp(r[erg.to_reduce_l].p, i)-pGetExp(red,i)));
4510    pSetm(m);
4511    poly red_cp;
4512    #ifdef HAVE_PLURAL
4513    if (c->nc)
4514      red_cp = nc_mm_Mult_pp(m, red, c->r);
4515    else
4516    #endif
4517      red_cp=ppMult_mm(red,m);
4518    if(!erg.fromS){
4519      kBucketInit(r[rn].bucket,red,red_len);
4520    }
4521    //now reduce the copy
4522    //static poly redNF2 (poly h,slimgb_alg* c , int &len, number&  m,int n)
4523
4524    if (!c->nc)
4525      redTailShort(red_cp,c->strat);
4526    //number mul;
4527    // red_len--;
4528//     red_cp->next=redNF2(red_cp->next,c,red_len,mul,c->average_length);
4529//     pSetCoeff(red_cp,nMult(red_cp->coef,mul));
4530//     nDelete(&mul);
4531//     red_len++;
4532    red=red_cp;
4533    red_len=pLength(red);
4534    // pDelete(&m);
4535
4536  }
4537  int i;
4538
4539
4540
4541  assume(red_len==pLength(red));
4542
4543  int reducer_deg=0;
4544  if (c->eliminationProblem){
4545     int lm_deg=c->pTotaldegree(r[erg.to_reduce_l].p);
4546     int ecart;
4547     if (erg.fromS){
4548       ecart=c->strat->ecartS[erg.reduce_by];
4549     } else {
4550       ecart=c->pTotaldegree_full(red)-lm_deg;
4551     }
4552     reducer_deg=lm_deg+ecart;
4553  }
4554  pointer=new simple_reducer(red,red_len,reducer_deg,c);
4555
4556  if ((!work_on_copy) && (!erg.fromS))
4557    pointer->fill_back=r[rn].bucket;
4558  else
4559    pointer->fill_back=NULL;
4560  pointer->reduction_id=id;
4561  pointer->c=c;
4562
4563  pointer->reduce(r,erg.to_reduce_l, erg.to_reduce_u);
4564  if(work_on_copy) pDelete(&pointer->p);
4565  delete pointer;
4566  if (lt_changed){
4567    assume(!erg.fromS);
4568    r[erg.reduce_by].sev=sev;
4569  }
4570
4571};
4572
4573
4574
4575
4576void simple_reducer:: pre_reduce(red_object* r, int l, int u){}
4577
Note: See TracBrowser for help on using the repository browser.