source: git/Singular/ipshell.cc @ 9e79fc

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