source: git/Singular/ipshell.cc @ 529aad

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