source: git/Singular/ipshell.cc @ 122981

spielwiese
Last change on this file since 122981 was 122981, checked in by Oliver Wienand <wienand@…>, 16 years ago
ipshell.cc: usigned long long ringflaga fuer modul git-svn-id: file:///usr/local/Singular/svn/trunk@10536 2c84dea3-7e68-4137-9b89-c4e89433aadc
  • Property mode set to 100644
File size: 116.2 KB
Line 
1/****************************************
2*  Computer Algebra System SINGULAR     *
3****************************************/
4/* $Id: ipshell.cc,v 1.175 2008-01-30 16:10:37 wienand Exp $ */
5/*
6* ABSTRACT:
7*/
8
9//#include <stdlib.h>
10#include <stdio.h>
11#include <string.h>
12#include <ctype.h>
13#include <math.h>
14
15#include "mod2.h"
16#include "tok.h"
17#include "ipid.h"
18#include "intvec.h"
19#include "omalloc.h"
20#include "febase.h"
21#include "polys.h"
22#include "prCopy.h"
23#include "ideals.h"
24#include "matpol.h"
25#include "kstd1.h"
26#include "ring.h"
27#include "subexpr.h"
28#include "maps.h"
29#include "syz.h"
30#include "numbers.h"
31#include "modulop.h"
32#include "longalg.h"
33#include "lists.h"
34#include "attrib.h"
35#include "ipconv.h"
36#include "silink.h"
37#include "stairc.h"
38#include "weight.h"
39#include "semic.h"
40#include "splist.h"
41#include "spectrum.h"
42#include "gnumpfl.h"
43#include "mpr_base.h"
44#include "ffields.h"
45#include "clapsing.h"
46#include "hutil.h"
47#include "ipshell.h"
48#ifdef HAVE_FACTORY
49#define SI_DONT_HAVE_GLOBAL_VARS
50#include <factory.h>
51#endif
52
53// define this if you want to use the fast_map routine for mapping ideals
54#define FAST_MAP
55
56#ifdef FAST_MAP
57#include "fast_maps.h"
58#endif
59
60leftv iiCurrArgs=NULL;
61int  traceit = 0;
62char *lastreserved=NULL;
63
64int  myynest = -1;
65
66static BOOLEAN iiNoKeepRing=TRUE;
67
68/*0 implementation*/
69
70char * iiTwoOps(int t)
71{
72  if (t<127)
73  {
74    static char ch[2];
75    switch (t)
76    {
77      case '&':
78        return "and";
79      case '|':
80        return "or";
81      default:
82        ch[0]=t;
83        ch[1]='\0';
84        return ch;
85    }
86  }
87  switch (t)
88  {
89    case COLONCOLON:  return "::";
90    case DOTDOT:      return "..";
91    //case PLUSEQUAL:   return "+=";
92    //case MINUSEQUAL:  return "-=";
93    case MINUSMINUS:  return "--";
94    case PLUSPLUS:    return "++";
95    case EQUAL_EQUAL: return "==";
96    case LE:          return "<=";
97    case GE:          return ">=";
98    case NOTEQUAL:    return "<>";
99    default:          return Tok2Cmdname(t);
100  }
101}
102
103static void list1(const char* s, idhdl h,BOOLEAN c, BOOLEAN fullname)
104{
105  char buffer[22];
106  int l;
107  char buf2[128];
108
109  if(fullname) sprintf(buf2, "%s::%s", "", IDID(h));
110  else sprintf(buf2, "%s", IDID(h));
111
112  Print("%s%-20.20s [%d]  ",s,buf2,IDLEV(h));
113  if (h == currRingHdl) PrintS("*");
114  PrintS(Tok2Cmdname((int)IDTYP(h)));
115
116  ipListFlag(h);
117  switch(IDTYP(h))
118  {
119    case INT_CMD:   Print(" %d",IDINT(h)); break;
120    case INTVEC_CMD:Print(" (%d)",IDINTVEC(h)->length()); break;
121    case INTMAT_CMD:Print(" %d x %d",IDINTVEC(h)->rows(),IDINTVEC(h)->cols());
122                    break;
123    case POLY_CMD:
124    case VECTOR_CMD:if (c)
125                    {
126                      PrintS(" ");wrp(IDPOLY(h));
127                      if(IDPOLY(h) != NULL)
128                      {
129                        Print(", %d monomial(s)",pLength(IDPOLY(h)));
130                      }
131                    }
132                    break;
133    case MODUL_CMD: Print(", rk %d", IDIDEAL(h)->rank);
134    case IDEAL_CMD: Print(", %u generator(s)",
135                    IDELEMS(IDIDEAL(h)),IDIDEAL(h)->rank); break;
136    case MAP_CMD:
137                    Print(" from %s",IDMAP(h)->preimage); break;
138    case MATRIX_CMD:Print(" %u x %u"
139                      ,MATROWS(IDMATRIX(h))
140                      ,MATCOLS(IDMATRIX(h))
141                    );
142                    break;
143    case PACKAGE_CMD:
144                    PrintS(" (");
145                    switch (IDPACKAGE(h)->language)
146                    {
147                        case LANG_SINGULAR: PrintS("S"); break;
148                        case LANG_C:        PrintS("C"); break;
149                        case LANG_TOP:      PrintS("T"); break;
150                        case LANG_NONE:     PrintS("N"); break;
151                        default:            PrintS("U");
152                    }
153                    if(IDPACKAGE(h)->libname!=NULL)
154                      Print(",%s", IDPACKAGE(h)->libname);
155                    PrintS(")");
156                    break;
157    case PROC_CMD: if(strlen(IDPROC(h)->libname)>0)
158                     Print(" from %s",IDPROC(h)->libname);
159                   if(IDPROC(h)->is_static)
160                     PrintS(" (static)");
161                   break;
162    case STRING_CMD:
163                   {
164                     char *s;
165                     l=strlen(IDSTRING(h));
166                     memset(buffer,0,22);
167                     strncpy(buffer,IDSTRING(h),si_min(l,20));
168                     if ((s=strchr(buffer,'\n'))!=NULL)
169                     {
170                       *s='\0';
171                     }
172                     PrintS(" ");
173                     PrintS(buffer);
174                     if((s!=NULL) ||(l>20))
175                     {
176                       Print("..., %d char(s)",l);
177                     }
178                     break;
179                   }
180    case LIST_CMD: Print(", size: %d",IDLIST(h)->nr+1);
181                   break;
182    case QRING_CMD:
183    case RING_CMD:
184                   if ((IDRING(h)==currRing) && (currRingHdl!=h))
185                     PrintS("(*)"); /* this is an alias to currRing */
186#ifdef RDEBUG
187                   if (traceit &TRACE_SHOW_RINGS)
188                     Print(" <%x>",IDRING(h));
189#endif
190                   break;
191    /*default:     break;*/
192  }
193  PrintLn();
194}
195
196void type_cmd(idhdl h)
197{
198  BOOLEAN oldShortOut = FALSE;
199
200  if (currRing != NULL)
201  {
202    oldShortOut = currRing->ShortOut;
203    currRing->ShortOut = 1;
204  }
205  list1("// ",h,FALSE,FALSE);
206  if (IDTYP(h)!=INT_CMD)
207  {
208    sleftv expr;
209    memset(&expr,0,sizeof(expr));
210    expr.rtyp=IDHDL;
211    expr.name=IDID(h);
212    expr.data=(void *)h;
213    expr.Print();
214  }
215  if (currRing != NULL)
216    currRing->ShortOut = oldShortOut;
217}
218
219static void killlocals0(int v, idhdl * localhdl, const ring r)
220{
221  idhdl h = *localhdl;
222  while (h!=NULL)
223  {
224    int vv;
225    //Print("consider %s, lev: %d:",IDID(h),IDLEV(h));
226    if ((vv=IDLEV(h))>0)
227    {
228      if (vv < v)
229      {
230        if (iiNoKeepRing)
231        {
232          //PrintS(" break\n");
233          return;
234        }
235        h = IDNEXT(h);
236        //PrintLn();
237      }
238      else if (vv >= v)
239      {
240        idhdl nexth = IDNEXT(h);
241        killhdl2(h,localhdl,r);
242        h = nexth;
243        //PrintS("kill\n");
244      }
245    }
246    else
247    {
248      h = IDNEXT(h);
249      //PrintLn();
250    }
251  }
252}
253#ifndef HAVE_NS
254void killlocals(int v)
255{
256  killlocals0(v,&IDROOT,currRing);
257
258  if ((iiRETURNEXPR_len > myynest)
259  && ((iiRETURNEXPR[myynest].Typ()==RING_CMD)
260    || (iiRETURNEXPR[myynest].Typ()==QRING_CMD)))
261  {
262    leftv h=&iiRETURNEXPR[myynest];
263    killlocals0(v,&(((ring)h->data)->idroot),(ring)h->data);
264  }
265
266  idhdl sh=currRingHdl;
267  ring sr=currRing;
268  BOOLEAN changed=FALSE;
269  idhdl h = IDROOT;
270
271//  Print("killlocals in %s\n",IDID(currPackHdl));
272  while (h!=NULL)
273  {
274    if (((IDTYP(h)==QRING_CMD) || (IDTYP(h) == RING_CMD))
275    && (IDRING(h)->idroot!=NULL))
276    {
277      if (IDRING(h)!=currRing) {changed=TRUE;rSetHdl(h);}
278      killlocals0(v,&(IDRING(h)->idroot),IDRING(h));
279    }
280    else if (IDTYP(h) == PACKAGE_CMD)
281    {
282      killlocals0(v,&(IDPACKAGE(h)->idroot),IDRING(h));
283    }
284    h = IDNEXT(h);
285  }
286  if (changed)
287  {
288    currRing=NULL;
289    currRingHdl=NULL;
290    if (sh!=NULL) rSetHdl(sh);
291    else if (sr!=NULL)
292    {
293      sh=rFindHdl(sr,NULL,NULL);
294      rSetHdl(sh);
295    }
296  }
297
298  if (myynest<=1) iiNoKeepRing=TRUE;
299  //Print("end killlocals  >= %d\n",v);
300  //listall();
301}
302#endif
303#ifdef HAVE_NS
304void killlocals_rec(idhdl *root,int v, ring r)
305{
306  idhdl h=*root;
307  while (h!=NULL)
308  {
309    if (IDLEV(h)>=v)
310    {
311//      Print("kill %s, lev %d for lev %d\n",IDID(h),IDLEV(h),v);
312      idhdl n=IDNEXT(h);
313      killhdl2(h,root,r);
314      h=n;
315    }
316    else if (IDTYP(h)==PACKAGE_CMD)
317    {
318 //     Print("into pack %s, lev %d for lev %d\n",IDID(h),IDLEV(h),v);
319      if (IDPACKAGE(h)!=basePack)
320        killlocals_rec(&(IDRING(h)->idroot),v,r);
321      h=IDNEXT(h);
322    }
323    else if ((IDTYP(h)==RING_CMD)
324    ||(IDTYP(h)==QRING_CMD))
325    {
326      if (IDRING(h)->idroot!=NULL)
327      {
328  //    Print("into ring %s, lev %d for lev %d\n",IDID(h),IDLEV(h),v);
329        killlocals_rec(&(IDRING(h)->idroot),v,IDRING(h));
330      }
331      h=IDNEXT(h);
332    }
333    else
334    {
335//      Print("skip %s lev %d for lev %d\n",IDID(h),IDLEV(h),v);
336      h=IDNEXT(h);
337    }
338  }
339}
340BOOLEAN killlocals_list(int v, lists L)
341{
342  if (L==NULL) return FALSE;
343  BOOLEAN changed=FALSE;
344  int n=L->nr;
345  for(;n>=0;n--)
346  {
347    leftv h=&(L->m[n]);
348    void *d=h->data;
349    if (((h->rtyp==RING_CMD) || (h->rtyp==QRING_CMD))
350    && (((ring)d)->idroot!=NULL))
351    {
352      if (d!=currRing) {changed=TRUE;rChangeCurrRing((ring)d);}
353      killlocals0(v,&(((ring)h->data)->idroot),(ring)h->data);
354    }
355    else if (h->rtyp==LIST_CMD)
356      changed|=killlocals_list(v,(lists)d);
357  }
358  return changed;
359}
360void killlocals(int v)
361{
362  BOOLEAN changed=FALSE;
363  idhdl sh=currRingHdl;
364  ring cr=currRing;
365  if (sh!=NULL) changed=((IDLEV(sh)<v) || (IDRING(sh)->ref>0));
366  //if (changed) Print("currRing=%s(%x), lev=%d,ref=%d\n",IDID(sh),IDRING(sh),IDLEV(sh),IDRING(sh)->ref);
367
368  killlocals_rec(&(basePack->idroot),v,currRing);
369
370  if (iiRETURNEXPR_len > myynest)
371  {
372    int t=iiRETURNEXPR[myynest].Typ();
373    if ((/*iiRETURNEXPR[myynest].Typ()*/ t==RING_CMD)
374    || (/*iiRETURNEXPR[myynest].Typ()*/ t==QRING_CMD))
375    {
376      leftv h=&iiRETURNEXPR[myynest];
377      if (((ring)h->data)->idroot!=NULL)
378        killlocals0(v,&(((ring)h->data)->idroot),(ring)h->data);
379    }
380    else if (/*iiRETURNEXPR[myynest].Typ()*/ t==LIST_CMD)
381    {
382      leftv h=&iiRETURNEXPR[myynest];
383      changed |=killlocals_list(v,(lists)h->data);
384    }
385  }
386  if (changed)
387  {
388    currRingHdl=rFindHdl(cr,NULL,NULL);
389    if (currRingHdl==NULL)
390      currRing=NULL;
391    else
392      rChangeCurrRing(cr);
393  }
394
395  if (myynest<=1) iiNoKeepRing=TRUE;
396  //Print("end killlocals  >= %d\n",v);
397  //listall();
398}
399#endif
400
401void list_cmd(int typ, const char* what, const char *prefix,BOOLEAN iterate, BOOLEAN fullname)
402{
403  idhdl h,start;
404  BOOLEAN all = typ<0;
405  BOOLEAN really_all=FALSE;
406  BOOLEAN do_packages=FALSE;
407
408  if ( typ == -1 ) do_packages=TRUE;
409  if ( typ==0 )
410  {
411    if (strcmp(what,"all")==0)
412    {
413      really_all=TRUE;
414#ifdef HAVE_NS
415      h=basePack->idroot;
416#else
417      h=IDROOT;
418#endif
419    }
420    else
421    {
422      h = ggetid(what);
423      if (h!=NULL)
424      {
425        if (iterate) list1(prefix,h,TRUE,fullname);
426        if ((IDTYP(h)==RING_CMD)
427            || (IDTYP(h)==QRING_CMD)
428#ifdef HAVE_NS
429            //|| (IDTYP(h)==PACKE_CMD)
430#endif
431        )
432        {
433          h=IDRING(h)->idroot;
434        }
435        else if((IDTYP(h)==PACKAGE_CMD) || (IDTYP(h)==POINTER_CMD))
436        {
437          //Print("list_cmd:package or pointer\n");
438          all=TRUE;typ=PROC_CMD;fullname=TRUE;really_all=TRUE;
439          h=IDPACKAGE(h)->idroot;
440        }
441        else
442          return;
443      }
444      else
445      {
446        Werror("%s is undefined",what);
447        return;
448      }
449    }
450    all=TRUE;
451  }
452  else if (RingDependend(typ))
453  {
454    h = currRing->idroot;
455  }
456  else
457    h = IDROOT;
458  start=h;
459  while (h!=NULL)
460  {
461    if ((all && (IDTYP(h)!=PROC_CMD) &&(IDTYP(h)!=PACKAGE_CMD))
462    || (typ == IDTYP(h))
463    || ((IDTYP(h)==QRING_CMD) && (typ==RING_CMD)))
464    {
465      list1(prefix,h,start==currRingHdl, fullname);
466      if (((IDTYP(h)==RING_CMD)||(IDTYP(h)==QRING_CMD))
467        && (really_all || (all && (h==currRingHdl)))
468        && ((IDLEV(h)==0)||(IDLEV(h)==myynest)))
469      {
470        list_cmd(0,IDID(h),"//      ",FALSE);
471      }
472#ifdef HAVE_NS
473      if (IDTYP(h)==PACKAGE_CMD && really_all)
474      {
475        package save_p=currPack;
476        currPack=IDPACKAGE(h);
477        list_cmd(0,IDID(h),"//      ",FALSE);
478        currPack=save_p;
479      }
480#endif /* HAVE_NS */
481    }
482    h = IDNEXT(h);
483  }
484}
485
486void test_cmd(int i)
487{
488  int ii=(char)i;
489
490  if (i == (-32))
491  {
492    test = 0;
493  }
494  else
495  {
496    if (i<0)
497    {
498      ii= -i;
499      if (Sy_bit(ii) & kOptions)
500      {
501        Warn("Gerhard, use the option command");
502        test &= ~Sy_bit(ii);
503      }
504      else if (Sy_bit(ii) & validOpts)
505        test &= ~Sy_bit(ii);
506    }
507    else if (i<32)
508    {
509      if (Sy_bit(ii) & kOptions)
510      {
511        Warn("Gerhard, use the option command");
512        test |= Sy_bit(ii);
513      }
514      else if (Sy_bit(ii) & validOpts)
515        test |= Sy_bit(ii);
516    }
517  }
518}
519
520int exprlist_length(leftv v)
521{
522  int rc = 0;
523  while (v!=NULL)
524  {
525    switch (v->Typ())
526    {
527      case INT_CMD:
528      case POLY_CMD:
529      case VECTOR_CMD:
530      case NUMBER_CMD:
531        rc++;
532        break;
533      case INTVEC_CMD:
534      case INTMAT_CMD:
535        rc += ((intvec *)(v->Data()))->length();
536        break;
537      case MATRIX_CMD:
538      case IDEAL_CMD:
539      case MODUL_CMD:
540        {
541          matrix mm = (matrix)(v->Data());
542          rc += mm->rows() * mm->cols();
543        }
544        break;
545      case LIST_CMD:
546        rc+=((lists)v->Data())->nr+1;
547        break;
548      default:
549        rc++;
550    }
551    v = v->next;
552  }
553  return rc;
554}
555
556int IsPrime(int p)  /* brute force !!!! */
557{
558  int i,j;
559  if      (p == 0)    return 0;
560  else if (p == 1)    return 1/*1*/;
561  else if (p == 2)    return p;
562  else if (p < 0)     return (-IsPrime(-p));
563  else if (!(p & 1)) return IsPrime(p-1);
564#ifdef HAVE_FACTORY
565  else if (p<=32749) // max. small prime in factory
566  {
567    int a=0;
568    int e=cf_getNumSmallPrimes()-1;
569    i=e/2;
570    do
571    {
572      if (p==(j=cf_getSmallPrime(i))) return p;
573      if (p<j) e=i-1;
574      else     a=i+1;
575      i=a+(e-a)/2;
576    } while ( a<= e);
577    if (p>j) return j;
578    else     return cf_getSmallPrime(i-1);
579  }
580#endif
581#ifdef HAVE_FACTORY
582  int end_i=cf_getNumSmallPrimes()-1;
583#else
584  int end_i=p/2;
585#endif
586  int end_p=(int)sqrt((double)p);
587restart:
588  for (i=0; i<end_i; i++)
589  {
590#ifdef HAVE_FACTORY
591    j=cf_getSmallPrime(i);
592#else
593    if (i==0) j=2;
594    else j=2*i-1;
595#endif
596    if ((p%j) == 0)
597    {
598    #ifdef HAVE_FACTORY
599      if (p<=32751) return IsPrime(p-2);
600    #endif
601      p-=2;
602      goto restart;
603    }
604    if (j > end_p) return p;
605  }
606  return p;
607}
608
609BOOLEAN iiWRITE(leftv res,leftv v)
610{
611  sleftv vf;
612  if (iiConvert(v->Typ(),LINK_CMD,iiTestConvert(v->Typ(),LINK_CMD),v,&vf))
613  {
614    WerrorS("link expected");
615    return TRUE;
616  }
617  si_link l=(si_link)vf.Data();
618  if (vf.next == NULL)
619  {
620    WerrorS("write: need at least two arguments");
621    return TRUE;
622  }
623
624  BOOLEAN b=slWrite(l,vf.next); /* iiConvert preserves next */
625  if (b)
626  {
627    const char *s;
628    if ((l!=NULL)&&(l->name!=NULL)) s=l->name;
629    else                            s=sNoName;
630    Werror("cannot write to %s",s);
631  }
632  vf.CleanUp();
633  return b;
634}
635
636leftv iiMap(map theMap, char * what)
637{
638  idhdl w,r;
639  leftv v;
640  int i;
641  nMapFunc nMap;
642
643  r=IDROOT->get(theMap->preimage,myynest);
644#ifdef HAVE_NS
645  if ((currPack!=basePack)
646  &&((r==NULL) || ((r->typ != RING_CMD) && (r->typ != QRING_CMD))))
647    r=basePack->idroot->get(theMap->preimage,myynest);
648  if ((r==NULL) && (currRingHdl!=NULL)
649  && (strcmp(theMap->preimage,IDID(currRingHdl))==0))
650  {
651    r=currRingHdl;
652  }
653#endif /* HAVE_NS */
654  if ((r!=NULL) && ((r->typ == RING_CMD) || (r->typ== QRING_CMD)))
655  {
656    //if ((nMap=nSetMap(rInternalChar(IDRING(r)),
657    //             IDRING(r)->parameter,
658    //             rPar(IDRING(r)),
659    //             IDRING(r)->minpoly)))
660    if ((nMap=nSetMap(IDRING(r)))==NULL)
661    {
662      if (rEqual(IDRING(r),currRing))
663      {
664        nMap=nCopy;
665      }
666      else
667      {
668        Werror("can not map from ground field of %s to current ground field",
669          theMap->preimage);
670        return NULL;
671      }
672    }
673    if (IDELEMS(theMap)<IDRING(r)->N)
674    {
675      theMap->m=(polyset)omReallocSize((ADDRESS)theMap->m,
676                                 IDELEMS(theMap)*sizeof(poly),
677                                 (IDRING(r)->N)*sizeof(poly));
678      for(i=IDELEMS(theMap);i<IDRING(r)->N;i++)
679        theMap->m[i]=NULL;
680      IDELEMS(theMap)=IDRING(r)->N;
681    }
682    if (what==NULL)
683    {
684      WerrorS("argument of a map must have a name");
685    }
686    else if ((w=IDRING(r)->idroot->get(what,myynest))!=NULL)
687    {
688      char *save_r=NULL;
689      v=(leftv)omAlloc0Bin(sleftv_bin);
690      sleftv tmpW;
691      memset(&tmpW,0,sizeof(sleftv));
692      tmpW.rtyp=IDTYP(w);
693      if (tmpW.rtyp==MAP_CMD)
694      {
695        tmpW.rtyp=IDEAL_CMD;
696        save_r=IDMAP(w)->preimage;
697        IDMAP(w)->preimage=0;
698      }
699      tmpW.data=IDDATA(w);
700      #if 0
701      if (((tmpW.rtyp==IDEAL_CMD)||(tmpW.rtyp==MODUL_CMD)) && idIs0(IDIDEAL(w)))
702      {
703        v->rtyp=tmpW.rtyp;
704        v->data=idInit(IDELEMS(IDIDEAL(w)),IDIDEAL(w)->rank);
705      }
706      else
707      #endif
708      {
709        #ifdef FAST_MAP
710        if ((tmpW.rtyp==IDEAL_CMD) && (nMap==nCopy)
711        #ifdef HAVE_PLURAL
712        && (!rIsPluralRing(currRing))
713        #endif
714        )
715        {
716          v->rtyp=IDEAL_CMD;
717          v->data=fast_map(IDIDEAL(w), IDRING(r), (ideal)theMap, currRing);
718        }
719        else
720        #endif
721        if (maApplyFetch(MAP_CMD,theMap,v,&tmpW,IDRING(r),NULL,NULL,0,nMap))
722        {
723          Werror("cannot map %s(%d)",Tok2Cmdname(w->typ),w->typ);
724          omFreeBin((ADDRESS)v, sleftv_bin);
725          if (save_r!=NULL) IDMAP(w)->preimage=save_r;
726          return NULL;
727        }
728      }
729      if (save_r!=NULL)
730      {
731        IDMAP(w)->preimage=save_r;
732        IDMAP((idhdl)v)->preimage=omStrDup(save_r);
733        v->rtyp=MAP_CMD;
734      }
735      return v;
736    }
737    else
738    {
739      Werror("%s undefined in %s",what,theMap->preimage);
740    }
741  }
742  else
743  {
744    Werror("cannot find preimage %s",theMap->preimage);
745  }
746  return NULL;
747}
748
749#ifdef OLD_RES
750void  iiMakeResolv(resolvente r, int length, int rlen, char * name, int typ0,
751                   intvec ** weights)
752{
753  lists L=liMakeResolv(r,length,rlen,typ0,weights);
754  int i=0;
755  idhdl h;
756  char * s=(char *)omAlloc(strlen(name)+5);
757
758  while (i<=L->nr)
759  {
760    sprintf(s,"%s(%d)",name,i+1);
761    if (i==0)
762      h=enterid(s,myynest,typ0,&(currRing->idroot), FALSE);
763    else
764      h=enterid(s,myynest,MODUL_CMD,&(currRing->idroot), FALSE);
765    if (h!=NULL)
766    {
767      h->data.uideal=(ideal)L->m[i].data;
768      h->attribute=L->m[i].attribute;
769      if (BVERBOSE(V_DEF_RES))
770        Print("//defining: %s as %d-th syzygy module\n",s,i+1);
771    }
772    else
773    {
774      idDelete((ideal *)&(L->m[i].data));
775      Warn("cannot define %s",s);
776    }
777    //L->m[i].data=NULL;
778    //L->m[i].rtyp=0;
779    //L->m[i].attribute=NULL;
780    i++;
781  }
782  omFreeSize((ADDRESS)L->m,(L->nr+1)*sizeof(sleftv));
783  omFreeBin((ADDRESS)L, slists_bin);
784  omFreeSize((ADDRESS)s,strlen(name)+5);
785}
786#endif
787
788//resolvente iiFindRes(char * name, int * len, int *typ0)
789//{
790//  char *s=(char *)omAlloc(strlen(name)+5);
791//  int i=-1;
792//  resolvente r;
793//  idhdl h;
794//
795//  do
796//  {
797//    i++;
798//    sprintf(s,"%s(%d)",name,i+1);
799//    h=currRing->idroot->get(s,myynest);
800//  } while (h!=NULL);
801//  *len=i-1;
802//  if (*len<=0)
803//  {
804//    Werror("no objects %s(1),.. found",name);
805//    omFreeSize((ADDRESS)s,strlen(name)+5);
806//    return NULL;
807//  }
808//  r=(ideal *)omAlloc(/*(len+1)*/ i*sizeof(ideal));
809//  memset(r,0,(*len)*sizeof(ideal));
810//  i=-1;
811//  *typ0=MODUL_CMD;
812//  while (i<(*len))
813//  {
814//    i++;
815//    sprintf(s,"%s(%d)",name,i+1);
816//    h=currRing->idroot->get(s,myynest);
817//    if (h->typ != MODUL_CMD)
818//    {
819//      if ((i!=0) || (h->typ!=IDEAL_CMD))
820//      {
821//        Werror("%s is not of type module",s);
822//        omFreeSize((ADDRESS)r,(*len)*sizeof(ideal));
823//        omFreeSize((ADDRESS)s,strlen(name)+5);
824//        return NULL;
825//      }
826//      *typ0=IDEAL_CMD;
827//    }
828//    if ((i>0) && (idIs0(r[i-1])))
829//    {
830//      *len=i-1;
831//      break;
832//    }
833//    r[i]=IDIDEAL(h);
834//  }
835//  omFreeSize((ADDRESS)s,strlen(name)+5);
836//  return r;
837//}
838
839static resolvente iiCopyRes(resolvente r, int l)
840{
841  int i;
842  resolvente res=(ideal *)omAlloc0((l+1)*sizeof(ideal));
843
844  for (i=0; i<l; i++)
845    res[i]=idCopy(r[i]);
846  return res;
847}
848
849BOOLEAN jjMINRES(leftv res, leftv v)
850{
851  int len=0;
852  int typ0;
853  lists L=(lists)v->Data();
854  intvec *weights=(intvec*)atGet(v,"isHomog",INTVEC_CMD);
855  int add_row_shift = 0;
856  if (weights==NULL)
857    weights=(intvec*)atGet(&(L->m[0]),"isHomog",INTVEC_CMD);
858  if (weights!=NULL)  add_row_shift=weights->min_in();
859  resolvente rr=liFindRes(L,&len,&typ0);
860  if (rr==NULL) return TRUE;
861  resolvente r=iiCopyRes(rr,len);
862
863  syMinimizeResolvente(r,len,0);
864  omFreeSize((ADDRESS)rr,len*sizeof(ideal));
865  len++;
866  res->data=(char *)liMakeResolv(r,len,-1,typ0,NULL,add_row_shift);
867  return FALSE;
868}
869
870BOOLEAN jjBETTI(leftv res, leftv u)
871{
872  sleftv tmp;
873  memset(&tmp,0,sizeof(tmp));
874  tmp.rtyp=INT_CMD;
875  tmp.data=(void *)1;
876  if ((u->Typ()==IDEAL_CMD)
877  || (u->Typ()==MODUL_CMD))
878    return jjBETTI2_ID(res,u,&tmp);
879  else
880    return jjBETTI2(res,u,&tmp);
881}
882
883BOOLEAN jjBETTI2_ID(leftv res, leftv u, leftv v)
884{
885  lists l=(lists) omAllocBin(slists_bin);
886  l->Init(1);
887  l->m[0].rtyp=u->Typ();
888  l->m[0].data=u->Data();
889  l->m[0].attribute=u->attribute;
890  sleftv tmp2;
891  memset(&tmp2,0,sizeof(tmp2));
892  tmp2.rtyp=LIST_CMD;
893  tmp2.data=(void *)l;
894  BOOLEAN r=jjBETTI2(res,&tmp2,v);
895  l->m[0].data=NULL;
896  l->m[0].attribute=NULL;
897  l->m[0].rtyp=DEF_CMD;
898  l->Clean();
899  return r;
900}
901
902BOOLEAN jjBETTI2(leftv res, leftv u, leftv v)
903{
904  resolvente r;
905  int len;
906  int reg,typ0;
907  lists l=(lists)u->Data();
908
909  intvec *weights=NULL;
910  int add_row_shift=0;
911  intvec *ww=(intvec *)atGet(&(l->m[0]),"isHomog",INTVEC_CMD);
912  if (ww!=NULL)
913  {
914     weights=ivCopy(ww);
915     add_row_shift = ww->min_in();
916     (*weights) -= add_row_shift;
917  }
918  //Print("attr:%x\n",weights);
919
920  r=liFindRes(l,&len,&typ0);
921  if (r==NULL) return TRUE;
922  res->data=(char *)syBetti(r,len,&reg,weights,(int)(long)v->Data());
923  omFreeSize((ADDRESS)r,(len)*sizeof(ideal));
924  atSet(res,omStrDup("rowShift"),(void*)add_row_shift,INT_CMD);
925  if (weights!=NULL) delete weights;
926  return FALSE;
927}
928
929int iiRegularity(lists L)
930{
931  int len,reg,typ0;
932
933  resolvente r=liFindRes(L,&len,&typ0);
934
935  if (r==NULL)
936    return -2;
937  intvec *weights=NULL;
938  int add_row_shift=0;
939  intvec *ww=(intvec *)atGet(&(L->m[0]),"isHomog",INTVEC_CMD);
940  if (ww!=NULL)
941  {
942     weights=ivCopy(ww);
943     add_row_shift = ww->min_in();
944     (*weights) -= add_row_shift;
945  }
946  //Print("attr:%x\n",weights);
947
948  intvec *dummy=syBetti(r,len,&reg,weights);
949  if (weights!=NULL) delete weights;
950  delete dummy;
951  omFreeSize((ADDRESS)r,len*sizeof(ideal));
952  return reg+1+add_row_shift;
953}
954
955BOOLEAN iiDebugMarker=TRUE;
956#define BREAK_LINE_LENGTH 80
957void iiDebug()
958{
959  Print("\n-- break point in %s --\n",VoiceName());
960  if (iiDebugMarker) VoiceBackTrack();
961  char * s;
962  iiDebugMarker=FALSE;
963  s = (char *)omAlloc(BREAK_LINE_LENGTH+4);
964  loop
965  {
966    memset(s,0,80);
967    fe_fgets_stdin("",s,BREAK_LINE_LENGTH);
968    if (s[BREAK_LINE_LENGTH-1]!='\0')
969    {
970      Print("line too long, max is %d chars\n",BREAK_LINE_LENGTH);
971    }
972    else
973      break;
974  }
975  if (*s=='\n')
976  {
977    iiDebugMarker=TRUE;
978  }
979#if MDEBUG
980  else if(strncmp(s,"cont;",5)==0)
981  {
982    iiDebugMarker=TRUE;
983  }
984#endif /* MDEBUG */
985  else
986  {
987    strcat( s, "\n;~\n");
988    newBuffer(s,BT_execute);
989  }
990}
991
992lists scIndIndset(ideal S, BOOLEAN all, ideal Q)
993{
994  int i;
995  indset save;
996  lists res=(lists)omAlloc0Bin(slists_bin);
997
998  hexist = hInit(S, Q, &hNexist);
999  if ((hNexist == 0) || (hisModule!=0))
1000  {
1001    res->Init(0);
1002    return res;
1003  }
1004  save = ISet = (indset)omAlloc0Bin(indlist_bin);
1005  hMu = 0;
1006  hwork = (scfmon)omAlloc(hNexist * sizeof(scmon));
1007  hvar = (varset)omAlloc((pVariables + 1) * sizeof(int));
1008  hpure = (scmon)omAlloc((1 + (pVariables * pVariables)) * sizeof(Exponent_t));
1009  hrad = hexist;
1010  hNrad = hNexist;
1011  radmem = hCreate(pVariables - 1);
1012  hCo = pVariables + 1;
1013  hNvar = pVariables;
1014  hRadical(hrad, &hNrad, hNvar);
1015  hSupp(hrad, hNrad, hvar, &hNvar);
1016  if (hNvar)
1017  {
1018    hCo = hNvar;
1019    memset(hpure, 0, (pVariables + 1) * sizeof(Exponent_t));
1020    hPure(hrad, 0, &hNrad, hvar, hNvar, hpure, &hNpure);
1021    hLexR(hrad, hNrad, hvar, hNvar);
1022    hDimSolve(hpure, hNpure, hrad, hNrad, hvar, hNvar);
1023  }
1024  if (hCo && (hCo < pVariables))
1025  {
1026    hIndMult(hpure, hNpure, hrad, hNrad, hvar, hNvar);
1027  }
1028  if (hMu!=0)
1029  {
1030    ISet = save;
1031    hMu2 = 0;
1032    if (all && (hCo+1 < pVariables))
1033    {
1034      JSet = (indset)omAlloc0Bin(indlist_bin);
1035      hIndAllMult(hpure, hNpure, hrad, hNrad, hvar, hNvar);
1036      i=hMu+hMu2;
1037      res->Init(i);
1038      if (hMu2 == 0)
1039      {
1040        omFreeBin((ADDRESS)JSet, indlist_bin);
1041      }
1042    }
1043    else
1044    {
1045      res->Init(hMu);
1046    }
1047    for (i=0;i<hMu;i++)
1048    {
1049      res->m[i].data = (void *)save->set;
1050      res->m[i].rtyp = INTVEC_CMD;
1051      ISet = save;
1052      save = save->nx;
1053      omFreeBin((ADDRESS)ISet, indlist_bin);
1054    }
1055    omFreeBin((ADDRESS)save, indlist_bin);
1056    if (hMu2 != 0)
1057    {
1058      save = JSet;
1059      for (i=hMu;i<hMu+hMu2;i++)
1060      {
1061        res->m[i].data = (void *)save->set;
1062        res->m[i].rtyp = INTVEC_CMD;
1063        JSet = save;
1064        save = save->nx;
1065        omFreeBin((ADDRESS)JSet, indlist_bin);
1066      }
1067      omFreeBin((ADDRESS)save, indlist_bin);
1068    }
1069  }
1070  else
1071  {
1072    res->Init(0);
1073    omFreeBin((ADDRESS)ISet,  indlist_bin);
1074  }
1075  hKill(radmem, pVariables - 1);
1076  omFreeSize((ADDRESS)hpure, (1 + (pVariables * pVariables)) * sizeof(Exponent_t));
1077  omFreeSize((ADDRESS)hvar, (pVariables + 1) * sizeof(int));
1078  omFreeSize((ADDRESS)hwork, hNexist * sizeof(scmon));
1079  hDelete(hexist, hNexist);
1080  return res;
1081}
1082
1083int iiDeclCommand(leftv sy, leftv name, int lev,int t, idhdl* root,BOOLEAN isring, BOOLEAN init_b)
1084{
1085  BOOLEAN res=FALSE;
1086  char *id = name->name;
1087
1088  memset(sy,0,sizeof(sleftv));
1089  if ((name->name==NULL)||(isdigit(name->name[0])))
1090  {
1091    WerrorS("object to declare is not a name");
1092    res=TRUE;
1093  }
1094  else
1095  {
1096    //if (name->rtyp!=0)
1097    //{
1098    //  Warn("`%s` is already in use",name->name);
1099    //}
1100    {
1101      sy->data = (char *)enterid(id,lev,t,root,init_b);
1102    }
1103    if (sy->data!=NULL)
1104    {
1105      sy->rtyp=IDHDL;
1106      currid=sy->name=IDID((idhdl)sy->data);
1107      // name->name=NULL; /* used in enterid */
1108      //sy->e = NULL;
1109      if (name->next!=NULL)
1110      {
1111        sy->next=(leftv)omAllocBin(sleftv_bin);
1112        res=iiDeclCommand(sy->next,name->next,lev,t,root, isring);
1113      }
1114    }
1115    else res=TRUE;
1116  }
1117  name->CleanUp();
1118  return res;
1119}
1120
1121BOOLEAN iiParameter(leftv p)
1122{
1123  if (iiCurrArgs==NULL)
1124  {
1125    if (strcmp(p->name,"#")==0) return FALSE;
1126    Werror("not enough arguments for proc %s",VoiceName());
1127    p->CleanUp();
1128    return TRUE;
1129  }
1130  leftv h=iiCurrArgs;
1131  if (strcmp(p->name,"#")==0)
1132  {
1133    iiCurrArgs=NULL;
1134  }
1135  else
1136  {
1137    iiCurrArgs=h->next;
1138    h->next=NULL;
1139  }
1140  BOOLEAN res=iiAssign(p,h);
1141  h->CleanUp();
1142  omFreeBin((ADDRESS)h, sleftv_bin);
1143  return res;
1144}
1145
1146static BOOLEAN iiInternalExport (leftv v, int toLev)
1147{
1148  idhdl h=(idhdl)v->data;
1149  //Print("iiInternalExport('%s',%d)%s\n", v->name, toLev,"");
1150  if (IDLEV(h)==0) Warn("`%s` is already global",IDID(h));
1151  else
1152  {
1153    h=IDROOT->get(v->name,toLev);
1154    idhdl *root=&IDROOT;
1155    if ((h==NULL)&&(currRing!=NULL))
1156    {
1157      h=currRing->idroot->get(v->name,toLev);
1158      root=&currRing->idroot;
1159    }
1160    BOOLEAN keepring=FALSE;
1161    if ((h!=NULL)&&(IDLEV(h)==toLev))
1162    {
1163      if (IDTYP(h)==v->Typ())
1164      {
1165        if (((IDTYP(h)==RING_CMD)||(IDTYP(h)==QRING_CMD))
1166        && (v->Data()==IDDATA(h)))
1167        {
1168          IDRING(h)->ref++;
1169          keepring=TRUE;
1170          IDLEV(h)=toLev;
1171          //WarnS("keepring");
1172          return FALSE;
1173        }
1174        if (BVERBOSE(V_REDEFINE))
1175        {
1176          Warn("redefining %s",IDID(h));
1177        }
1178#ifdef USE_IILOCALRING
1179        if (iiLocalRing[0]==IDRING(h) && (!keepring)) iiLocalRing[0]=NULL;
1180#else
1181        proclevel *p=procstack;
1182        while (p->next!=NULL) p=p->next;
1183        if ((p->cRing==IDRING(h)) && (!keepring))
1184        {
1185          p->cRing=NULL;
1186          p->cRingHdl=NULL;
1187        }
1188#endif
1189        killhdl2(h,root,currRing);
1190      }
1191      else
1192      {
1193        return TRUE;
1194      }
1195    }
1196    h=(idhdl)v->data;
1197    IDLEV(h)=toLev;
1198    if (keepring) IDRING(h)->ref--;
1199    iiNoKeepRing=FALSE;
1200    //Print("export %s\n",IDID(h));
1201  }
1202  return FALSE;
1203}
1204
1205#ifdef HAVE_NS
1206BOOLEAN iiInternalExport (leftv v, int toLev, idhdl roothdl)
1207{
1208  idhdl h=(idhdl)v->data;
1209  if(h==NULL)
1210  {
1211    Warn("'%s': no such identifier\n", v->name);
1212    return FALSE;
1213  }
1214  package frompack=v->req_packhdl;
1215  if (frompack==NULL) frompack=currPack;
1216  package rootpack = IDPACKAGE(roothdl);
1217//  Print("iiInternalExport('%s',%d,%s->%s) typ:%d\n", v->name, toLev, IDID(currPackHdl),IDID(roothdl),v->Typ());
1218  if ((RingDependend(IDTYP(h)))
1219  || ((IDTYP(h)==LIST_CMD)
1220     && (lRingDependend(IDLIST(h)))
1221     )
1222  )
1223  {
1224    //Print("// ==> Ringdependent set nesting to 0\n");
1225    return (iiInternalExport(v, toLev));
1226  }
1227  else
1228  {
1229    IDLEV(h)=toLev;
1230    v->req_packhdl=rootpack;
1231    if (h==frompack->idroot)
1232    {
1233      frompack->idroot=h->next;
1234    }
1235    else
1236    {
1237      idhdl hh=frompack->idroot;
1238      while ((hh!=NULL) && (hh->next!=h))
1239        hh=hh->next;
1240      if ((hh!=NULL) && (hh->next==h))
1241        hh->next=h->next;
1242      else
1243      {
1244        Werror("`%s` not found",v->Name());
1245        return TRUE;
1246      }
1247    }
1248    h->next=rootpack->idroot;
1249    rootpack->idroot=h;
1250  }
1251  return FALSE;
1252}
1253#endif /* HAVE_NS */
1254
1255BOOLEAN iiExport (leftv v, int toLev)
1256{
1257#ifdef HAVE_NS
1258#ifndef NDEBUG
1259  checkall();
1260#endif
1261#endif
1262  BOOLEAN nok=FALSE;
1263  leftv r=v;
1264  while (v!=NULL)
1265  {
1266    if ((v->name==NULL)||(v->rtyp==0)||(v->e!=NULL))
1267    {
1268      WerrorS("cannot export");
1269      nok=TRUE;
1270    }
1271    else
1272    {
1273      if(iiInternalExport(v, toLev))
1274      {
1275        r->CleanUp();
1276        return TRUE;
1277      }
1278    }
1279    v=v->next;
1280  }
1281  r->CleanUp();
1282#ifdef HAVE_NS
1283#ifndef NDEBUG
1284  checkall();
1285#endif
1286#endif
1287  return nok;
1288}
1289
1290/*assume root!=idroot*/
1291#ifdef HAVE_NS
1292BOOLEAN iiExport (leftv v, int toLev, idhdl root)
1293{
1294#ifndef NDEBUG
1295  checkall();
1296#endif
1297  //  Print("iiExport1: pack=%s\n",IDID(root));
1298  package pack=IDPACKAGE(root);
1299  BOOLEAN nok=FALSE;
1300  leftv rv=v;
1301  while (v!=NULL)
1302  {
1303    if ((v->name==NULL)||(v->rtyp==0)||(v->e!=NULL)
1304    )
1305    {
1306      WerrorS("cannot export");
1307      nok=TRUE;
1308    }
1309    else
1310    {
1311      idhdl old=pack->idroot->get( v->name,toLev);
1312      if (old!=NULL)
1313      {
1314        if ((pack==currPack) && (old==(idhdl)v->data))
1315        {
1316          Warn("`%s` is already global",IDID(old));
1317          break;
1318        }
1319        else if (IDTYP(old)==v->Typ())
1320        {
1321          if (BVERBOSE(V_REDEFINE))
1322          {
1323            Warn("redefining %s",IDID(old));
1324          }
1325          v->name=omStrDup(v->name);
1326          killhdl2(old,&(pack->idroot),currRing);
1327        }
1328        else
1329        {
1330          rv->CleanUp();
1331          return TRUE;
1332        }
1333      }
1334      //Print("iiExport: pack=%s\n",IDID(root));
1335      if(iiInternalExport(v, toLev, root))
1336      {
1337        rv->CleanUp();
1338        return TRUE;
1339      }
1340    }
1341    v=v->next;
1342  }
1343  rv->CleanUp();
1344#ifndef NDEBUG
1345  checkall();
1346#endif
1347  return nok;
1348}
1349#endif
1350
1351BOOLEAN iiCheckRing(int i)
1352{
1353  if (currRingHdl==NULL)
1354  {
1355    #ifdef SIQ
1356    if (siq<=0)
1357    {
1358    #endif
1359      if (RingDependend(i))
1360      {
1361        WerrorS("no ring active");
1362        return TRUE;
1363      }
1364    #ifdef SIQ
1365    }
1366    #endif
1367  }
1368  return FALSE;
1369}
1370
1371poly    iiHighCorner(ideal I, int ak)
1372{
1373  int i;
1374  if(!idIsZeroDim(I)) return NULL; // not zero-dim.
1375  poly po=NULL;
1376  if (currRing->OrdSgn== -1)
1377  {
1378    scComputeHC(I,currQuotient,ak,po);
1379    if (po!=NULL)
1380    {
1381      pGetCoeff(po)=nInit(1);
1382      for (i=pVariables; i>0; i--)
1383      {
1384        if (pGetExp(po, i) > 0) pDecrExp(po,i);
1385      }
1386      pSetComp(po,ak);
1387      pSetm(po);
1388    }
1389  }
1390  else
1391    po=pOne();
1392  return po;
1393}
1394
1395#ifdef HAVE_NS
1396void iiCheckPack(package &p)
1397{
1398  if (p==basePack) return;
1399
1400  idhdl t=basePack->idroot;
1401
1402  while ((t!=NULL) && (IDTYP(t)!=PACKAGE_CMD) && (IDPACKAGE(t)!=p)) t=t->next;
1403
1404  if (t==NULL)
1405  {
1406    WarnS("package not found\n");
1407    p=basePack;
1408  }
1409  return;
1410}
1411#endif
1412
1413idhdl rDefault(char *s)
1414{
1415  idhdl tmp=NULL;
1416
1417  if (s!=NULL) tmp = enterid(s, myynest, RING_CMD, &IDROOT);
1418  if (tmp==NULL) return NULL;
1419
1420  if (ppNoether!=NULL) pDelete(&ppNoether);
1421  if (sLastPrinted.RingDependend())
1422  {
1423    sLastPrinted.CleanUp();
1424    memset(&sLastPrinted,0,sizeof(sleftv));
1425  }
1426
1427  ring r = IDRING(tmp);
1428
1429  r->ch    = 32003;
1430  r->N     = 3;
1431  /*r->P     = 0; Alloc0 in idhdl::set, ipid.cc*/
1432  /*names*/
1433  r->names = (char **) omAlloc0(3 * sizeof(char_ptr));
1434  r->names[0]  = omStrDup("x");
1435  r->names[1]  = omStrDup("y");
1436  r->names[2]  = omStrDup("z");
1437  /*weights: entries for 3 blocks: NULL*/
1438  r->wvhdl = (int **)omAlloc0(3 * sizeof(int_ptr));
1439  /*order: dp,C,0*/
1440  r->order = (int *) omAlloc(3 * sizeof(int *));
1441  r->block0 = (int *)omAlloc0(3 * sizeof(int *));
1442  r->block1 = (int *)omAlloc0(3 * sizeof(int *));
1443  /* ringorder dp for the first block: var 1..3 */
1444  r->order[0]  = ringorder_dp;
1445  r->block0[0] = 1;
1446  r->block1[0] = 3;
1447  /* ringorder C for the second block: no vars */
1448  r->order[1]  = ringorder_C;
1449  /* the last block: everything is 0 */
1450  r->order[2]  = 0;
1451  /*polynomial ring*/
1452  r->OrdSgn    = 1;
1453
1454  /* complete ring intializations */
1455  rComplete(r);
1456  rSetHdl(tmp);
1457  return currRingHdl;
1458}
1459
1460idhdl rFindHdl(ring r, idhdl n, idhdl w)
1461{
1462  idhdl h=rSimpleFindHdl(r,IDROOT,n);
1463  if (h!=NULL)  return h;
1464#ifdef HAVE_NS
1465  if (IDROOT!=basePack->idroot) h=rSimpleFindHdl(r,basePack->idroot,n);
1466  if (h!=NULL)  return h;
1467  proclevel *p=procstack;
1468  while(p!=NULL)
1469  {
1470    if ((p->cPack!=basePack)
1471    && (p->cPack!=currPack))
1472      h=rSimpleFindHdl(r,p->cPack->idroot,n);
1473    if (h!=NULL)  return h;
1474    p=p->next;
1475  }
1476  idhdl tmp=basePack->idroot;
1477  while (tmp!=NULL)
1478  {
1479    if (IDTYP(tmp)==PACKAGE_CMD)
1480      h=rSimpleFindHdl(r,IDPACKAGE(tmp)->idroot,n);
1481    if (h!=NULL)  return h;
1482    tmp=IDNEXT(tmp);
1483  }
1484#endif
1485  return NULL;
1486}
1487
1488void rDecomposeCF(leftv h,const ring r,const ring R)
1489{
1490  lists L=(lists)omAlloc0Bin(slists_bin);
1491  L->Init(4);
1492  h->rtyp=LIST_CMD;
1493  h->data=(void *)L;
1494  // 0: char/ cf - ring
1495  // 1: list (var)
1496  // 2: list (ord)
1497  // 3: qideal
1498  // ----------------------------------------
1499  // 0: char/ cf - ring
1500  L->m[0].rtyp=INT_CMD;
1501  L->m[0].data=(void *)r->ch;
1502  // ----------------------------------------
1503  // 1: list (var)
1504  lists LL=(lists)omAlloc0Bin(slists_bin);
1505  LL->Init(r->N);
1506  int i;
1507  for(i=0; i<r->N; i++)
1508  {
1509    LL->m[i].rtyp=STRING_CMD;
1510    LL->m[i].data=(void *)omStrDup(r->names[i]);
1511  }
1512  L->m[1].rtyp=LIST_CMD;
1513  L->m[1].data=(void *)LL;
1514  // ----------------------------------------
1515  // 2: list (ord)
1516  LL=(lists)omAlloc0Bin(slists_bin);
1517  i=rBlocks(r)-1;
1518  LL->Init(i);
1519  i--;
1520  lists LLL;
1521  for(; i>=0; i--)
1522  {
1523    intvec *iv;
1524    int j;
1525    LL->m[i].rtyp=LIST_CMD;
1526    LLL=(lists)omAlloc0Bin(slists_bin);
1527    LLL->Init(2);
1528    LLL->m[0].rtyp=STRING_CMD;
1529    LLL->m[0].data=(void *)omStrDup(rSimpleOrdStr(r->order[i]));
1530    if (r->block1[i]-r->block0[i] >=0 )
1531    {
1532      j=r->block1[i]-r->block0[i];
1533      if(r->order[i]==ringorder_M) j=(j+1)*(j+1)-1;
1534      iv=new intvec(j+1);
1535      if ((r->wvhdl!=NULL) && (r->wvhdl[i]!=NULL))
1536      {
1537        for(;j>=0; j--) (*iv)[j]=r->wvhdl[i][j];
1538      }
1539      else switch (r->order[i])
1540      {
1541        case ringorder_dp:
1542        case ringorder_Dp:
1543        case ringorder_ds:
1544        case ringorder_Ds:
1545        case ringorder_lp:
1546          for(;j>=0; j--) (*iv)[j]=1;
1547          break;
1548        default: /* do nothing */;
1549      }
1550    }
1551    else
1552    {
1553      iv=new intvec(1);
1554    }
1555    LLL->m[1].rtyp=INTVEC_CMD;
1556    LLL->m[1].data=(void *)iv;
1557    LL->m[i].data=(void *)LLL;
1558  }
1559  L->m[2].rtyp=LIST_CMD;
1560  L->m[2].data=(void *)LL;
1561  // ----------------------------------------
1562  // 3: qideal
1563  L->m[3].rtyp=IDEAL_CMD;
1564  if (R->minpoly==NULL)
1565    L->m[3].data=(void *)idInit(1,1);
1566  else
1567  {
1568    ideal I=idInit(1,1);
1569    L->m[3].data=(void *)I;
1570    I->m[0]=pOne();
1571    pSetCoeff(I->m[0],R->minpoly);
1572  }
1573  // ----------------------------------------
1574}
1575void rDecomposeC(leftv h,const ring R)
1576/* field is R or C */
1577{
1578  lists L=(lists)omAlloc0Bin(slists_bin);
1579  if (rField_is_long_C(R)) L->Init(3);
1580  else                     L->Init(2);
1581  h->rtyp=LIST_CMD;
1582  h->data=(void *)L;
1583  // 0: char/ cf - ring
1584  // 1: list (var)
1585  // 2: list (ord)
1586  // ----------------------------------------
1587  // 0: char/ cf - ring
1588  L->m[0].rtyp=INT_CMD;
1589  L->m[0].data=(void *)0;
1590  // ----------------------------------------
1591  // 1:
1592  lists LL=(lists)omAlloc0Bin(slists_bin);
1593  LL->Init(2);
1594    LL->m[0].rtyp=INT_CMD;
1595    LL->m[0].data=(void *)si_max(R->float_len,SHORT_REAL_LENGTH/2);
1596    LL->m[1].rtyp=INT_CMD;
1597    LL->m[1].data=(void *)si_max(R->float_len2,SHORT_REAL_LENGTH);
1598  L->m[1].rtyp=LIST_CMD;
1599  L->m[1].data=(void *)LL;
1600  // ----------------------------------------
1601  // 2: list (par)
1602  if (rField_is_long_C(R))
1603  {
1604    L->m[2].rtyp=STRING_CMD;
1605    L->m[2].data=(void *)omStrDup(R->parameter[0]);
1606  }
1607  // ----------------------------------------
1608}
1609
1610lists rDecompose(const ring r)
1611{
1612  // sanity check: require currRing==r for rings with polynomial data
1613  if ((r!=currRing)
1614  && ((r->minpoly!=NULL) || (r->qideal!=NULL) || (r->minideal!=NULL)
1615#ifdef HAVE_PLURAL
1616  || (rIsPluralRing(r))
1617#endif
1618  ))
1619  {
1620    WerrorS("ring with polynomial data must be the base ring or compatible");
1621    return NULL;
1622  }
1623  // 0: char/ cf - ring
1624  // 1: list (var)
1625  // 2: list (ord)
1626  // 3: qideal
1627  // possibly:
1628  // 4: C
1629  // 5: D
1630  lists L=(lists)omAlloc0Bin(slists_bin);
1631  if (rIsPluralRing(r))
1632    L->Init(6);
1633  else
1634    L->Init(4);
1635  // ----------------------------------------
1636  // 0: char/ cf - ring
1637  #if 1 /* TODO */
1638  if (rField_is_numeric(r))
1639  {
1640    rDecomposeC(&(L->m[0]),r);
1641  }
1642  else if (rIsExtension(r))
1643  {
1644    if (r->algring!=NULL)
1645      rDecomposeCF(&(L->m[0]),r->algring,r);
1646    if (L->m[0].rtyp==0)
1647    {
1648      //omFreeBin(slists_bin,(void *)L);
1649      return NULL;
1650    }
1651  }
1652  else
1653  #endif
1654  {
1655    L->m[0].rtyp=INT_CMD;
1656    L->m[0].data=(void *)r->ch;
1657  }
1658  // ----------------------------------------
1659  // 1: list (var)
1660  lists LL=(lists)omAlloc0Bin(slists_bin);
1661  LL->Init(r->N);
1662  int i;
1663  for(i=0; i<r->N; i++)
1664  {
1665    LL->m[i].rtyp=STRING_CMD;
1666    LL->m[i].data=(void *)omStrDup(r->names[i]);
1667  }
1668  L->m[1].rtyp=LIST_CMD;
1669  L->m[1].data=(void *)LL;
1670  // ----------------------------------------
1671  // 2: list (ord)
1672  LL=(lists)omAlloc0Bin(slists_bin);
1673  i=rBlocks(r)-1;
1674  LL->Init(i);
1675  i--;
1676  lists LLL;
1677  for(; i>=0; i--)
1678  {
1679    intvec *iv;
1680    int j;
1681    LL->m[i].rtyp=LIST_CMD;
1682    LLL=(lists)omAlloc0Bin(slists_bin);
1683    LLL->Init(2);
1684    LLL->m[0].rtyp=STRING_CMD;
1685    LLL->m[0].data=(void *)omStrDup(rSimpleOrdStr(r->order[i]));
1686    if (r->block1[i]-r->block0[i] >=0 )
1687    {
1688      j=r->block1[i]-r->block0[i];
1689      if (r->order[i]==ringorder_M)  j=(j+1)*(j+1)-1;
1690      iv=new intvec(j+1);
1691      if ((r->wvhdl!=NULL) && (r->wvhdl[i]!=NULL))
1692      {
1693        for(;j>=0; j--) (*iv)[j]=r->wvhdl[i][j];
1694      }
1695      else switch (r->order[i])
1696      {
1697        case ringorder_dp:
1698        case ringorder_Dp:
1699        case ringorder_ds:
1700        case ringorder_Ds:
1701        case ringorder_lp:
1702          for(;j>=0; j--) (*iv)[j]=1;
1703          break;
1704        default: /* do nothing */;
1705      }
1706    }
1707    else
1708    {
1709      iv=new intvec(1);
1710    }
1711    LLL->m[1].rtyp=INTVEC_CMD;
1712    LLL->m[1].data=(void *)iv;
1713    LL->m[i].data=(void *)LLL;
1714  }
1715  L->m[2].rtyp=LIST_CMD;
1716  L->m[2].data=(void *)LL;
1717  // ----------------------------------------
1718  // 3: qideal
1719  L->m[3].rtyp=IDEAL_CMD;
1720  if (r->qideal==NULL)
1721    L->m[3].data=(void *)idInit(1,1);
1722  else
1723    L->m[3].data=(void *)idCopy(r->qideal);
1724  // ----------------------------------------
1725  #ifdef HAVE_PLURAL
1726  if (rIsPluralRing(r))
1727  {
1728    L->m[4].rtyp=MATRIX_CMD;
1729    L->m[4].data=(void *)mpCopy(r->nc->C);
1730    L->m[5].rtyp=MATRIX_CMD;
1731    L->m[5].data=(void *)mpCopy(r->nc->D);
1732  }
1733  #endif
1734  return L;
1735}
1736
1737void rComposeC(lists L, ring R)
1738/* field is R or C */
1739{
1740  // ----------------------------------------
1741  // 0: char/ cf - ring
1742  if ((L->m[0].rtyp!=INT_CMD) || (L->m[0].data!=(char *)0))
1743  {
1744    Werror("invald coeff. field description, expecting 0");
1745    return;
1746  }
1747  R->ch=-1;
1748  // ----------------------------------------
1749  // 1:
1750  if (L->m[1].rtyp!=LIST_CMD)
1751    Werror("invald coeff. field description, expecting precision list");
1752  lists LL=(lists)L->m[1].data;
1753  int r1=(int)(long)LL->m[0].data;
1754  int r2=(int)(long)LL->m[1].data;
1755  if ((r1<=SHORT_REAL_LENGTH)
1756  && (r2=SHORT_REAL_LENGTH))
1757  {
1758    R->float_len=SHORT_REAL_LENGTH/2;
1759    R->float_len2=SHORT_REAL_LENGTH;
1760  }
1761  else
1762  {
1763    R->float_len=si_min(r1,32767);
1764    R->float_len2=si_min(r2,32767);
1765  }
1766  // ----------------------------------------
1767  // 2: list (par)
1768  if (L->nr==2)
1769  {
1770    R->P=1;
1771    if (L->m[2].rtyp!=STRING_CMD)
1772    {
1773      Werror("invald coeff. field description, expecting parameter name");
1774      return;
1775    }
1776    R->parameter=(char**)omAlloc0(R->P*sizeof(char_ptr));
1777    R->parameter[0]=omStrDup((char *)L->m[2].data);
1778  }
1779  // ----------------------------------------
1780}
1781ring rCompose(const lists  L)
1782{
1783  if ((L->nr!=3)
1784#ifdef HAVE_PLURAL
1785  &&(L->nr!=5)
1786#endif
1787  )
1788    return NULL;
1789  // 0: char/ cf - ring
1790  // 1: list (var)
1791  // 2: list (ord)
1792  // 3: qideal
1793  // possibly:
1794  // 4: C
1795  // 5: D
1796  ring R=(ring) omAlloc0Bin(sip_sring_bin);
1797  // ------------------------- VARS ---------------------------
1798  if (L->m[1].Typ()==LIST_CMD)
1799  {
1800    lists v=(lists)L->m[1].Data();
1801    R->N = v->nr+1;
1802    R->names   = (char **)omAlloc0(R->N * sizeof(char_ptr));
1803    int i;
1804    for(i=0;i<R->N;i++)
1805    {
1806      if (v->m[i].Typ()==STRING_CMD)
1807        R->names[i]=omStrDup((char *)v->m[i].Data());
1808      else if (v->m[i].Typ()==POLY_CMD)
1809      {
1810        poly p=(poly)v->m[i].Data();
1811        int nr=pIsPurePower(p);
1812        if (nr>0)
1813          R->names[i]=omStrDup(currRing->names[nr-1]);
1814        else
1815        {
1816          Werror("var name %d must be a string or a ring variable",i+1);
1817          goto rCompose_err;
1818        }
1819      }
1820      else
1821      {
1822        Werror("var name %d must be `string`",i+1);
1823        goto rCompose_err;
1824      }
1825    }
1826  }
1827  else
1828  {
1829    WerrorS("variable must be given as `list`");
1830    goto rCompose_err;
1831  }
1832  rNameCheck(R);
1833  // ------------------------ ORDER ------------------------------
1834  if (L->m[2].Typ()==LIST_CMD)
1835  {
1836    lists v=(lists)L->m[2].Data();
1837    int n= v->nr+2;
1838    int j;
1839    // initialize fields of R
1840    R->order=(int *)omAlloc0(n*sizeof(int));
1841    R->block0=(int *)omAlloc0(n*sizeof(int));
1842    R->block1=(int *)omAlloc0(n*sizeof(int));
1843    R->wvhdl=(int**)omAlloc0(n*sizeof(int_ptr));
1844    // init order, so that rBlocks works correctly
1845    for (j=0; j < n-1; j++)
1846      R->order[j] = (int) ringorder_unspec;
1847    // orderings
1848    R->OrdSgn=1;
1849    for(j=0;j<n-1;j++)
1850    {
1851    // todo: a(..), M
1852      if (v->m[j].Typ()!=LIST_CMD)
1853      {
1854        WerrorS("ordering must be list of lists");
1855        goto rCompose_err;
1856      }
1857      lists vv=(lists)v->m[j].Data();
1858      if ((vv->nr!=1)
1859      || (vv->m[0].Typ()!=STRING_CMD)
1860      || ((vv->m[1].Typ()!=INTVEC_CMD) && (vv->m[1].Typ()!=INT_CMD)))
1861      {
1862        WerrorS("ordering name must be a (string,intvec)");
1863        goto rCompose_err;
1864      }
1865      R->order[j]=rOrderName(omStrDup((char*)vv->m[0].Data())); // assume STRING
1866      if (j==0) R->block0[0]=1;
1867      else
1868      {
1869         int jj=j-1;
1870         while((jj>=0)
1871         && ((R->order[jj]== ringorder_a)
1872            || (R->order[jj]== ringorder_aa)
1873            || (R->order[jj]== ringorder_c)
1874            || (R->order[jj]== ringorder_C)
1875         ))
1876         {
1877           //Print("jj=%, skip %s\n",rSimpleOrdStr(R->order[jj]));
1878           jj--;
1879         }
1880         if (jj<0) R->block0[j]=1;
1881         else       R->block0[j]=R->block1[jj]+1;
1882      }
1883      intvec *iv;
1884      if (vv->m[1].Typ()==INT_CMD)
1885        iv=new intvec((int)(long)vv->m[1].Data(),(int)(long)vv->m[1].Data());
1886      else
1887        iv=ivCopy((intvec*)vv->m[1].Data()); //assume INTVEC
1888      R->block1[j]=si_max(R->block0[j],R->block0[j]+iv->length()-1);
1889      //Print("block %d from %d to %d\n",j,R->block0[j], R->block1[j]);
1890      int i;
1891      switch (R->order[j])
1892      {
1893         case ringorder_ws:
1894         case ringorder_Ws:
1895            R->OrdSgn=-1;
1896         case ringorder_aa:
1897         case ringorder_a:
1898         case ringorder_wp:
1899         case ringorder_Wp:
1900           R->wvhdl[j] =( int *)omAlloc((iv->length())*sizeof(int));
1901           for (i=0; i<iv->length();i++)
1902           {
1903             R->wvhdl[j][i]=(*iv)[i];
1904           }
1905           break;
1906         case ringorder_M:
1907           R->wvhdl[j] =( int *)omAlloc((iv->length())*sizeof(int));
1908           for (i=0; i<iv->length();i++) R->wvhdl[j][i]=(*iv)[i];
1909           R->block1[j]=si_max(R->block0[j],R->block0[j]+(int)sqrt((double)(iv->length()-1)));
1910           break;
1911         case ringorder_ls:
1912         case ringorder_ds:
1913         case ringorder_Ds:
1914         case ringorder_rs:
1915           R->OrdSgn=-1;
1916         case ringorder_lp:
1917         case ringorder_dp:
1918         case ringorder_Dp:
1919         case ringorder_rp:
1920           break;
1921         case ringorder_S:
1922           break;
1923         case ringorder_c:
1924         case ringorder_C:
1925           R->block1[j]=R->block0[j]=0;
1926           break;
1927         case 0:
1928         case ringorder_unspec:
1929           break;
1930      }
1931    }
1932    // sanity check
1933    j=n-2;
1934    if ((R->order[j]==ringorder_c)
1935    || (R->order[j]==ringorder_C)
1936    || (R->order[j]==ringorder_unspec)) j--;
1937    if (R->block1[j] != R->N)
1938    {
1939      if (((R->order[j]==ringorder_dp) ||
1940           (R->order[j]==ringorder_ds) ||
1941           (R->order[j]==ringorder_Dp) ||
1942           (R->order[j]==ringorder_Ds) ||
1943           (R->order[j]==ringorder_rp) ||
1944           (R->order[j]==ringorder_rs) ||
1945           (R->order[j]==ringorder_lp) ||
1946           (R->order[j]==ringorder_ls))
1947          &&
1948            R->block0[j] <= R->N)
1949      {
1950        R->block1[j] = R->N;
1951      }
1952      else
1953      {
1954        Werror("ordering incomplete: size (%d) should be %d",R->block1[j],R->N);
1955        goto rCompose_err;
1956      }
1957    }
1958  }
1959  else
1960  {
1961    WerrorS("ordering must be given as `list`");
1962    goto rCompose_err;
1963  }
1964  // ------------------------------------------------------------------
1965  // 0: char:
1966  if (L->m[0].Typ()==INT_CMD)
1967  {
1968    R->ch=(int)(long)L->m[0].Data();
1969    if (R->ch!=-1)
1970    {
1971      int l;
1972      if (((R->ch!=0) && (R->ch<2))
1973      #ifndef NV_OPS
1974      || (R->ch > 32003)
1975      #endif
1976      || ((l=IsPrime(R->ch))!=R->ch)
1977      )
1978      {
1979        Warn("%d is invalid characteristic of ground field. %d is used.", R->ch,l);
1980        R->ch=l;
1981      }
1982    }
1983  }
1984  else if (L->m[0].Typ()==LIST_CMD)
1985  {
1986    lists LL=(lists)L->m[0].Data();
1987    if (LL->nr<3)
1988      rComposeC(LL,R); /* R, long_R, long_C */
1989    else
1990    {
1991      R->algring=rCompose((lists)L->m[0].Data());
1992      if (R->algring==NULL)
1993      {
1994        WerrorS("could not create rational function coefficient field");
1995        goto rCompose_err;
1996      }
1997      if (R->algring->ch>0)
1998         R->ch= -R->algring->ch;
1999      else
2000         R->ch=1;
2001      R->P=R->algring->N;
2002      R->parameter=(char**)omAlloc0(R->P*sizeof(char_ptr));
2003      int i;
2004      for(i=R->P-1;i>=0;i--)
2005        R->parameter[i]=omStrDup(R->algring->names[i]);
2006      if (R->algring->qideal!=NULL)
2007      {
2008        if (IDELEMS(R->algring->qideal)==1)
2009        {
2010          R->minpoly=naInit(1);
2011          lnumber n=(lnumber)R->minpoly;
2012          n->z=R->algring->qideal->m[0];
2013          R->algring->qideal->m[0]=NULL;
2014          idDelete(&(R->algring->qideal));
2015        }
2016        else
2017        {
2018          WerrorS("not implemented yet.");
2019        }
2020      }
2021    }
2022  }
2023  else
2024  {
2025    WerrorS("coefficient field must be described by `int` or `list`");
2026    goto rCompose_err;
2027  }
2028  // ------------------------ Q-IDEAL ------------------------
2029  rComplete(R);
2030
2031  if (L->m[3].Typ()==IDEAL_CMD)
2032  {
2033    ideal q=(ideal)L->m[3].Data();
2034    if (q->m[0]!=NULL)
2035    {
2036      if (R->ch!=currRing->ch)
2037      {
2038      #if 0
2039            WerrorS("coefficient fields must be equal if q-ideal !=0");
2040            goto rCompose_err;
2041      #else
2042        ring orig_ring=currRing;
2043        rChangeCurrRing(R);
2044        int *perm=NULL;
2045        int *par_perm=NULL;
2046        int par_perm_size=0;
2047        nMapFunc nMap;
2048        BOOLEAN bo;
2049
2050        if ((nMap=nSetMap(orig_ring))==NULL)
2051        {
2052          if (rEqual(orig_ring,currRing))
2053          {
2054            nMap=nCopy;
2055          }
2056          else
2057          // Allow imap/fetch to be make an exception only for:
2058          if ( (rField_is_Q_a(orig_ring) &&  // Q(a..) -> Q(a..) || Q || Zp || Zp(a)
2059            (rField_is_Q() || rField_is_Q_a() ||
2060             (rField_is_Zp() || rField_is_Zp_a())))
2061           ||
2062           (rField_is_Zp_a(orig_ring) &&  // Zp(a..) -> Zp(a..) || Zp
2063            (rField_is_Zp(currRing, rInternalChar(orig_ring)) ||
2064             rField_is_Zp_a(currRing, rInternalChar(orig_ring)))) )
2065          {
2066            par_perm_size=rPar(orig_ring);
2067            BITSET save_test=test;
2068            naSetChar(rInternalChar(orig_ring),orig_ring);
2069            nSetChar(currRing);
2070            test=save_test;
2071          }
2072          else
2073          {
2074            WerrorS("coefficient fields must be equal if q-ideal !=0");
2075            goto rCompose_err;
2076          }
2077        }
2078        perm=(int *)omAlloc0((orig_ring->N+1)*sizeof(int));
2079        if (par_perm_size!=0)
2080          par_perm=(int *)omAlloc0(par_perm_size*sizeof(int));
2081        int i;
2082        #if 0
2083        // use imap:
2084        maFindPerm(orig_ring->names,orig_ring->N,orig_ring->parameter,orig_ring->P,
2085          currRing->names,currRing->N,currRing->parameter, currRing->P,
2086          perm,par_perm, currRing->ch);
2087        #else
2088        // use fetch
2089        if ((rPar(orig_ring)>0) && (rPar(currRing)==0))
2090        {
2091          for(i=si_min(rPar(orig_ring),rVar(currRing))-1;i>=0;i--) par_perm[i]=i+1;
2092        }
2093        else if (par_perm_size!=0)
2094          for(i=si_min(rPar(orig_ring),rPar(currRing))-1;i>=0;i--) par_perm[i]=-(i+1);
2095        for(i=si_min(orig_ring->N,pVariables);i>0;i--) perm[i]=i;
2096        #endif
2097        ideal dest_id=idInit(IDELEMS(q),1);
2098        for(i=IDELEMS(q)-1; i>=0; i--)
2099        {
2100          dest_id->m[i]=pPermPoly(q->m[i],perm,orig_ring,nMap,
2101                                  par_perm,par_perm_size);
2102          //  PrintS("map:");pWrite(dest_id->m[i]);PrintLn();
2103          pTest(dest_id->m[i]);
2104        }
2105        R->qideal=dest_id;
2106        if (perm!=NULL)
2107          omFreeSize((ADDRESS)perm,(orig_ring->N+1)*sizeof(int));
2108        if (par_perm!=NULL)
2109          omFreeSize((ADDRESS)par_perm,par_perm_size*sizeof(int));
2110        rChangeCurrRing(orig_ring);
2111      #endif
2112      }
2113      else
2114        R->qideal=idrCopyR(q,currRing,R);
2115    }
2116  }
2117  else
2118  {
2119    WerrorS("q-ideal must be given as `ideal`");
2120    goto rCompose_err;
2121  }
2122
2123
2124  // ---------------------------------------------------------------
2125  #ifdef HAVE_PLURAL
2126  if (L->nr==5)
2127  {
2128    if (nc_CallPlural((matrix)L->m[4].Data(),(matrix)L->m[5].Data(),
2129        NULL,NULL,R))
2130      goto rCompose_err;
2131  }
2132  #endif
2133  return R;
2134
2135rCompose_err:
2136  if (R->N>0)
2137  {
2138    int i;
2139    if (R->names!=NULL)
2140    {
2141      i=R->N-1;
2142      while (i>=0) { if (R->names[i]!=NULL) omFree(R->names[i]); i--; }
2143      omFree(R->names);
2144    }
2145  }
2146  if (R->order!=NULL) omFree(R->order);
2147  if (R->block0!=NULL) omFree(R->block0);
2148  if (R->block1!=NULL) omFree(R->block1);
2149  if (R->wvhdl!=NULL) omFree(R->wvhdl);
2150  omFree(R);
2151  return NULL;
2152}
2153
2154// from matpol.cc
2155
2156/*2
2157* compute the jacobi matrix of an ideal
2158*/
2159BOOLEAN mpJacobi(leftv res,leftv a)
2160{
2161  int     i,j;
2162  matrix result;
2163  ideal id=(ideal)a->Data();
2164
2165  result =mpNew(IDELEMS(id),pVariables);
2166  for (i=1; i<=IDELEMS(id); i++)
2167  {
2168    for (j=1; j<=pVariables; j++)
2169    {
2170      MATELEM(result,i,j) = pDiff(id->m[i-1],j);
2171    }
2172  }
2173  res->data=(char *)result;
2174  return FALSE;
2175}
2176
2177/*2
2178* returns the Koszul-matrix of degree d of a vectorspace with dimension n
2179* uses the first n entrees of id, if id <> NULL
2180*/
2181BOOLEAN mpKoszul(leftv res,leftv c/*ip*/, leftv b/*in*/, leftv id)
2182{
2183  int n=(int)(long)b->Data();
2184  int d=(int)(long)c->Data();
2185  int     k,l,sign,row,col;
2186  matrix  result;
2187  ideal temp;
2188  BOOLEAN bo;
2189  poly    p;
2190
2191  if ((d>n) || (d<1) || (n<1))
2192  {
2193    res->data=(char *)mpNew(1,1);
2194    return FALSE;
2195  }
2196  int *choise = (int*)omAlloc(d*sizeof(int));
2197  if (id==NULL)
2198    temp=idMaxIdeal(1);
2199  else
2200    temp=(ideal)id->Data();
2201
2202  k = binom(n,d);
2203  l = k*d;
2204  l /= n-d+1;
2205  result =mpNew(l,k);
2206  col = 1;
2207  idInitChoise(d,1,n,&bo,choise);
2208  while (!bo)
2209  {
2210    sign = 1;
2211    for (l=1;l<=d;l++)
2212    {
2213      if (choise[l-1]<=IDELEMS(temp))
2214      {
2215        p = pCopy(temp->m[choise[l-1]-1]);
2216        if (sign == -1) p = pNeg(p);
2217        sign *= -1;
2218        row = idGetNumberOfChoise(l-1,d,1,n,choise);
2219        MATELEM(result,row,col) = p;
2220      }
2221    }
2222    col++;
2223    idGetNextChoise(d,n,&bo,choise);
2224  }
2225  if (id==NULL) idDelete(&temp);
2226
2227  res->data=(char *)result;
2228  return FALSE;
2229}
2230
2231// from syz1.cc
2232/*2
2233* read out the Betti numbers from resolution
2234* (interpreter interface)
2235*/
2236BOOLEAN syBetti2(leftv res, leftv u, leftv w)
2237{
2238  syStrategy syzstr=(syStrategy)u->Data();
2239  BOOLEAN minim=(int)(long)w->Data();
2240  int row_shift=0;
2241  int add_row_shift=0;
2242  intvec *weights=NULL;
2243  intvec *ww=(intvec *)atGet(u,"isHomog",INTVEC_CMD);
2244  if (ww!=NULL)
2245  {
2246     weights=ivCopy(ww);
2247     add_row_shift = ww->min_in();
2248     (*weights) -= add_row_shift;
2249  }
2250  res->data=(void *)syBettiOfComputation(syzstr,minim,&row_shift,weights);
2251  //row_shift += add_row_shift;
2252  //Print("row_shift=%d, add_row_shift=%d\n",row_shift,add_row_shift);
2253  atSet(res,omStrDup("rowShift"),(void*)add_row_shift,INT_CMD);
2254  return FALSE;
2255}
2256BOOLEAN syBetti1(leftv res, leftv u)
2257{
2258  sleftv tmp;
2259  memset(&tmp,0,sizeof(tmp));
2260  tmp.rtyp=INT_CMD;
2261  tmp.data=(void *)1;
2262  return syBetti2(res,u,&tmp);
2263}
2264
2265/*3
2266* converts a resolution into a list of modules
2267*/
2268lists syConvRes(syStrategy syzstr,BOOLEAN toDel,int add_row_shift)
2269{
2270  if ((syzstr->fullres==NULL) && (syzstr->minres==NULL))
2271  {
2272    if (syzstr->hilb_coeffs==NULL)
2273    {
2274      syzstr->fullres = syReorder(syzstr->res,syzstr->length,syzstr);
2275    }
2276    else
2277    {
2278      syzstr->minres = syReorder(syzstr->orderedRes,syzstr->length,syzstr);
2279      syKillEmptyEntres(syzstr->minres,syzstr->length);
2280    }
2281  }
2282  resolvente tr;
2283  int typ0=IDEAL_CMD;
2284  if (syzstr->minres!=NULL)
2285    tr = syzstr->minres;
2286  else
2287    tr = syzstr->fullres;
2288  resolvente trueres=NULL;
2289  intvec ** w=NULL;
2290  if (syzstr->length>0)
2291  {
2292    trueres=(resolvente)omAlloc0((syzstr->length)*sizeof(ideal));
2293    for (int i=(syzstr->length)-1;i>=0;i--)
2294    {
2295      if (tr[i]!=NULL)
2296      {
2297        trueres[i] = idCopy(tr[i]);
2298      }
2299    }
2300    if (idRankFreeModule(trueres[0]) > 0)
2301      typ0 = MODUL_CMD;
2302    if (syzstr->weights!=NULL)
2303    {
2304      w = (intvec**)omAlloc0((syzstr->length)*sizeof(intvec*));
2305      for (int i=(syzstr->length)-1;i>=0;i--)
2306      {
2307        if (syzstr->weights[i]!=NULL) w[i] = ivCopy(syzstr->weights[i]);
2308      }
2309    }
2310  }
2311  lists li = liMakeResolv(trueres,syzstr->length,syzstr->list_length,typ0,
2312                          w,add_row_shift);
2313  if (w != NULL) omFreeSize(w, (syzstr->length)*sizeof(intvec*));
2314  if (toDel) syKillComputation(syzstr);
2315  return li;
2316}
2317
2318/*3
2319* converts a list of modules into a resolution
2320*/
2321syStrategy syConvList(lists li,BOOLEAN toDel)
2322{
2323  int typ0;
2324  syStrategy result=(syStrategy)omAlloc0(sizeof(ssyStrategy));
2325
2326  resolvente fr = liFindRes(li,&(result->length),&typ0,&(result->weights));
2327  if (fr != NULL)
2328  {
2329
2330    result->fullres = (resolvente)omAlloc0((result->length+1)*sizeof(ideal));
2331    for (int i=result->length-1;i>=0;i--)
2332    {
2333      if (fr[i]!=NULL)
2334        result->fullres[i] = idCopy(fr[i]);
2335    }
2336    result->list_length=result->length;
2337    omFreeSize((ADDRESS)fr,(result->length)*sizeof(ideal));
2338  }
2339  else
2340  {
2341    omFreeSize(result, sizeof(ssyStrategy));
2342    result = NULL;
2343  }
2344  if (toDel) li->Clean();
2345  return result;
2346}
2347
2348/*3
2349* converts a list of modules into a minimal resolution
2350*/
2351syStrategy syForceMin(lists li)
2352{
2353  int typ0;
2354  syStrategy result=(syStrategy)omAlloc0(sizeof(ssyStrategy));
2355
2356  resolvente fr = liFindRes(li,&(result->length),&typ0);
2357  result->minres = (resolvente)omAlloc0((result->length+1)*sizeof(ideal));
2358  for (int i=result->length-1;i>=0;i--)
2359  {
2360    if (fr[i]!=NULL)
2361      result->minres[i] = idCopy(fr[i]);
2362  }
2363  omFreeSize((ADDRESS)fr,(result->length)*sizeof(ideal));
2364  return result;
2365}
2366// from weight.cc
2367BOOLEAN kWeight(leftv res,leftv id)
2368{
2369  ideal F=(ideal)id->Data();
2370  intvec * iv = new intvec(pVariables);
2371  polyset s;
2372  int  sl, n, i;
2373  int  *x;
2374
2375  res->data=(char *)iv;
2376  s = F->m;
2377  sl = IDELEMS(F) - 1;
2378  n = pVariables;
2379  double wNsqr = (double)2.0 / (double)n;
2380  wFunctional = wFunctionalBuch;
2381  x = (int * )omAlloc(2 * (n + 1) * sizeof(int));
2382  wCall(s, sl, x, wNsqr);
2383  for (i = n; i!=0; i--)
2384    (*iv)[i-1] = x[i + n + 1];
2385  omFreeSize((ADDRESS)x, 2 * (n + 1) * sizeof(int));
2386  return FALSE;
2387}
2388
2389BOOLEAN kQHWeight(leftv res,leftv v)
2390{
2391  res->data=(char *)idQHomWeight((ideal)v->Data());
2392  if (res->data==NULL)
2393    res->data=(char *)new intvec(pVariables);
2394  return FALSE;
2395}
2396/*==============================================================*/
2397// from clapsing.cc
2398#if 0
2399BOOLEAN jjIS_SQR_FREE(leftv res, leftv u)
2400{
2401  BOOLEAN b=singclap_factorize((poly)(u->CopyD()), &v, 0);
2402  res->data=(void *)b;
2403}
2404#endif
2405
2406BOOLEAN jjRESULTANT(leftv res, leftv u, leftv v, leftv w)
2407{
2408  res->data=singclap_resultant((poly)u->Data(),(poly)v->Data(), (poly)w->Data());
2409  return errorreported;
2410}
2411BOOLEAN jjCHARSERIES(leftv res, leftv u)
2412{
2413  res->data=singclap_irrCharSeries((ideal)u->Data());
2414  return (res->data==NULL);
2415}
2416
2417// from semic.cc
2418#ifdef HAVE_SPECTRUM
2419
2420// ----------------------------------------------------------------------------
2421//  Initialize a  spectrum  deep from another  spectrum
2422// ----------------------------------------------------------------------------
2423
2424void spectrum::copy_deep( const spectrum &spec )
2425{
2426    mu = spec.mu;
2427    pg = spec.pg;
2428    n  = spec.n;
2429
2430    copy_new( n );
2431
2432    for( int i=0; i<n; i++ )
2433    {
2434        s[i] = spec.s[i];
2435        w[i] = spec.w[i];
2436    }
2437}
2438
2439// ----------------------------------------------------------------------------
2440//  Initialize a  spectrum  deep from a  singular  lists
2441// ----------------------------------------------------------------------------
2442
2443void spectrum::copy_deep( lists l )
2444{
2445    mu = (int)(long)(l->m[0].Data( ));
2446    pg = (int)(long)(l->m[1].Data( ));
2447    n  = (int)(long)(l->m[2].Data( ));
2448
2449    copy_new( n );
2450
2451    intvec  *num = (intvec*)l->m[3].Data( );
2452    intvec  *den = (intvec*)l->m[4].Data( );
2453    intvec  *mul = (intvec*)l->m[5].Data( );
2454
2455    for( int i=0; i<n; i++ )
2456    {
2457        s[i] = (Rational)((*num)[i])/(Rational)((*den)[i]);
2458        w[i] = (*mul)[i];
2459    }
2460}
2461
2462// ----------------------------------------------------------------------------
2463//  singular lists  constructor for  spectrum
2464// ----------------------------------------------------------------------------
2465
2466spectrum::spectrum( lists l )
2467{
2468    copy_deep( l );
2469}
2470
2471// ----------------------------------------------------------------------------
2472//  generate a Singular  lists  from a spectrum
2473// ----------------------------------------------------------------------------
2474
2475lists   spectrum::thelist( void )
2476{
2477    lists   L  = (lists)omAllocBin( slists_bin);
2478
2479    L->Init( 6 );
2480
2481    intvec            *num  = new intvec( n );
2482    intvec            *den  = new intvec( n );
2483    intvec            *mult = new intvec( n );
2484
2485    for( int i=0; i<n; i++ )
2486    {
2487        (*num) [i] = s[i].get_num_si( );
2488        (*den) [i] = s[i].get_den_si( );
2489        (*mult)[i] = w[i];
2490    }
2491
2492    L->m[0].rtyp = INT_CMD;    //  milnor number
2493    L->m[1].rtyp = INT_CMD;    //  geometrical genus
2494    L->m[2].rtyp = INT_CMD;    //  # of spectrum numbers
2495    L->m[3].rtyp = INTVEC_CMD; //  numerators
2496    L->m[4].rtyp = INTVEC_CMD; //  denomiantors
2497    L->m[5].rtyp = INTVEC_CMD; //  multiplicities
2498
2499    L->m[0].data = (void*)mu;
2500    L->m[1].data = (void*)pg;
2501    L->m[2].data = (void*)n;
2502    L->m[3].data = (void*)num;
2503    L->m[4].data = (void*)den;
2504    L->m[5].data = (void*)mult;
2505
2506    return  L;
2507}
2508// from spectrum.cc
2509// ----------------------------------------------------------------------------
2510//  print out an error message for a spectrum list
2511// ----------------------------------------------------------------------------
2512
2513void    list_error( semicState state )
2514{
2515    switch( state )
2516    {
2517        case semicListTooShort:
2518            WerrorS( "the list is too short" );
2519            break;
2520        case semicListTooLong:
2521            WerrorS( "the list is too long" );
2522            break;
2523
2524        case semicListFirstElementWrongType:
2525            WerrorS( "first element of the list should be int" );
2526            break;
2527        case semicListSecondElementWrongType:
2528            WerrorS( "second element of the list should be int" );
2529            break;
2530        case semicListThirdElementWrongType:
2531            WerrorS( "third element of the list should be int" );
2532            break;
2533        case semicListFourthElementWrongType:
2534            WerrorS( "fourth element of the list should be intvec" );
2535            break;
2536        case semicListFifthElementWrongType:
2537            WerrorS( "fifth element of the list should be intvec" );
2538            break;
2539        case semicListSixthElementWrongType:
2540            WerrorS( "sixth element of the list should be intvec" );
2541            break;
2542
2543        case semicListNNegative:
2544            WerrorS( "first element of the list should be positive" );
2545            break;
2546        case semicListWrongNumberOfNumerators:
2547            WerrorS( "wrong number of numerators" );
2548            break;
2549        case semicListWrongNumberOfDenominators:
2550            WerrorS( "wrong number of denominators" );
2551            break;
2552        case semicListWrongNumberOfMultiplicities:
2553            WerrorS( "wrong number of multiplicities" );
2554            break;
2555
2556        case semicListMuNegative:
2557            WerrorS( "the Milnor number should be positive" );
2558            break;
2559        case semicListPgNegative:
2560            WerrorS( "the geometrical genus should be nonnegative" );
2561            break;
2562        case semicListNumNegative:
2563            WerrorS( "all numerators should be positive" );
2564            break;
2565        case semicListDenNegative:
2566            WerrorS( "all denominators should be positive" );
2567            break;
2568        case semicListMulNegative:
2569            WerrorS( "all multiplicities should be positive" );
2570            break;
2571
2572        case semicListNotSymmetric:
2573            WerrorS( "it is not symmetric" );
2574            break;
2575        case semicListNotMonotonous:
2576            WerrorS( "it is not monotonous" );
2577            break;
2578
2579        case semicListMilnorWrong:
2580            WerrorS( "the Milnor number is wrong" );
2581            break;
2582        case semicListPGWrong:
2583            WerrorS( "the geometrical genus is wrong" );
2584            break;
2585
2586        default:
2587            WerrorS( "unspecific error" );
2588            break;
2589    }
2590}
2591// ----------------------------------------------------------------------------
2592//  this is the main spectrum computation function
2593// ----------------------------------------------------------------------------
2594
2595spectrumState   spectrumCompute( poly h,lists *L,int fast )
2596{
2597  int i,j;
2598
2599  #ifdef SPECTRUM_DEBUG
2600  #ifdef SPECTRUM_PRINT
2601  #ifdef SPECTRUM_IOSTREAM
2602    cout << "spectrumCompute\n";
2603    if( fast==0 ) cout << "    no optimization" << endl;
2604    if( fast==1 ) cout << "    weight optimization" << endl;
2605    if( fast==2 ) cout << "    symmetry optimization" << endl;
2606  #else
2607    fprintf( stdout,"spectrumCompute\n" );
2608    if( fast==0 ) fprintf( stdout,"    no optimization\n" );
2609    if( fast==1 ) fprintf( stdout,"    weight optimization\n" );
2610    if( fast==2 ) fprintf( stdout,"    symmetry optimization\n" );
2611  #endif
2612  #endif
2613  #endif
2614
2615  // ----------------------
2616  //  check if  h  is zero
2617  // ----------------------
2618
2619  if( h==(poly)NULL )
2620  {
2621    return  spectrumZero;
2622  }
2623
2624  // ----------------------------------
2625  //  check if  h  has a constant term
2626  // ----------------------------------
2627
2628  if( hasConstTerm( h ) )
2629  {
2630    return  spectrumBadPoly;
2631  }
2632
2633  // --------------------------------
2634  //  check if  h  has a linear term
2635  // --------------------------------
2636
2637  if( hasLinearTerm( h ) )
2638  {
2639    *L = (lists)omAllocBin( slists_bin);
2640    (*L)->Init( 1 );
2641    (*L)->m[0].rtyp = INT_CMD;    //  milnor number
2642    /* (*L)->m[0].data = (void*)0;a  -- done by Init */
2643
2644    return  spectrumNoSingularity;
2645  }
2646
2647  // ----------------------------------
2648  //  compute the jacobi ideal of  (h)
2649  // ----------------------------------
2650
2651  ideal J = NULL;
2652  J = idInit( pVariables,1 );
2653
2654  #ifdef SPECTRUM_DEBUG
2655  #ifdef SPECTRUM_PRINT
2656  #ifdef SPECTRUM_IOSTREAM
2657    cout << "\n   computing the Jacobi ideal...\n";
2658  #else
2659    fprintf( stdout,"\n   computing the Jacobi ideal...\n" );
2660  #endif
2661  #endif
2662  #endif
2663
2664  for( i=0; i<pVariables; i++ )
2665  {
2666    J->m[i] = pDiff( h,i+1); //j );
2667
2668    #ifdef SPECTRUM_DEBUG
2669    #ifdef SPECTRUM_PRINT
2670    #ifdef SPECTRUM_IOSTREAM
2671      cout << "        ";
2672    #else
2673      fprintf( stdout,"        " );
2674    #endif
2675      pWrite( J->m[i] );
2676    #endif
2677    #endif
2678  }
2679
2680  // --------------------------------------------
2681  //  compute a standard basis  stdJ  of  jac(h)
2682  // --------------------------------------------
2683
2684  #ifdef SPECTRUM_DEBUG
2685  #ifdef SPECTRUM_PRINT
2686  #ifdef SPECTRUM_IOSTREAM
2687    cout << endl;
2688    cout << "    computing a standard basis..." << endl;
2689  #else
2690    fprintf( stdout,"\n" );
2691    fprintf( stdout,"    computing a standard basis...\n" );
2692  #endif
2693  #endif
2694  #endif
2695
2696  ideal stdJ = kStd(J,currQuotient,isNotHomog,NULL);
2697  idSkipZeroes( stdJ );
2698
2699  #ifdef SPECTRUM_DEBUG
2700  #ifdef SPECTRUM_PRINT
2701    for( i=0; i<IDELEMS(stdJ); i++ )
2702    {
2703      #ifdef SPECTRUM_IOSTREAM
2704        cout << "        ";
2705      #else
2706        fprintf( stdout,"        " );
2707      #endif
2708
2709      pWrite( stdJ->m[i] );
2710    }
2711  #endif
2712  #endif
2713
2714  idDelete( &J );
2715
2716  // ------------------------------------------
2717  //  check if the  h  has a singularity
2718  // ------------------------------------------
2719
2720  if( hasOne( stdJ ) )
2721  {
2722    // -------------------------------
2723    //  h is smooth in the origin
2724    //  return only the Milnor number
2725    // -------------------------------
2726
2727    *L = (lists)omAllocBin( slists_bin);
2728    (*L)->Init( 1 );
2729    (*L)->m[0].rtyp = INT_CMD;    //  milnor number
2730    /* (*L)->m[0].data = (void*)0;a  -- done by Init */
2731
2732    return  spectrumNoSingularity;
2733  }
2734
2735  // ------------------------------------------
2736  //  check if the singularity  h  is isolated
2737  // ------------------------------------------
2738
2739  for( i=pVariables; i>0; i-- )
2740  {
2741    if( hasAxis( stdJ,i )==FALSE )
2742    {
2743      return  spectrumNotIsolated;
2744    }
2745  }
2746
2747  // ------------------------------------------
2748  //  compute the highest corner  hc  of  stdJ
2749  // ------------------------------------------
2750
2751  #ifdef SPECTRUM_DEBUG
2752  #ifdef SPECTRUM_PRINT
2753  #ifdef SPECTRUM_IOSTREAM
2754    cout << "\n    computing the highest corner...\n";
2755  #else
2756    fprintf( stdout,"\n    computing the highest corner...\n" );
2757  #endif
2758  #endif
2759  #endif
2760
2761  poly hc = (poly)NULL;
2762
2763  scComputeHC( stdJ,currQuotient, 0,hc );
2764
2765  if( hc!=(poly)NULL )
2766  {
2767    pGetCoeff(hc) = nInit(1);
2768
2769    for( i=pVariables; i>0; i-- )
2770    {
2771      if( pGetExp( hc,i )>0 ) pDecrExp( hc,i );
2772    }
2773    pSetm( hc );
2774  }
2775  else
2776  {
2777    return  spectrumNoHC;
2778  }
2779
2780  #ifdef SPECTRUM_DEBUG
2781  #ifdef SPECTRUM_PRINT
2782  #ifdef SPECTRUM_IOSTREAM
2783    cout << "       ";
2784  #else
2785    fprintf( stdout,"       " );
2786  #endif
2787    pWrite( hc );
2788  #endif
2789  #endif
2790
2791  // ----------------------------------------
2792  //  compute the Newton polygon  nph  of  h
2793  // ----------------------------------------
2794
2795  #ifdef SPECTRUM_DEBUG
2796  #ifdef SPECTRUM_PRINT
2797  #ifdef SPECTRUM_IOSTREAM
2798    cout << "\n    computing the newton polygon...\n";
2799  #else
2800    fprintf( stdout,"\n    computing the newton polygon...\n" );
2801  #endif
2802  #endif
2803  #endif
2804
2805  newtonPolygon nph( h );
2806
2807  #ifdef SPECTRUM_DEBUG
2808  #ifdef SPECTRUM_PRINT
2809    cout << nph;
2810  #endif
2811  #endif
2812
2813  // -----------------------------------------------
2814  //  compute the weight corner  wc  of  (stdj,nph)
2815  // -----------------------------------------------
2816
2817  #ifdef SPECTRUM_DEBUG
2818  #ifdef SPECTRUM_PRINT
2819  #ifdef SPECTRUM_IOSTREAM
2820    cout << "\n    computing the weight corner...\n";
2821  #else
2822    fprintf( stdout,"\n    computing the weight corner...\n" );
2823  #endif
2824  #endif
2825  #endif
2826
2827  poly    wc = ( fast==0 ? pCopy( hc ) :
2828               ( fast==1 ? computeWC( nph,(Rational)pVariables ) :
2829              /* fast==2 */computeWC( nph,((Rational)pVariables)/(Rational)2 ) ) );
2830
2831  #ifdef SPECTRUM_DEBUG
2832  #ifdef SPECTRUM_PRINT
2833  #ifdef SPECTRUM_IOSTREAM
2834    cout << "        ";
2835  #else
2836    fprintf( stdout,"        " );
2837  #endif
2838    pWrite( wc );
2839  #endif
2840  #endif
2841
2842  // -------------
2843  //  compute  NF
2844  // -------------
2845
2846  #ifdef SPECTRUM_DEBUG
2847  #ifdef SPECTRUM_PRINT
2848  #ifdef SPECTRUM_IOSTREAM
2849    cout << "\n    computing NF...\n" << endl;
2850  #else
2851    fprintf( stdout,"\n    computing NF...\n" );
2852  #endif
2853  #endif
2854  #endif
2855
2856  spectrumPolyList NF( &nph );
2857
2858  computeNF( stdJ,hc,wc,&NF );
2859
2860  #ifdef SPECTRUM_DEBUG
2861  #ifdef SPECTRUM_PRINT
2862    cout << NF;
2863  #ifdef SPECTRUM_IOSTREAM
2864    cout << endl;
2865  #else
2866    fprintf( stdout,"\n" );
2867  #endif
2868  #endif
2869  #endif
2870
2871  // ----------------------------
2872  //  compute the spectrum of  h
2873  // ----------------------------
2874
2875  return  NF.spectrum( L,fast );
2876}
2877
2878// ----------------------------------------------------------------------------
2879//  this procedure is called from the interpreter
2880// ----------------------------------------------------------------------------
2881//  first  = polynomial
2882//  result = list of spectrum numbers
2883// ----------------------------------------------------------------------------
2884
2885BOOLEAN spectrumProc( leftv result,leftv first )
2886{
2887  spectrumState state = spectrumOK;
2888
2889  // -------------------
2890  //  check consistency
2891  // -------------------
2892
2893  //  check for a local ring
2894
2895  if( !ringIsLocal( ) )
2896  {
2897    WerrorS( "only works for local orderings" );
2898    state = spectrumWrongRing;
2899  }
2900
2901  //  no quotient rings are allowed
2902
2903  else if( currRing->qideal != NULL )
2904  {
2905    WerrorS( "does not work in quotient rings" );
2906    state = spectrumWrongRing;
2907  }
2908  else
2909  {
2910    lists   L    = (lists)NULL;
2911    int     flag = 1; // weight corner optimization is safe
2912
2913    state = spectrumCompute( (poly)first->Data( ),&L,flag );
2914
2915    if( state==spectrumOK )
2916    {
2917      result->rtyp = LIST_CMD;
2918      result->data = (char*)L;
2919    }
2920    else
2921    {
2922      spectrumPrintError(state);
2923    }
2924  }
2925
2926  return  (state!=spectrumOK);
2927}
2928
2929// ----------------------------------------------------------------------------
2930//  this procedure is called from the interpreter
2931// ----------------------------------------------------------------------------
2932//  first  = polynomial
2933//  result = list of spectrum numbers
2934// ----------------------------------------------------------------------------
2935
2936BOOLEAN spectrumfProc( leftv result,leftv first )
2937{
2938  spectrumState state = spectrumOK;
2939
2940  // -------------------
2941  //  check consistency
2942  // -------------------
2943
2944  //  check for a local polynomial ring
2945
2946  if( currRing->OrdSgn != -1 )
2947  // ?? HS: the test above is also true for k[x][[y]], k[[x]][y]
2948  // or should we use:
2949  //if( !ringIsLocal( ) )
2950  {
2951    WerrorS( "only works for local orderings" );
2952    state = spectrumWrongRing;
2953  }
2954  else if( currRing->qideal != NULL )
2955  {
2956    WerrorS( "does not work in quotient rings" );
2957    state = spectrumWrongRing;
2958  }
2959  else
2960  {
2961    lists   L    = (lists)NULL;
2962    int     flag = 2; // symmetric optimization
2963
2964    state = spectrumCompute( (poly)first->Data( ),&L,flag );
2965
2966    if( state==spectrumOK )
2967    {
2968      result->rtyp = LIST_CMD;
2969      result->data = (char*)L;
2970    }
2971    else
2972    {
2973      spectrumPrintError(state);
2974    }
2975  }
2976
2977  return  (state!=spectrumOK);
2978}
2979
2980// ----------------------------------------------------------------------------
2981//  check if a list is a spectrum
2982//  check for:
2983//      list has 6 elements
2984//      1st element is int (mu=Milnor number)
2985//      2nd element is int (pg=geometrical genus)
2986//      3rd element is int (n =number of different spectrum numbers)
2987//      4th element is intvec (num=numerators)
2988//      5th element is intvec (den=denomiantors)
2989//      6th element is intvec (mul=multiplicities)
2990//      exactly n numerators
2991//      exactly n denominators
2992//      exactly n multiplicities
2993//      mu>0
2994//      pg>=0
2995//      n>0
2996//      num>0
2997//      den>0
2998//      mul>0
2999//      symmetriy with respect to numberofvariables/2
3000//      monotony
3001//      mu = sum of all multiplicities
3002//      pg = sum of all multiplicities where num/den<=1
3003// ----------------------------------------------------------------------------
3004
3005semicState  list_is_spectrum( lists l )
3006{
3007    // -------------------
3008    //  check list length
3009    // -------------------
3010
3011    if( l->nr < 5 )
3012    {
3013        return  semicListTooShort;
3014    }
3015    else if( l->nr > 5 )
3016    {
3017        return  semicListTooLong;
3018    }
3019
3020    // -------------
3021    //  check types
3022    // -------------
3023
3024    if( l->m[0].rtyp != INT_CMD )
3025    {
3026        return  semicListFirstElementWrongType;
3027    }
3028    else if( l->m[1].rtyp != INT_CMD )
3029    {
3030        return  semicListSecondElementWrongType;
3031    }
3032    else if( l->m[2].rtyp != INT_CMD )
3033    {
3034        return  semicListThirdElementWrongType;
3035    }
3036    else if( l->m[3].rtyp != INTVEC_CMD )
3037    {
3038        return  semicListFourthElementWrongType;
3039    }
3040    else if( l->m[4].rtyp != INTVEC_CMD )
3041    {
3042        return  semicListFifthElementWrongType;
3043    }
3044    else if( l->m[5].rtyp != INTVEC_CMD )
3045    {
3046        return  semicListSixthElementWrongType;
3047    }
3048
3049    // -------------------------
3050    //  check number of entries
3051    // -------------------------
3052
3053    int     mu = (int)(long)(l->m[0].Data( ));
3054    int     pg = (int)(long)(l->m[1].Data( ));
3055    int     n  = (int)(long)(l->m[2].Data( ));
3056
3057    if( n <= 0 )
3058    {
3059        return  semicListNNegative;
3060    }
3061
3062    intvec  *num = (intvec*)l->m[3].Data( );
3063    intvec  *den = (intvec*)l->m[4].Data( );
3064    intvec  *mul = (intvec*)l->m[5].Data( );
3065
3066    if( n != num->length( ) )
3067    {
3068        return  semicListWrongNumberOfNumerators;
3069    }
3070    else if( n != den->length( ) )
3071    {
3072        return  semicListWrongNumberOfDenominators;
3073    }
3074    else if( n != mul->length( ) )
3075    {
3076        return  semicListWrongNumberOfMultiplicities;
3077    }
3078
3079    // --------
3080    //  values
3081    // --------
3082
3083    if( mu <= 0 )
3084    {
3085        return  semicListMuNegative;
3086    }
3087    if( pg < 0 )
3088    {
3089        return  semicListPgNegative;
3090    }
3091
3092    int i;
3093
3094    for( i=0; i<n; i++ )
3095    {
3096        if( (*num)[i] <= 0 )
3097        {
3098            return  semicListNumNegative;
3099        }
3100        if( (*den)[i] <= 0 )
3101        {
3102            return  semicListDenNegative;
3103        }
3104        if( (*mul)[i] <= 0 )
3105        {
3106            return  semicListMulNegative;
3107        }
3108    }
3109
3110    // ----------------
3111    //  check symmetry
3112    // ----------------
3113
3114    int     j;
3115
3116    for( i=0, j=n-1; i<=j; i++,j-- )
3117    {
3118        if( (*num)[i] != pVariables*((*den)[i]) - (*num)[j] ||
3119            (*den)[i] != (*den)[j] ||
3120            (*mul)[i] != (*mul)[j] )
3121        {
3122            return  semicListNotSymmetric;
3123        }
3124    }
3125
3126    // ----------------
3127    //  check monotony
3128    // ----------------
3129
3130    for( i=0, j=1; i<n/2; i++,j++ )
3131    {
3132        if( (*num)[i]*(*den)[j] >= (*num)[j]*(*den)[i] )
3133        {
3134            return  semicListNotMonotonous;
3135        }
3136    }
3137
3138    // ---------------------
3139    //  check Milnor number
3140    // ---------------------
3141
3142    for( mu=0, i=0; i<n; i++ )
3143    {
3144        mu += (*mul)[i];
3145    }
3146
3147    if( mu != (int)(long)(l->m[0].Data( )) )
3148    {
3149        return  semicListMilnorWrong;
3150    }
3151
3152    // -------------------------
3153    //  check geometrical genus
3154    // -------------------------
3155
3156    for( pg=0, i=0; i<n; i++ )
3157    {
3158        if( (*num)[i]<=(*den)[i] )
3159        {
3160            pg += (*mul)[i];
3161        }
3162    }
3163
3164    if( pg != (int)(long)(l->m[1].Data( )) )
3165    {
3166        return  semicListPGWrong;
3167    }
3168
3169    return  semicOK;
3170}
3171
3172// ----------------------------------------------------------------------------
3173//  this procedure is called from the interpreter
3174// ----------------------------------------------------------------------------
3175//  first  = list of spectrum numbers
3176//  second = list of spectrum numbers
3177//  result = sum of the two lists
3178// ----------------------------------------------------------------------------
3179
3180BOOLEAN spaddProc( leftv result,leftv first,leftv second )
3181{
3182    semicState  state;
3183
3184    // -----------------
3185    //  check arguments
3186    // -----------------
3187
3188    lists l1 = (lists)first->Data( );
3189    lists l2 = (lists)second->Data( );
3190
3191    if( (state=list_is_spectrum( l1 )) != semicOK )
3192    {
3193        WerrorS( "first argument is not a spectrum:" );
3194        list_error( state );
3195    }
3196    else if( (state=list_is_spectrum( l2 )) != semicOK )
3197    {
3198        WerrorS( "second argument is not a spectrum:" );
3199        list_error( state );
3200    }
3201    else
3202    {
3203        spectrum s1( l1 );
3204        spectrum s2( l2 );
3205        spectrum sum( s1+s2 );
3206
3207        result->rtyp = LIST_CMD;
3208        result->data = (char*)(sum.thelist( ));
3209    }
3210
3211    return  (state!=semicOK);
3212}
3213
3214// ----------------------------------------------------------------------------
3215//  this procedure is called from the interpreter
3216// ----------------------------------------------------------------------------
3217//  first  = list of spectrum numbers
3218//  second = integer
3219//  result = the multiple of the first list by the second factor
3220// ----------------------------------------------------------------------------
3221
3222BOOLEAN spmulProc( leftv result,leftv first,leftv second )
3223{
3224    semicState  state;
3225
3226    // -----------------
3227    //  check arguments
3228    // -----------------
3229
3230    lists   l = (lists)first->Data( );
3231    int     k = (int)(long)second->Data( );
3232
3233    if( (state=list_is_spectrum( l ))!=semicOK )
3234    {
3235        WerrorS( "first argument is not a spectrum" );
3236        list_error( state );
3237    }
3238    else if( k < 0 )
3239    {
3240        WerrorS( "second argument should be positive" );
3241        state = semicMulNegative;
3242    }
3243    else
3244    {
3245        spectrum s( l );
3246        spectrum product( k*s );
3247
3248        result->rtyp = LIST_CMD;
3249        result->data = (char*)product.thelist( );
3250    }
3251
3252    return  (state!=semicOK);
3253}
3254
3255// ----------------------------------------------------------------------------
3256//  this procedure is called from the interpreter
3257// ----------------------------------------------------------------------------
3258//  first  = list of spectrum numbers
3259//  second = list of spectrum numbers
3260//  result = semicontinuity index
3261// ----------------------------------------------------------------------------
3262
3263BOOLEAN    semicProc3   ( leftv res,leftv u,leftv v,leftv w )
3264{
3265  semicState  state;
3266  BOOLEAN qh=(((int)(long)w->Data())==1);
3267
3268  // -----------------
3269  //  check arguments
3270  // -----------------
3271
3272  lists l1 = (lists)u->Data( );
3273  lists l2 = (lists)v->Data( );
3274
3275  if( (state=list_is_spectrum( l1 ))!=semicOK )
3276  {
3277    WerrorS( "first argument is not a spectrum" );
3278    list_error( state );
3279  }
3280  else if( (state=list_is_spectrum( l2 ))!=semicOK )
3281  {
3282    WerrorS( "second argument is not a spectrum" );
3283    list_error( state );
3284  }
3285  else
3286  {
3287    spectrum s1( l1 );
3288    spectrum s2( l2 );
3289
3290    res->rtyp = INT_CMD;
3291    if (qh)
3292      res->data = (void*)(s1.mult_spectrumh( s2 ));
3293    else
3294      res->data = (void*)(s1.mult_spectrum( s2 ));
3295  }
3296
3297  // -----------------
3298  //  check status
3299  // -----------------
3300
3301  return  (state!=semicOK);
3302}
3303BOOLEAN    semicProc   ( leftv res,leftv u,leftv v )
3304{
3305  sleftv tmp;
3306  memset(&tmp,0,sizeof(tmp));
3307  tmp.rtyp=INT_CMD;
3308  /* tmp.data = (void *)0;  -- done by memset */
3309
3310  return  semicProc3(res,u,v,&tmp);
3311}
3312// from splist.cc
3313// ----------------------------------------------------------------------------
3314//  Compute the spectrum of a  spectrumPolyList
3315// ----------------------------------------------------------------------------
3316
3317spectrumState   spectrumPolyList::spectrum( lists *L,int fast )
3318{
3319    spectrumPolyNode  **node = &root;
3320    spectrumPolyNode  *search;
3321
3322    poly              f,tmp;
3323    int               found,cmp;
3324
3325    Rational smax( ( fast==0 ? 0 : pVariables ),
3326                   ( fast==2 ? 2 : 1 ) );
3327
3328    Rational weight_prev( 0,1 );
3329
3330    int     mu = 0;          // the milnor number
3331    int     pg = 0;          // the geometrical genus
3332    int     n  = 0;          // number of different spectral numbers
3333    int     z  = 0;          // number of spectral number equal to smax
3334
3335    int     k = 0;
3336
3337    while( (*node)!=(spectrumPolyNode*)NULL &&
3338           ( fast==0 || (*node)->weight<=smax ) )
3339    {
3340        // ---------------------------------------
3341        //  determine the first normal form which
3342        //  contains the monomial  node->mon
3343        // ---------------------------------------
3344
3345        found  = FALSE;
3346        search = *node;
3347
3348        while( search!=(spectrumPolyNode*)NULL && found==FALSE )
3349        {
3350            if( search->nf!=(poly)NULL )
3351            {
3352                f = search->nf;
3353
3354                do
3355                {
3356                    // --------------------------------
3357                    //  look for  (*node)->mon  in   f
3358                    // --------------------------------
3359
3360                    cmp = pCmp( (*node)->mon,f );
3361
3362                    if( cmp<0 )
3363                    {
3364                        f = pNext( f );
3365                    }
3366                    else if( cmp==0 )
3367                    {
3368                        // -----------------------------
3369                        //  we have found a normal form
3370                        // -----------------------------
3371
3372                        found = TRUE;
3373
3374                        //  normalize coefficient
3375
3376                        number inv = nInvers( pGetCoeff( f ) );
3377                        pMult_nn( search->nf,inv );
3378                        nDelete( &inv );
3379
3380                        //  exchange  normal forms
3381
3382                        tmp         = (*node)->nf;
3383                        (*node)->nf = search->nf;
3384                        search->nf  = tmp;
3385                    }
3386                }
3387                while( cmp<0 && f!=(poly)NULL );
3388            }
3389            search = search->next;
3390        }
3391
3392        if( found==FALSE )
3393        {
3394            // ------------------------------------------------
3395            //  the weight of  node->mon  is a spectrum number
3396            // ------------------------------------------------
3397
3398            mu++;
3399
3400            if( (*node)->weight<=(Rational)1 )              pg++;
3401            if( (*node)->weight==smax )           z++;
3402            if( (*node)->weight>weight_prev )     n++;
3403
3404            weight_prev = (*node)->weight;
3405            node = &((*node)->next);
3406        }
3407        else
3408        {
3409            // -----------------------------------------------
3410            //  determine all other normal form which contain
3411            //  the monomial  node->mon
3412            //  replace for  node->mon  its normal form
3413            // -----------------------------------------------
3414
3415            while( search!=(spectrumPolyNode*)NULL )
3416            {
3417                    if( search->nf!=(poly)NULL )
3418                {
3419                    f = search->nf;
3420
3421                    do
3422                    {
3423                        // --------------------------------
3424                        //  look for  (*node)->mon  in   f
3425                        // --------------------------------
3426
3427                        cmp = pCmp( (*node)->mon,f );
3428
3429                        if( cmp<0 )
3430                        {
3431                            f = pNext( f );
3432                        }
3433                        else if( cmp==0 )
3434                        {
3435                            search->nf = pSub( search->nf,
3436                                ppMult_nn( (*node)->nf,pGetCoeff( f ) ) );
3437                            pNorm( search->nf );
3438                        }
3439                    }
3440                    while( cmp<0 && f!=(poly)NULL );
3441                }
3442                search = search->next;
3443            }
3444            delete_node( node );
3445        }
3446
3447    }
3448
3449    // --------------------------------------------------------
3450    //  fast computation exploits the symmetry of the spectrum
3451    // --------------------------------------------------------
3452
3453    if( fast==2 )
3454    {
3455        mu = 2*mu - z;
3456        n  = ( z > 0 ? 2*n - 1 : 2*n );
3457    }
3458
3459    // --------------------------------------------------------
3460    //  compute the spectrum numbers with their multiplicities
3461    // --------------------------------------------------------
3462
3463    intvec            *nom  = new intvec( n );
3464    intvec            *den  = new intvec( n );
3465    intvec            *mult = new intvec( n );
3466
3467    int count         = 0;
3468    int multiplicity  = 1;
3469
3470    for( search=root; search!=(spectrumPolyNode*)NULL &&
3471                     ( fast==0 || search->weight<=smax );
3472                     search=search->next )
3473    {
3474        if( search->next==(spectrumPolyNode*)NULL ||
3475            search->weight<search->next->weight )
3476        {
3477            (*nom) [count] = search->weight.get_num_si( );
3478            (*den) [count] = search->weight.get_den_si( );
3479            (*mult)[count] = multiplicity;
3480
3481            multiplicity=1;
3482            count++;
3483        }
3484        else
3485        {
3486            multiplicity++;
3487        }
3488    }
3489
3490    // --------------------------------------------------------
3491    //  fast computation exploits the symmetry of the spectrum
3492    // --------------------------------------------------------
3493
3494    if( fast==2 )
3495    {
3496        int n1,n2;
3497        for( n1=0, n2=n-1; n1<n2; n1++, n2-- )
3498        {
3499            (*nom) [n2] = pVariables*(*den)[n1]-(*nom)[n1];
3500            (*den) [n2] = (*den)[n1];
3501            (*mult)[n2] = (*mult)[n1];
3502        }
3503    }
3504
3505    // -----------------------------------
3506    //  test if the spectrum is symmetric
3507    // -----------------------------------
3508
3509    if( fast==0 || fast==1 )
3510    {
3511        int symmetric=TRUE;
3512
3513        for( int n1=0, n2=n-1 ; n1<n2 && symmetric==TRUE; n1++, n2-- )
3514        {
3515            if( (*mult)[n1]!=(*mult)[n2] ||
3516                (*den) [n1]!= (*den)[n2] ||
3517                (*nom)[n1]+(*nom)[n2]!=pVariables*(*den) [n1] )
3518            {
3519                symmetric = FALSE;
3520            }
3521        }
3522
3523        if( symmetric==FALSE )
3524        {
3525            // ---------------------------------------------
3526            //  the spectrum is not symmetric => degenerate
3527            //  principal part
3528            // ---------------------------------------------
3529
3530            *L = (lists)omAllocBin( slists_bin);
3531            (*L)->Init( 1 );
3532            (*L)->m[0].rtyp = INT_CMD;    //  milnor number
3533            (*L)->m[0].data = (void*)mu;
3534
3535            return spectrumDegenerate;
3536        }
3537    }
3538
3539    *L = (lists)omAllocBin( slists_bin);
3540
3541    (*L)->Init( 6 );
3542
3543    (*L)->m[0].rtyp = INT_CMD;    //  milnor number
3544    (*L)->m[1].rtyp = INT_CMD;    //  geometrical genus
3545    (*L)->m[2].rtyp = INT_CMD;    //  number of spectrum values
3546    (*L)->m[3].rtyp = INTVEC_CMD; //  nominators
3547    (*L)->m[4].rtyp = INTVEC_CMD; //  denomiantors
3548    (*L)->m[5].rtyp = INTVEC_CMD; //  multiplicities
3549
3550    (*L)->m[0].data = (void*)mu;
3551    (*L)->m[1].data = (void*)pg;
3552    (*L)->m[2].data = (void*)n;
3553    (*L)->m[3].data = (void*)nom;
3554    (*L)->m[4].data = (void*)den;
3555    (*L)->m[5].data = (void*)mult;
3556
3557    return  spectrumOK;
3558}
3559
3560#endif
3561
3562//from mpr_inout.cc
3563extern void nPrint(number n);
3564
3565BOOLEAN loNewtonP( leftv res, leftv arg1 )
3566{
3567  res->data= (void*)loNewtonPolytope( (ideal)arg1->Data() );
3568  return FALSE;
3569}
3570
3571BOOLEAN loSimplex( leftv res, leftv args )
3572{
3573  if ( !(rField_is_long_R()) )
3574  {
3575    WerrorS("Ground field not implemented!");
3576    return TRUE;
3577  }
3578
3579  simplex * LP;
3580  matrix m;
3581
3582  leftv v= args;
3583  if ( v->Typ() != MATRIX_CMD ) // 1: matrix
3584    return TRUE;
3585  else
3586    m= (matrix)(v->CopyD());
3587
3588  LP = new simplex(MATROWS(m),MATCOLS(m));
3589  LP->mapFromMatrix(m);
3590
3591  v= v->next;
3592  if ( v->Typ() != INT_CMD )    // 2: m = number of constraints
3593    return TRUE;
3594  else
3595    LP->m= (int)(long)(v->Data());
3596
3597  v= v->next;
3598  if ( v->Typ() != INT_CMD )    // 3: n = number of variables
3599    return TRUE;
3600  else
3601    LP->n= (int)(long)(v->Data());
3602
3603  v= v->next;
3604  if ( v->Typ() != INT_CMD )    // 4: m1 = number of <= constraints
3605    return TRUE;
3606  else
3607    LP->m1= (int)(long)(v->Data());
3608
3609  v= v->next;
3610  if ( v->Typ() != INT_CMD )    // 5: m2 = number of >= constraints
3611    return TRUE;
3612  else
3613    LP->m2= (int)(long)(v->Data());
3614
3615  v= v->next;
3616  if ( v->Typ() != INT_CMD )    // 6: m3 = number of == constraints
3617    return TRUE;
3618  else
3619    LP->m3= (int)(long)(v->Data());
3620
3621#ifdef mprDEBUG_PROT
3622  Print("m (constraints) %d\n",LP->m);
3623  Print("n (columns) %d\n",LP->n);
3624  Print("m1 (<=) %d\n",LP->m1);
3625  Print("m2 (>=) %d\n",LP->m2);
3626  Print("m3 (==) %d\n",LP->m3);
3627#endif
3628
3629  LP->compute();
3630
3631  lists lres= (lists)omAlloc( sizeof(slists) );
3632  lres->Init( 6 );
3633
3634  lres->m[0].rtyp= MATRIX_CMD; // output matrix
3635  lres->m[0].data=(void*)LP->mapToMatrix(m);
3636
3637  lres->m[1].rtyp= INT_CMD;   // found a solution?
3638  lres->m[1].data=(void*)LP->icase;
3639
3640  lres->m[2].rtyp= INTVEC_CMD;
3641  lres->m[2].data=(void*)LP->posvToIV();
3642
3643  lres->m[3].rtyp= INTVEC_CMD;
3644  lres->m[3].data=(void*)LP->zrovToIV();
3645
3646  lres->m[4].rtyp= INT_CMD;
3647  lres->m[4].data=(void*)LP->m;
3648
3649  lres->m[5].rtyp= INT_CMD;
3650  lres->m[5].data=(void*)LP->n;
3651
3652  res->data= (void*)lres;
3653
3654  return FALSE;
3655}
3656
3657BOOLEAN nuMPResMat( leftv res, leftv arg1, leftv arg2 )
3658{
3659  ideal gls = (ideal)(arg1->Data());
3660  int imtype= (int)(long)arg2->Data();
3661
3662  uResultant::resMatType mtype= determineMType( imtype );
3663
3664  // check input ideal ( = polynomial system )
3665  if ( mprIdealCheck( gls, arg1->Name(), mtype, true ) != mprOk )
3666  {
3667    return TRUE;
3668  }
3669
3670  uResultant *resMat= new uResultant( gls, mtype, false );
3671  if (resMat!=NULL)
3672  {
3673    res->rtyp = MODUL_CMD;
3674    res->data= (void*)resMat->accessResMat()->getMatrix();
3675    if (!errorreported) delete resMat;
3676  }
3677  return errorreported;
3678}
3679
3680BOOLEAN nuLagSolve( leftv res, leftv arg1, leftv arg2, leftv arg3 )
3681{
3682
3683  poly gls;
3684  gls= (poly)(arg1->Data());
3685  int howclean= (int)(long)arg3->Data();
3686
3687  if ( !(rField_is_R() ||
3688         rField_is_Q() ||
3689         rField_is_long_R() ||
3690         rField_is_long_C()) )
3691  {
3692    WerrorS("Ground field not implemented!");
3693    return TRUE;
3694  }
3695
3696  if ( !(rField_is_R()||rField_is_long_R()||rField_is_long_C()) )
3697  {
3698    unsigned long int ii = (unsigned long int)arg2->Data();
3699    setGMPFloatDigits( ii, ii );
3700  }
3701
3702  if ( gls == NULL || pIsConstant( gls ) )
3703  {
3704    WerrorS("Input polynomial is constant!");
3705    return TRUE;
3706  }
3707
3708  int ldummy;
3709  int deg= pLDeg( gls, &ldummy, currRing );
3710  //  int deg= pDeg( gls );
3711  int len= pLength( gls );
3712  int i,vpos;
3713  poly piter;
3714  lists elist;
3715  lists rlist;
3716
3717  elist= (lists)omAlloc( sizeof(slists) );
3718  elist->Init( 0 );
3719
3720  if ( pVariables > 1 )
3721  {
3722    piter= gls;
3723    for ( i= 1; i <= pVariables; i++ )
3724      if ( pGetExp( piter, i ) )
3725      {
3726        vpos= i;
3727        break;
3728      }
3729    while ( piter )
3730    {
3731      for ( i= 1; i <= pVariables; i++ )
3732        if ( (vpos != i) && (pGetExp( piter, i ) != 0) )
3733        {
3734          WerrorS("The input polynomial must be univariate!");
3735          return TRUE;
3736        }
3737      pIter( piter );
3738    }
3739  }
3740
3741  rootContainer * roots= new rootContainer();
3742  number * pcoeffs= (number *)omAlloc( (deg+1) * sizeof( number ) );
3743  piter= gls;
3744  for ( i= deg; i >= 0; i-- )
3745  {
3746    //if ( piter ) Print("deg %d, pDeg(piter) %d\n",i,pTotaldegree(piter));
3747    if ( piter && pTotaldegree(piter) == i )
3748    {
3749      pcoeffs[i]= nCopy( pGetCoeff( piter ) );
3750      //nPrint( pcoeffs[i] );PrintS("  ");
3751      pIter( piter );
3752    }
3753    else
3754    {
3755      pcoeffs[i]= nInit(0);
3756    }
3757  }
3758
3759#ifdef mprDEBUG_PROT
3760  for (i=deg; i >= 0; i--)
3761  {
3762    nPrint( pcoeffs[i] );PrintS("  ");
3763  }
3764  PrintLn();
3765#endif
3766
3767  roots->fillContainer( pcoeffs, NULL, 1, deg, rootContainer::onepoly, 1 );
3768  roots->solver( howclean );
3769
3770  int elem= roots->getAnzRoots();
3771  char *out;
3772  char *dummy;
3773  int j;
3774
3775  rlist= (lists)omAlloc( sizeof(slists) );
3776  rlist->Init( elem );
3777
3778  if (rField_is_long_C())
3779  {
3780    for ( j= 0; j < elem; j++ )
3781    {
3782      rlist->m[j].rtyp=NUMBER_CMD;
3783      rlist->m[j].data=(void *)nCopy((number)(roots->getRoot(j)));
3784      //rlist->m[j].data=(void *)(number)(roots->getRoot(j));
3785    }
3786  }
3787  else
3788  {
3789    for ( j= 0; j < elem; j++ )
3790    {
3791      dummy = complexToStr( (*roots)[j], gmp_output_digits );
3792      rlist->m[j].rtyp=STRING_CMD;
3793      rlist->m[j].data=(void *)dummy;
3794    }
3795  }
3796
3797  elist->Clean();
3798  //omFreeSize( (ADDRESS) elist, sizeof(slists) );
3799
3800  // this is (via fillContainer) the same data as in root
3801  //for ( i= deg; i >= 0; i-- ) nDelete( &pcoeffs[i] );
3802  //omFreeSize( (ADDRESS) pcoeffs, (deg+1) * sizeof( number ) );
3803
3804  delete roots;
3805
3806  res->rtyp= LIST_CMD;
3807  res->data= (void*)rlist;
3808
3809  return FALSE;
3810}
3811
3812BOOLEAN nuVanderSys( leftv res, leftv arg1, leftv arg2, leftv arg3)
3813{
3814  int i;
3815  ideal p,w;
3816  p= (ideal)arg1->Data();
3817  w= (ideal)arg2->Data();
3818
3819  // w[0] = f(p^0)
3820  // w[1] = f(p^1)
3821  // ...
3822  // p can be a vector of numbers (multivariate polynom)
3823  //   or one number (univariate polynom)
3824  // tdg = deg(f)
3825
3826  int n= IDELEMS( p );
3827  int m= IDELEMS( w );
3828  int tdg= (int)(long)arg3->Data();
3829
3830  res->data= (void*)NULL;
3831
3832  // check the input
3833  if ( tdg < 1 )
3834  {
3835    WerrorS("Last input parameter must be > 0!");
3836    return TRUE;
3837  }
3838  if ( n != pVariables )
3839  {
3840    Werror("Size of first input ideal must be equal to %d!",pVariables);
3841    return TRUE;
3842  }
3843  if ( m != (int)pow((double)tdg+1,(double)n) )
3844  {
3845    Werror("Size of second input ideal must be equal to %d!",
3846      (int)pow((double)tdg+1,(double)n));
3847    return TRUE;
3848  }
3849  if ( !(rField_is_Q() /* ||
3850         rField_is_R() || rField_is_long_R() ||
3851         rField_is_long_C()*/ ) )
3852         {
3853    WerrorS("Ground field not implemented!");
3854    return TRUE;
3855  }
3856
3857  number tmp;
3858  number *pevpoint= (number *)omAlloc( n * sizeof( number ) );
3859  for ( i= 0; i < n; i++ )
3860  {
3861    pevpoint[i]=nInit(0);
3862    if (  (p->m)[i] )
3863    {
3864      tmp = pGetCoeff( (p->m)[i] );
3865      if ( nIsZero(tmp) || nIsOne(tmp) || nIsMOne(tmp) )
3866      {
3867        omFreeSize( (ADDRESS)pevpoint, n * sizeof( number ) );
3868        WerrorS("Elements of first input ideal must not be equal to -1, 0, 1!");
3869        return TRUE;
3870      }
3871    } else tmp= NULL;
3872    if ( !nIsZero(tmp) )
3873    {
3874      if ( !pIsConstant((p->m)[i]))
3875      {
3876        omFreeSize( (ADDRESS)pevpoint, n * sizeof( number ) );
3877        WerrorS("Elements of first input ideal must be numbers!");
3878        return TRUE;
3879      }
3880      pevpoint[i]= nCopy( tmp );
3881    }
3882  }
3883
3884  number *wresults= (number *)omAlloc( m * sizeof( number ) );
3885  for ( i= 0; i < m; i++ )
3886  {
3887    wresults[i]= nInit(0);
3888    if ( (w->m)[i] && !nIsZero(pGetCoeff((w->m)[i])) )
3889    {
3890      if ( !pIsConstant((w->m)[i]))
3891      {
3892        omFreeSize( (ADDRESS)pevpoint, n * sizeof( number ) );
3893        omFreeSize( (ADDRESS)wresults, m * sizeof( number ) );
3894        WerrorS("Elements of second input ideal must be numbers!");
3895        return TRUE;
3896      }
3897      wresults[i]= nCopy(pGetCoeff((w->m)[i]));
3898    }
3899  }
3900
3901  vandermonde vm( m, n, tdg, pevpoint, FALSE );
3902  number *ncpoly= vm.interpolateDense( wresults );
3903  // do not free ncpoly[]!!
3904  poly rpoly= vm.numvec2poly( ncpoly );
3905
3906  omFreeSize( (ADDRESS)pevpoint, n * sizeof( number ) );
3907  omFreeSize( (ADDRESS)wresults, m * sizeof( number ) );
3908
3909  res->data= (void*)rpoly;
3910  return FALSE;
3911}
3912
3913BOOLEAN nuUResSolve( leftv res, leftv args )
3914{
3915  leftv v= args;
3916
3917  ideal gls;
3918  int imtype;
3919  int howclean;
3920
3921  // get ideal
3922  if ( v->Typ() != IDEAL_CMD )
3923    return TRUE;
3924  else gls= (ideal)(v->Data());
3925  v= v->next;
3926
3927  // get resultant matrix type to use (0,1)
3928  if ( v->Typ() != INT_CMD )
3929    return TRUE;
3930  else imtype= (int)(long)v->Data();
3931  v= v->next;
3932
3933  if (imtype==0)
3934  {
3935    ideal test_id=idInit(1,1);
3936    int j;
3937    for(j=IDELEMS(gls)-1;j>=0;j--)
3938    {
3939      if (gls->m[j]!=NULL)
3940      {
3941        test_id->m[0]=gls->m[j];
3942        intvec *dummy_w=idQHomWeight(test_id);
3943        if (dummy_w!=NULL)
3944        {
3945          WerrorS("Newton polytope not of expected dimension");
3946          delete dummy_w;
3947          return TRUE;
3948        }
3949      }
3950    }
3951  }
3952
3953  // get and set precision in digits ( > 0 )
3954  if ( v->Typ() != INT_CMD )
3955    return TRUE;
3956  else if ( !(rField_is_R()||rField_is_long_R()||rField_is_long_C()) )
3957  {
3958    unsigned long int ii=(unsigned long int)v->Data();
3959    setGMPFloatDigits( ii, ii );
3960  }
3961  v= v->next;
3962
3963  // get interpolation steps (0,1,2)
3964  if ( v->Typ() != INT_CMD )
3965    return TRUE;
3966  else howclean= (int)(long)v->Data();
3967
3968  uResultant::resMatType mtype= determineMType( imtype );
3969  int i,c,count;
3970  lists listofroots= NULL;
3971  lists emptylist;
3972  number smv= NULL;
3973  BOOLEAN interpolate_det= (mtype==uResultant::denseResMat)?TRUE:FALSE;
3974
3975  //emptylist= (lists)omAlloc( sizeof(slists) );
3976  //emptylist->Init( 0 );
3977
3978  //res->rtyp = LIST_CMD;
3979  //res->data= (void *)emptylist;
3980
3981  // check input ideal ( = polynomial system )
3982  if ( mprIdealCheck( gls, args->Name(), mtype ) != mprOk )
3983  {
3984    return TRUE;
3985  }
3986
3987  uResultant * ures;
3988  rootContainer ** iproots;
3989  rootContainer ** muiproots;
3990  rootArranger * arranger;
3991
3992  // main task 1: setup of resultant matrix
3993  ures= new uResultant( gls, mtype );
3994  if ( ures->accessResMat()->initState() != resMatrixBase::ready )
3995  {
3996    WerrorS("Error occurred during matrix setup!");
3997    return TRUE;
3998  }
3999
4000  // if dense resultant, check if minor nonsingular
4001  if ( mtype == uResultant::denseResMat )
4002  {
4003    smv= ures->accessResMat()->getSubDet();
4004#ifdef mprDEBUG_PROT
4005    PrintS("// Determinant of submatrix: ");nPrint(smv);PrintLn();
4006#endif
4007    if ( nIsZero(smv) )
4008    {
4009      WerrorS("Unsuitable input ideal: Minor of resultant matrix is singular!");
4010      return TRUE;
4011    }
4012  }
4013
4014  // main task 2: Interpolate specialized resultant polynomials
4015  if ( interpolate_det )
4016    iproots= ures->interpolateDenseSP( false, smv );
4017  else
4018    iproots= ures->specializeInU( false, smv );
4019
4020  // main task 3: Interpolate specialized resultant polynomials
4021  if ( interpolate_det )
4022    muiproots= ures->interpolateDenseSP( true, smv );
4023  else
4024    muiproots= ures->specializeInU( true, smv );
4025
4026#ifdef mprDEBUG_PROT
4027  c= iproots[0]->getAnzElems();
4028  for (i=0; i < c; i++) pWrite(iproots[i]->getPoly());
4029  c= muiproots[0]->getAnzElems();
4030  for (i=0; i < c; i++) pWrite(muiproots[i]->getPoly());
4031#endif
4032
4033  // main task 4: Compute roots of specialized polys and match them up
4034  arranger= new rootArranger( iproots, muiproots, howclean );
4035  arranger->solve_all();
4036
4037  // get list of roots
4038  if ( arranger->success() )
4039  {
4040    arranger->arrange();
4041    listofroots= arranger->listOfRoots( gmp_output_digits );
4042  }
4043  else
4044  {
4045    WerrorS("Solver was unable to find any roots!");
4046    return TRUE;
4047  }
4048
4049  // free everything
4050  count= iproots[0]->getAnzElems();
4051  for (i=0; i < count; i++) delete iproots[i];
4052  omFreeSize( (ADDRESS) iproots, count * sizeof(rootContainer*) );
4053  count= muiproots[0]->getAnzElems();
4054  for (i=0; i < count; i++) delete muiproots[i];
4055  omFreeSize( (ADDRESS) muiproots, count * sizeof(rootContainer*) );
4056
4057  delete ures;
4058  delete arranger;
4059  nDelete( &smv );
4060
4061  res->data= (void *)listofroots;
4062
4063  //emptylist->Clean();
4064  //  omFreeSize( (ADDRESS) emptylist, sizeof(slists) );
4065
4066  return FALSE;
4067}
4068
4069// from mpr_numeric.cc
4070lists rootArranger::listOfRoots( const unsigned int oprec )
4071{
4072  int i,j,tr;
4073  int count= roots[0]->getAnzRoots(); // number of roots
4074  int elem= roots[0]->getAnzElems();  // number of koordinates per root
4075
4076  lists listofroots= (lists)omAlloc( sizeof(slists) ); // must be done this way!
4077
4078  if ( found_roots )
4079  {
4080    listofroots->Init( count );
4081
4082    for (i=0; i < count; i++)
4083    {
4084      lists onepoint= (lists)omAlloc(sizeof(slists)); // must be done this way!
4085      onepoint->Init(elem);
4086      for ( j= 0; j < elem; j++ )
4087      {
4088        if ( !rField_is_long_C() )
4089        {
4090          onepoint->m[j].rtyp=STRING_CMD;
4091          onepoint->m[j].data=(void *)complexToStr((*roots[j])[i],oprec);
4092        }
4093        else
4094        {
4095          onepoint->m[j].rtyp=NUMBER_CMD;
4096          onepoint->m[j].data=(void *)nCopy((number)(roots[j]->getRoot(i)));
4097        }
4098        onepoint->m[j].next= NULL;
4099        onepoint->m[j].name= NULL;
4100      }
4101      listofroots->m[i].rtyp=LIST_CMD;
4102      listofroots->m[i].data=(void *)onepoint;
4103      listofroots->m[j].next= NULL;
4104      listofroots->m[j].name= NULL;
4105    }
4106
4107  }
4108  else
4109  {
4110    listofroots->Init( 0 );
4111  }
4112
4113  return listofroots;
4114}
4115
4116// from ring.cc
4117void rSetHdl(idhdl h)
4118{
4119  int i;
4120  ring rg = NULL;
4121  if (h!=NULL)
4122  {
4123//   Print(" new ring:%s (l:%d)\n",IDID(h),IDLEV(h));
4124    rg = IDRING(h);
4125    omCheckAddrSize((ADDRESS)h,sizeof(idrec));
4126    if (IDID(h))  // OB: ????
4127      omCheckAddr((ADDRESS)IDID(h));
4128    rTest(rg);
4129  }
4130
4131  // clean up history
4132  if (sLastPrinted.RingDependend())
4133  {
4134    sLastPrinted.CleanUp();
4135    memset(&sLastPrinted,0,sizeof(sleftv));
4136  }
4137
4138   /*------------ change the global ring -----------------------*/
4139  rChangeCurrRing(rg);
4140  currRingHdl = h;
4141}
4142
4143BOOLEAN rSleftvOrdering2Ordering(sleftv *ord, ring R)
4144{
4145  int last = 0, o=0, n = 1, i=0, typ = 1, j;
4146  sleftv *sl = ord;
4147
4148  // determine nBlocks
4149  while (sl!=NULL)
4150  {
4151    intvec *iv = (intvec *)(sl->data);
4152    if (((*iv)[1]==ringorder_c)||((*iv)[1]==ringorder_C))
4153      i++;
4154    else if ((*iv)[1]==ringorder_L)
4155    {
4156      R->bitmask=(*iv)[2];
4157      n--;
4158    }
4159    else if (((*iv)[1]!=ringorder_a)
4160    && ((*iv)[1]!=ringorder_a64))
4161      o++;
4162    n++;
4163    sl=sl->next;
4164  }
4165  // check whether at least one real ordering
4166  if (o==0)
4167  {
4168    WerrorS("invalid combination of orderings");
4169    return TRUE;
4170  }
4171  // if no c/C ordering is given, increment n
4172  if (i==0) n++;
4173  else if (i != 1)
4174  {
4175    // throw error if more than one is given
4176    WerrorS("more than one ordering c/C specified");
4177    return TRUE;
4178  }
4179
4180  // initialize fields of R
4181  R->order=(int *)omAlloc0(n*sizeof(int));
4182  R->block0=(int *)omAlloc0(n*sizeof(int));
4183  R->block1=(int *)omAlloc0(n*sizeof(int));
4184  R->wvhdl=(int**)omAlloc0(n*sizeof(int_ptr));
4185
4186  // init order, so that rBlocks works correctly
4187  for (j=0; j < n-1; j++)
4188    R->order[j] = (int) ringorder_unspec;
4189  // set last _C order, if no c/C order was given
4190  if (i == 0) R->order[n-2] = ringorder_C;
4191
4192  /* init orders */
4193  sl=ord;
4194  n=-1;
4195  while (sl!=NULL)
4196  {
4197    intvec *iv;
4198    iv = (intvec *)(sl->data);
4199    if ((*iv)[1]!=ringorder_L)
4200    {
4201      n++;
4202
4203      /* the format of an ordering:
4204       *  iv[0]: factor
4205       *  iv[1]: ordering
4206       *  iv[2..end]: weights
4207       */
4208      R->order[n] = (*iv)[1];
4209      switch ((*iv)[1])
4210      {
4211          case ringorder_ws:
4212          case ringorder_Ws:
4213            typ=-1;
4214          case ringorder_wp:
4215          case ringorder_Wp:
4216            R->wvhdl[n]=(int*)omAlloc((iv->length()-1)*sizeof(int));
4217            for (i=2; i<iv->length(); i++)
4218            {
4219              R->wvhdl[n][i-2] = (*iv)[i];
4220            }
4221            R->block0[n] = last+1;
4222            last += iv->length()-2;
4223            R->block1[n] = last;
4224            break;
4225          case ringorder_ls:
4226          case ringorder_ds:
4227          case ringorder_Ds:
4228          case ringorder_rs:
4229            typ=-1;
4230          case ringorder_lp:
4231          case ringorder_dp:
4232          case ringorder_Dp:
4233          case ringorder_rp:
4234            R->block0[n] = last+1;
4235            if (iv->length() == 3) last+=(*iv)[2];
4236            else last += (*iv)[0];
4237            R->block1[n] = last;
4238            if (R->block0[n]>R->block1[n]) return TRUE;
4239            if (rCheckIV(iv)) return TRUE;
4240            break;
4241          case ringorder_S:
4242          case ringorder_c:
4243          case ringorder_C:
4244            if (rCheckIV(iv)) return TRUE;
4245            break;
4246          case ringorder_aa:
4247          case ringorder_a:
4248            R->block0[n] = last+1;
4249            R->block1[n] = si_min(last+iv->length()-2 , R->N);
4250            R->wvhdl[n] = (int*)omAlloc((iv->length()-1)*sizeof(int));
4251            for (i=2; i<iv->length(); i++)
4252            {
4253              R->wvhdl[n][i-2]=(*iv)[i];
4254              if ((*iv)[i]<0) typ=-1;
4255            }
4256            break;
4257          case ringorder_a64:
4258          {
4259            R->block0[n] = last+1;
4260            R->block1[n] = si_min(last+iv->length()-2 , R->N);
4261            R->wvhdl[n] = (int*)omAlloc((iv->length()-1)*sizeof(int64));
4262            int64 *w=(int64 *)R->wvhdl[n];
4263            for (i=2; i<iv->length(); i++)
4264            {
4265              w[i-2]=(*iv)[i];
4266              if ((*iv)[i]<0) typ=-1;
4267            }
4268            break;
4269          }
4270          case ringorder_M:
4271          {
4272            int Mtyp=rTypeOfMatrixOrder(iv);
4273            if (Mtyp==0) return TRUE;
4274            if (Mtyp==-1) typ = -1;
4275
4276            R->wvhdl[n] =( int *)omAlloc((iv->length()-1)*sizeof(int));
4277            for (i=2; i<iv->length();i++)
4278              R->wvhdl[n][i-2]=(*iv)[i];
4279
4280            R->block0[n] = last+1;
4281            last += (int)sqrt((double)(iv->length()-2));
4282            R->block1[n] = last;
4283            break;
4284          }
4285
4286          case ringorder_no:
4287            R->order[n] = ringorder_unspec;
4288            return TRUE;
4289
4290          default:
4291            Werror("Internal Error: Unknown ordering %d", (*iv)[1]);
4292            R->order[n] = ringorder_unspec;
4293            return TRUE;
4294      }
4295    }
4296    sl=sl->next;
4297  }
4298
4299  // check for complete coverage
4300  if ((R->order[n]==ringorder_c) ||  (R->order[n]==ringorder_C)) n--;
4301  if (R->block1[n] != R->N)
4302  {
4303    if (((R->order[n]==ringorder_dp) ||
4304         (R->order[n]==ringorder_ds) ||
4305         (R->order[n]==ringorder_Dp) ||
4306         (R->order[n]==ringorder_Ds) ||
4307         (R->order[n]==ringorder_rp) ||
4308         (R->order[n]==ringorder_rs) ||
4309         (R->order[n]==ringorder_lp) ||
4310         (R->order[n]==ringorder_ls))
4311        &&
4312        R->block0[n] <= R->N)
4313    {
4314      R->block1[n] = R->N;
4315    }
4316    else
4317    {
4318      Werror("mismatch of number of vars (%d) and ordering (%d vars)",
4319             R->N,R->block1[n]);
4320      return TRUE;
4321    }
4322  }
4323  R->OrdSgn = typ;
4324  return FALSE;
4325}
4326
4327BOOLEAN rSleftvList2StringArray(sleftv* sl, char** p)
4328{
4329
4330  while(sl!=NULL)
4331  {
4332    if (sl->Name() == sNoName)
4333    {
4334      if (sl->Typ()==POLY_CMD)
4335      {
4336        sleftv s_sl;
4337        iiConvert(POLY_CMD,ANY_TYPE,-1,sl,&s_sl);
4338        if (s_sl.Name() != sNoName)
4339          *p = omStrDup(s_sl.Name());
4340        else
4341          *p = NULL;
4342        sl->next = s_sl.next;
4343        s_sl.next = NULL;
4344        s_sl.CleanUp();
4345        if (*p == NULL) return TRUE;
4346      }
4347      else
4348        return TRUE;
4349    }
4350    else
4351      *p = omStrDup(sl->Name());
4352    p++;
4353    sl=sl->next;
4354  }
4355  return FALSE;
4356}
4357
4358////////////////////
4359//
4360// rInit itself:
4361//
4362// INPUT:  s: name, pn: ch & parameter (names), rv: variable (names)
4363//         ord: ordering
4364// RETURN: currRingHdl on success
4365//         NULL        on error
4366// NOTE:   * makes new ring to current ring, on success
4367//         * considers input sleftv's as read-only
4368//idhdl rInit(char *s, sleftv* pn, sleftv* rv, sleftv* ord)
4369ring rInit(sleftv* pn, sleftv* rv, sleftv* ord)
4370{
4371  int ch;
4372#ifdef HAVE_RINGS
4373  unsigned int ringtype = 0;
4374  unsigned long long ringflaga = 0;
4375  unsigned int ringflagb = 0;
4376#endif
4377  int float_len=0;
4378  int float_len2=0;
4379  ring R = NULL;
4380  idhdl tmp = NULL;
4381  BOOLEAN ffChar=FALSE;
4382  int typ = 1;
4383
4384  /* ch -------------------------------------------------------*/
4385  // get ch of ground field
4386  int numberOfAllocatedBlocks;
4387
4388  if (pn->Typ()==INT_CMD)
4389  {
4390    ch=(int)(long)pn->Data();
4391  }
4392  else if ((pn->name != NULL)
4393  && ((strcmp(pn->name,"real")==0) || (strcmp(pn->name,"complex")==0)))
4394  {
4395    BOOLEAN complex_flag=(strcmp(pn->name,"complex")==0);
4396    ch=-1;
4397    if ((pn->next!=NULL) && (pn->next->Typ()==INT_CMD))
4398    {
4399      float_len=(int)(long)pn->next->Data();
4400      float_len2=float_len;
4401      pn=pn->next;
4402      if ((pn->next!=NULL) && (pn->next->Typ()==INT_CMD))
4403      {
4404        float_len2=(int)(long)pn->next->Data();
4405        pn=pn->next;
4406      }
4407    }
4408    if ((pn->next==NULL) && complex_flag)
4409    {
4410      pn->next=(leftv)omAlloc0Bin(sleftv_bin);
4411      pn->next->name=omStrDup("i");
4412    }
4413  }
4414#ifdef HAVE_RINGZ
4415  else if ((pn->name != NULL)
4416  && (strcmp(pn->name,"integers")==0))
4417  {
4418    ch = 0;
4419    ringtype = 4;
4420    WarnS("integers not yet fully tested");
4421  }
4422#endif
4423#ifdef HAVE_RINGMODN
4424  else if ((pn->name != NULL)
4425  && (strcmp(pn->name,"modnat")==0))
4426  {
4427    unsigned long long module = 1;
4428    while ((pn->next!=NULL) && (pn->next->Typ()==INT_CMD))
4429    {
4430      module *= (unsigned long long) pn->next->Data();
4431      pn=pn->next;
4432    }
4433    if ((module < 2))
4434    {
4435      Werror("Wrong ground ring specification (modnat)");
4436      goto rInitError;
4437    }
4438    ch = module;
4439    ringtype = 2;
4440    ringflaga = module;
4441    ringflagb = 1;
4442    WarnS("Z/n not yet fully tested");
4443  }
4444#endif
4445#ifdef HAVE_RING2TOM
4446  else if ((pn->name != NULL)
4447  && (strcmp(pn->name,"modpow")==0))
4448  {
4449    unsigned long base = 0;
4450    unsigned int exp = 0;
4451    if ((pn->next!=NULL) && (pn->next->Typ()==INT_CMD))
4452    {
4453      base =(unsigned long) pn->next->Data();
4454      pn=pn->next;
4455      if ((pn->next!=NULL) && (pn->next->Typ()==INT_CMD))
4456      {
4457        exp = (unsigned int) (unsigned long) pn->next->Data();
4458        pn=pn->next;
4459      }
4460    }
4461    if ((base < 2) || (exp < 1))
4462    {
4463      Werror("Wrong ground ring specification");
4464      goto rInitError;
4465    }
4466    ch = exp;
4467    if ((base == 2) && (exp + 2 <= 8*sizeof(NATNUMBER)))
4468    {
4469      ringtype = 1; // Use Z/2^ch
4470      ringflaga = 2;
4471      ringflagb = exp;
4472      WarnS("Z/2^n not yet fully tested");
4473    }
4474    else
4475    {
4476      if ((base == 2) && (exp + 2 > 8*sizeof(NATNUMBER)))
4477      {
4478        Print("// exponent+2 is larger then number of bits in 'NATNUMBER' (%d bits)\n", 8*sizeof(NATNUMBER));
4479        WarnS("==> using generic gmp implementation (restriction from design and NTL)");
4480      }
4481      ringtype = 3;
4482      ringflaga = base;
4483      ringflagb = exp;
4484      WarnS("Z/p^n not yet fully tested");
4485    }
4486  }
4487#endif
4488  else
4489  {
4490    Werror("Wrong ground field specification");
4491    goto rInitError;
4492  }
4493  pn=pn->next;
4494
4495  int l, last;
4496  sleftv * sl;
4497  /*every entry in the new ring is initialized to 0*/
4498
4499  /* characteristic -----------------------------------------------*/
4500  /* input: 0 ch=0 : Q     parameter=NULL    ffChar=FALSE   float_len
4501   *         0    1 : Q(a,...)        *names         FALSE
4502   *         0   -1 : R               NULL           FALSE  0
4503   *         0   -1 : R               NULL           FALSE  prec. >6
4504   *         0   -1 : C               *names         FALSE  prec. 0..?
4505   *         p    p : Fp              NULL           FALSE
4506   *         p   -p : Fp(a)           *names         FALSE
4507   *         q    q : GF(q=p^n)       *names         TRUE
4508  */
4509  if ((ch!=-1)
4510#ifdef HAVE_RINGS
4511       && (ringtype == 0)
4512#endif
4513     )
4514  {
4515    int l = 0;
4516
4517    if (((ch!=0) && (ch<2))
4518    #ifndef NV_OPS
4519    || (ch > 32003)
4520    #endif
4521    )
4522    {
4523      Warn("%d is invalid characteristic of ground field. 32003 is used.", ch);
4524      ch=32003;
4525    }
4526    // load fftable, if necessary
4527    if (pn!=NULL)
4528    {
4529      while ((ch!=fftable[l]) && (fftable[l])) l++;
4530      if (fftable[l]==0) ch = IsPrime(ch);
4531      else
4532      {
4533        char *m[1]={(char *)sNoName};
4534        nfSetChar(ch,m);
4535        if (errorreported) goto rInitError;
4536        else ffChar=TRUE;
4537      }
4538    }
4539    else
4540    {
4541      ch = IsPrime(ch);
4542    }
4543  }
4544  // allocated ring and set ch
4545  R = (ring) omAlloc0Bin(sip_sring_bin);
4546  R->ch = ch;
4547#ifdef HAVE_RINGS
4548  R->ringtype = ringtype;
4549  R->ringflaga = ringflaga;
4550  R->ringflagb = ringflagb;
4551#endif
4552  if (ch == -1)
4553  {
4554    R->float_len= si_min(float_len,32767);
4555    R->float_len2= si_min(float_len2,32767);
4556  }
4557
4558  /* parameter -------------------------------------------------------*/
4559  if (pn!=NULL)
4560  {
4561    R->P=pn->listLength();
4562    //if ((ffChar|| (ch == 1)) && (R->P > 1))
4563    if ((R->P > 1) && (ffChar || (ch == -1)))
4564    {
4565      WerrorS("too many parameters");
4566      goto rInitError;
4567    }
4568    R->parameter=(char**)omAlloc0(R->P*sizeof(char_ptr));
4569    if (rSleftvList2StringArray(pn, R->parameter))
4570    {
4571      WerrorS("parameter expected");
4572      goto rInitError;
4573    }
4574    if (ch>1 && !ffChar) R->ch=-ch;
4575    else if (ch==0) R->ch=1;
4576  }
4577  else if (ffChar)
4578  {
4579    WerrorS("need one parameter");
4580    goto rInitError;
4581  }
4582  /* post-processing of field description */
4583  // we have short reals, but no short complex
4584  if ((R->ch == - 1)
4585  && (R->parameter !=NULL)
4586  && (R->float_len < SHORT_REAL_LENGTH))
4587  {
4588    R->float_len = SHORT_REAL_LENGTH;
4589    R->float_len2 = SHORT_REAL_LENGTH;
4590  }
4591
4592  /* names and number of variables-------------------------------------*/
4593  {
4594    int l=rv->listLength();
4595#if SIZEOF_SHORT == 2
4596#define MAX_SHORT 0x7fff
4597#endif
4598    if (l>MAX_SHORT)
4599    {
4600      Werror("too many ring variables(%d), max is %d",l,MAX_SHORT);
4601       goto rInitError;
4602    }
4603    R->N = l; /*rv->listLength();*/
4604  }
4605  R->names   = (char **)omAlloc0(R->N * sizeof(char_ptr));
4606  if (rSleftvList2StringArray(rv, R->names))
4607  {
4608    WerrorS("name of ring variable expected");
4609    goto rInitError;
4610  }
4611
4612  /* check names and parameters for conflicts ------------------------- */
4613  {
4614    int i,j;
4615    for(i=0;i<R->P; i++)
4616    {
4617      for(j=0;j<R->N;j++)
4618      {
4619        if (strcmp(R->parameter[i],R->names[j])==0)
4620        {
4621          Werror("parameter %d conflicts with variable %d",i+1,j+1);
4622          goto rInitError;
4623        }
4624      }
4625    }
4626  }
4627  rNameCheck(R);
4628  /* ordering -------------------------------------------------------------*/
4629  if (rSleftvOrdering2Ordering(ord, R))
4630    goto rInitError;
4631
4632  // Complete the initialization
4633  if (rComplete(R,1))
4634    goto rInitError;
4635
4636  rTest(R);
4637
4638  // try to enter the ring into the name list
4639  // need to clean up sleftv here, before this ring can be set to
4640  // new currRing or currRing can be killed beacuse new ring has
4641  // same name
4642  if (pn != NULL) pn->CleanUp();
4643  if (rv != NULL) rv->CleanUp();
4644  if (ord != NULL) ord->CleanUp();
4645  //if ((tmp = enterid(s, myynest, RING_CMD, &IDROOT))==NULL)
4646  //  goto rInitError;
4647
4648  //memcpy(IDRING(tmp),R,sizeof(*R));
4649  // set current ring
4650  //omFreeBin(R,  ip_sring_bin);
4651  //return tmp;
4652  return R;
4653
4654  // error case:
4655  rInitError:
4656  if  (R != NULL) rDelete(R);
4657  if (pn != NULL) pn->CleanUp();
4658  if (rv != NULL) rv->CleanUp();
4659  if (ord != NULL) ord->CleanUp();
4660  return NULL;
4661}
4662
4663void rKill(ring r)
4664{
4665  if ((r->ref<=0)&&(r->order!=NULL))
4666  {
4667#ifdef RDEBUG
4668    if (traceit &TRACE_SHOW_RINGS) Print("kill ring %x\n",r);
4669#endif
4670    if (r==currRing)
4671    {
4672      if (r->qideal!=NULL)
4673      {
4674        currQuotient=NULL;
4675      }
4676      if (ppNoether!=NULL) pDelete(&ppNoether);
4677      if (sLastPrinted.RingDependend())
4678      {
4679        sLastPrinted.CleanUp();
4680      }
4681      if ((myynest>0) && (iiRETURNEXPR[myynest].RingDependend()))
4682      {
4683        WerrorS("return value depends on local ring variable (export missing ?)");
4684        iiRETURNEXPR[myynest].CleanUp();
4685      }
4686      currRing=NULL;
4687      currRingHdl=NULL;
4688    }
4689    if (r->qideal!=NULL)
4690    {
4691      id_Delete(&r->qideal, r);
4692      r->qideal = NULL;
4693    }
4694    int i=1;
4695    int j;
4696    int *pi=r->order;
4697#ifdef USE_IILOCALRING
4698    for (j=0;j<iiRETURNEXPR_len;j++)
4699    {
4700      if (iiLocalRing[j]==r)
4701      {
4702        if (j<myynest) Warn("killing the basering for level %d",j);
4703        iiLocalRing[j]=NULL;
4704      }
4705    }
4706#else /* USE_IILOCALRING */
4707//#endif /* USE_IILOCALRING */
4708    {
4709      proclevel * nshdl = procstack;
4710      int lev=myynest-1;
4711
4712      for(; nshdl != NULL; nshdl = nshdl->next)
4713      {
4714        if (nshdl->cRing==r)
4715        {
4716          Warn("killing the basering for level %d",lev);
4717          nshdl->cRing=NULL;
4718          nshdl->cRingHdl=NULL;
4719        }
4720      }
4721    }
4722#endif /* USE_IILOCALRING */
4723// any variables depending on r ?
4724    while (r->idroot!=NULL)
4725    {
4726      killhdl2(r->idroot,&(r->idroot),r);
4727    }
4728
4729    /* nKillChar(r); will be called from inside of rDelete */
4730    rDelete(r);
4731    return;
4732  }
4733  r->ref--;
4734}
4735
4736void rKill(idhdl h)
4737{
4738  ring r = IDRING(h);
4739  int ref=0;
4740  if (r!=NULL)
4741  {
4742    ref=r->ref;
4743    rKill(r);
4744  }
4745  if (h==currRingHdl)
4746  {
4747    if (ref<=0) { currRing=NULL; currRingHdl=NULL;}
4748    else
4749    {
4750      currRingHdl=rFindHdl(r,currRingHdl,NULL);
4751    }
4752  }
4753}
4754
4755idhdl rSimpleFindHdl(ring r, idhdl root, idhdl n=NULL)
4756{
4757  //idhdl next_best=NULL;
4758  idhdl h=root;
4759  while (h!=NULL)
4760  {
4761    if (((IDTYP(h)==RING_CMD)||(IDTYP(h)==QRING_CMD))
4762    && (h!=n)
4763    && (IDRING(h)==r)
4764    )
4765    {
4766   //   if (IDLEV(h)==myynest)
4767   //     return h;
4768   //   if ((IDLEV(h)==0) || (next_best==NULL))
4769   //     next_best=h;
4770   //   else if (IDLEV(next_best)<IDLEV(h))
4771   //     next_best=h;
4772      return h;
4773    }
4774    h=IDNEXT(h);
4775  }
4776  //return next_best;
4777  return NULL;
4778}
4779
4780extern BOOLEAN jjPROC(leftv res, leftv u, leftv v);
4781ideal kGroebner(ideal F, ideal Q)
4782{
4783  //test|=Sy_bit(OPT_PROT);
4784  idhdl save_ringhdl=currRingHdl;
4785  ideal resid;
4786  idhdl new_ring=NULL;
4787  if ((currRingHdl==NULL) || (IDRING(currRingHdl)!=currRing))
4788  {
4789    currRingHdl=enterid(omStrDup(" GROEBNERring"),0,RING_CMD,&IDROOT,FALSE);
4790    new_ring=currRingHdl;
4791    IDRING(currRingHdl)=currRing;
4792  }
4793  sleftv v; memset(&v,0,sizeof(v)); v.rtyp=IDEAL_CMD; v.data=(char *) F;
4794  idhdl h=ggetid("groebner",FALSE);
4795  sleftv u; memset(&u,0,sizeof(u)); u.rtyp=IDHDL; u.data=(char *) h;
4796            u.name=IDID(h);
4797
4798  sleftv res; memset(&res,0,sizeof(res));
4799  if(jjPROC(&res,&u,&v))
4800  {
4801    resid=kStd(F,Q,testHomog,NULL);
4802  }
4803  else
4804  {
4805    //printf("typ:%d\n",res.rtyp);
4806    resid=(ideal)(res.data);
4807  }
4808  // cleanup GROEBNERring, save_ringhdl, u,v,(res )
4809  if (new_ring!=NULL)
4810  {
4811    idhdl h=IDROOT;
4812    if (h==new_ring) IDROOT=h->next;
4813    else
4814    {
4815      while ((h!=NULL) &&(h->next!=new_ring)) h=h->next;
4816      if (h!=NULL) h->next=h->next->next;
4817    }
4818    if (h!=NULL) omFreeSize(h,sizeof(*h));
4819  }
4820  currRingHdl=save_ringhdl;
4821  u.CleanUp();
4822  v.CleanUp();
4823  return resid;
4824}
4825
4826void jjINT_S_TO_LIST(int n,int *e, leftv res)
4827{
4828  lists l=(lists)omAlloc0Bin(slists_bin);
4829  l->Init(n);
4830  int i;
4831  poly p;
4832  for(i=pVariables;i>0;i--)
4833  {
4834    if (e[i]>0)
4835    {
4836      n--;
4837      l->m[n].rtyp=POLY_CMD;
4838      p=pOne();
4839      pSetExp(p,i,1);
4840      pSetm(p);
4841      l->m[n].data=(char *)p;
4842      if (n==0) break;
4843    }
4844  }
4845  res->data=(char*)l;
4846  omFreeSize((ADDRESS)e,(pVariables+1)*sizeof(int));
4847}
4848BOOLEAN jjVARIABLES_P(leftv res, leftv u)
4849{
4850  int *e=(int *)omAlloc0((pVariables+1)*sizeof(int));
4851  int n=pGetVariables((poly)u->Data(),e);
4852  jjINT_S_TO_LIST(n,e,res);
4853  return FALSE;
4854}
4855 
4856BOOLEAN jjVARIABLES_ID(leftv res, leftv u)
4857{
4858  int *e=(int *)omAlloc0((pVariables+1)*sizeof(int));
4859  ideal I=(ideal)u->Data();
4860  int i;
4861  int n=0;
4862  for(i=I->nrows*I->ncols-1;i>=0;i--)
4863  {
4864    n=pGetVariables(I->m[i],e);
4865  }
4866  jjINT_S_TO_LIST(n,e,res);
4867  return FALSE;
4868}
Note: See TracBrowser for help on using the repository browser.