source: git/Singular/LIB/general.lib @ bee06d

spielwiese
Last change on this file since bee06d was 66d68c, checked in by Hans Schoenemann <hannes@…>, 14 years ago
format git-svn-id: file:///usr/local/Singular/svn/trunk@13499 2c84dea3-7e68-4137-9b89-c4e89433aadc
  • Property mode set to 100644
File size: 39.6 KB
Line 
1///////////////////////////////////////////////////////////////////////////////
2version="$Id$";
3category="General purpose";
4info="
5LIBRARY:  general.lib   Elementary Computations of General Type
6
7PROCEDURES:
8 A_Z(\"a\",n);          string a,b,... of n comma separated letters
9 ASCII([n,m]);          string of printable ASCII characters (number n to m)
10 absValue(c);           absolute value of c
11 binomial(n,m[,../..]); n choose m (type int), [type bigint]
12 deleteSublist(iv,l);   delete entries given by iv from list l
13 factorial(n[,../..]);  n factorial (=n!) (type int), [type bigint]
14 fibonacci(n);          nth Fibonacci number
15 kmemory([n[,v]]);      active [allocated] memory in kilobyte
16 killall();             kill all user-defined variables
17 number_e(n);           compute exp(1) up to n decimal digits
18 number_pi(n);          compute pi (area of unit circle) up to n digits
19 primes(n,m);           intvec of primes p, n<=p<=m
20 product(../..[,v]);    multiply components of vector/ideal/...[indices v]
21 sort(ideal/module);    sort generators according to monomial ordering
22 sum(vector/id/..[,v]); add components of vector/ideal/...[with indices v]
23 watchdog(i,cmd);       only wait for result of command cmd for i seconds
24 which(command);        search for command and return absolute path, if found
25 primecoeffs(J[,q]);    primefactors <= min(p,32003) of coeffs of J
26 timeStd(i,d)           std(i) if the standard basis computation finished
27                        after d-1 seconds and i otherwhise
28 timeFactorize(p,d)     factorize(p) if the factorization finished after d-1
29                        seconds otherwhise f is considered to be irreducible
30 factorH(p)             changes variables to become the last variable the
31                        principal one in the multivariate factorization and
32                        factorizes then the polynomial
33
34           (parameters in square brackets [] are optional)
35";
36
37LIB "inout.lib";
38LIB "poly.lib";
39LIB "matrix.lib";
40///////////////////////////////////////////////////////////////////////////////
41
42proc A_Z (string s,int n)
43"USAGE:   A_Z(\"a\",n);  a any letter, n integer (-26<= n <=26, !=0)
44RETURN:  string of n small (if a is small) or capital (if a is capital)
45         letters, comma separated, beginning with a, in alphabetical
46         order (or reverse alphabetical order if n<0)
47EXAMPLE: example A_Z; shows an example
48"
49{
50  if ( n>=-26 and n<=26 and n!=0 )
51  {
52    string alpha =
53    "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,"+
54    "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,"+
55    "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,"+
56    "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
57    int ii; int aa;
58    for(ii=1; ii<=51; ii=ii+2)
59    {
60       if( alpha[ii]==s ) { aa=ii; }
61    }
62    if ( aa==0)
63    {
64      for(ii=105; ii<=155; ii=ii+2)
65      {
66        if( alpha[ii]==s ) { aa=ii; }
67      }
68    }
69    if( aa!=0 )
70    {
71      string out;
72      if (n > 0) { out = alpha[aa,2*(n)-1];  return (out); }
73      if (n < 0)
74      {
75        string beta =
76        "z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,"+
77        "z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,"+
78        "Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A,"+
79        "Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A";
80        if ( aa < 52 ) { aa=52-aa; }
81        if ( aa > 104 ) { aa=260-aa; }
82        out = beta[aa,2*(-n)-1]; return (out);
83      }
84    }
85  }
86}
87example
88{ "EXAMPLE:"; echo = 2;
89   A_Z("c",5);
90   A_Z("Z",-5);
91   string sR = "ring R = (0,"+A_Z("A",6)+"),("+A_Z("a",10)+"),dp;";
92   sR;
93   execute(sR);
94   R;
95}
96///////////////////////////////////////////////////////////////////////////////
97proc ASCII (list #)
98"USAGE:   ASCII([n,m]); n,m= integers (32 <= n <= m <= 126)
99RETURN:   string of printable ASCII characters (no native language support)@*
100          ASCII():    string of  all ASCII characters with its numbers,@*
101          ASCII(n):   n-th ASCII character@*
102          ASCII(n,m): n-th up to m-th ASCII character (inclusive)
103EXAMPLE: example ASCII; shows an example
104"
105{
106  string s1 =
107 "     !    \"    #    $    %    &    '    (    )    *    +    ,    -    .
10832   33   34   35   36   37   38   39   40   41   42   43   44   45   46
109/    0    1    2    3    4    5    6    7    8    9    :    ;    <    =
11047   48   49   50   51   52   53   54   55   56   57   58   59   60   61
111>    ?    @    A    B    C    D    E    F    G    H    I    J    K    L
11262   63   64   65   66   67   68   69   70   71   72   73   74   75   76
113M    N    O    P    Q    R    S    T    U    V    W    X    Y    Z    [
11477   78   79   80   81   82   83   84   85   86   87   88   89   90   91
115\\    ]    ^    _    `    a    b    c    d    e    f    g    h    i    j
11692   93   94   95   96   97   98   99  100  101  102  103  104  105  10
117k    l    m    n    o    p    q    r    s    t    u    v    w    x    y
118107  108  109  110  111  112  113  114  115  116  117  118  119  120  121
119z    {    |    }    ~
120122  123  124  125  126 ";
121
122   string s2 =
123 " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
124
125   if ( size(#) == 0 )
126   {
127      return(s1);
128   }
129   if ( size(#) == 1 )
130   {
131      return( s2[#[1]-31] );
132   }
133   if ( size(#) == 2 )
134   {
135      return( s2[#[1]-31,#[2]-#[1]+1] );
136   }
137}
138example
139{ "EXAMPLE:"; echo = 2;
140   ASCII();"";
141   ASCII(42);
142   ASCII(32,126);
143}
144///////////////////////////////////////////////////////////////////////////////
145
146proc absValue(def c)
147"USAGE:  absValue(c); c int, number or poly
148RETURN:  absValue(c); the absolute value of c
149NOTE:    absValue(c)=c if c>=0; absValue=-c if c<=0.
150@*       So the function can be applied to any type, for which comparison
151@*       operators are defined.
152EXAMPLE: example absValue; shows an example
153"
154{
155  if (c>=0) { return(c); }
156  else { return(-c); }
157}
158example
159{ "EXAMPLE:"; echo = 2;
160   ring r1 = 0,x,dp;
161   absValue(-2002);
162
163   poly f=-4;
164   absValue(f);
165}
166///////////////////////////////////////////////////////////////////////////////
167
168proc binomial (int n, int k)
169"USAGE:   binomial(n,k); n,k integers
170RETURN:  binomial(n,k); binomial coefficient n choose k
171EXAMPLE: example binomial; shows an example
172"
173{
174   bigint l;
175   bigint r=1;
176   bigint kk=k;
177   bigint nn=n;
178   if ( k > n-k )
179   { k = n-k; }
180   if ( k<=0 or k>n )               //trivial cases
181   { r = (k==0)*r; }
182   for (l=1; l<=kk; l=l+1 )
183   {
184      r=r*(nn+1-l)/l;
185   }
186   return(r);
187}
188example
189{ "EXAMPLE:"; echo = 2;
190   binomial(200,100);"";                 //type bigint
191   int n,k = 200,100;
192   bigint b1 = binomial(n,k);
193   ring r = 0,x,dp;
194   poly b2 = coeffs((x+1)^n,x)[k+1,1];  //coefficient of x^k in (x+1)^n
195   b1-b2;                               //b1 and b2 should coincide
196}
197///////////////////////////////////////////////////////////////////////////////
198
199///////////////////////////////////////////////////////////////////////////////
200
201proc factorial (int n)
202"USAGE:    factorial(n);  n integer
203RETURN:   factorial(n):   n! of type bigint.
204SEE ALSO: prime
205EXAMPLE:  example factorial; shows an example
206"
207{
208   bigint r=1;
209//------------------------------ computation --------------------------------
210   for (int l=2; l<=n; l++)
211   {
212      r=r*l;
213   }
214   return(r);
215}
216example
217{ "EXAMPLE:"; echo = 2;
218   factorial(37);
219}
220///////////////////////////////////////////////////////////////////////////////
221
222proc fibonacci (int n)
223"USAGE:    fibonacci(n);  n,p integers
224RETURN:   fibonacci(n): nth Fibonacci number, f(0)=f(1)=1, f(i+1)=f(i-1)+f(i)
225@*        - computed in characteristic 0, of type bigint
226SEE ALSO: prime
227EXAMPLE: example fibonacci; shows an example
228"
229{
230  bigint f,g,h=1,1,1;
231//------------------------------ computation --------------------------------
232   for (int ii=3; ii<=n; ii++)
233   {
234      h = f+g; f = g; g = h;
235   }
236   return(h);
237}
238example
239{ "EXAMPLE:"; echo = 2;
240   fibonacci(42);
241}
242///////////////////////////////////////////////////////////////////////////////
243
244proc kmemory (list #)
245"USAGE:   kmemory([n,[v]]); n,v integers
246RETURN:  memory in kilobyte of type bigint
247@*       n=0: memory used by active variables (same as no parameters)
248@*       n=1: total memory allocated by Singular
249DISPLAY: detailed information about allocated and used memory if v!=0
250NOTE:    kmemory uses internal function 'memory' to compute kilobyte, and
251         is the same as 'memory' for n!=0,1,2
252EXAMPLE: example kmemory; shows an example
253"
254{
255   int n;
256   int verb;
257   if (size(#) != 0)
258   {
259     n=#[1];
260     if (size(#) >1)
261     { verb=#[2]; }
262   }
263
264  if ( verb != 0)
265  {
266    if ( n==0)
267    { dbprint(printlevel-voice+3,
268      "// memory used, at the moment, by active variables (kilobyte):"); }
269    if ( n==1 )
270    { dbprint(printlevel-voice+3,
271      "// total memory allocated, at the moment, by SINGULAR (kilobyte):"); }
272  }
273  return ((memory(n)+1023) div 1024);
274}
275example
276{ "EXAMPLE:"; echo = 2;
277   kmemory();
278   kmemory(1,1);
279}
280///////////////////////////////////////////////////////////////////////////////
281
282proc killall
283"USAGE:   killall(); (no parameter)
284         killall(\"type_name\");
285         killall(\"not\", \"type_name\");
286RETURN:  killall(); kills all user-defined variables except loaded procedures,
287         no return value.
288@*       - killall(\"type_name\"); kills all user-defined variables,
289           of type \"type_name\"
290@*       - killall(\"not\", \"type_name\"); kills all user-defined variables,
291           except those of type \"type_name\" and except loaded procedures
292@*       - killall(\"not\", \"name_1\", \"name_2\", ...);
293           kills all user-defined variables, except those of name \"name_i\"
294           and except loaded procedures
295NOTE:    killall should never be used inside a procedure
296EXAMPLE: example killall; shows an example AND KILLS ALL YOUR VARIABLES
297"
298{
299  list @marie=names(Top);
300  int j, no_kill, @joni;
301  for ( @joni=1; @joni<=size(#);  @joni++)
302  {
303    if (typeof(#[@joni]) != "string")
304    {
305      ERROR("Need string as " + string(@joni) + "th argument");
306    }
307  }
308
309  // kills all user-defined variables but not loaded procedures
310  if( size(#)==0 )
311  {
312    for ( @joni=size(@marie); @joni>0; @joni-- )
313    {
314      if( @marie[@joni]!="LIB" and typeof(`@marie[@joni]`)!="proc"
315      and typeof(`@marie[@joni]`)!="package")
316      { kill `@marie[@joni]`; }
317    }
318  }
319  else
320  {
321    // kills all user-defined variables
322    if( size(#)==1 )
323    {
324      // of type proc
325      if( #[1] == "proc" )
326      {
327        for ( @joni=size(@marie); @joni>0; @joni-- )
328        {
329          if( (@marie[@joni]!="General")
330          and (@marie[@joni]!="Top")
331          and (@marie[@joni]!="killall")
332          and (@marie[@joni]!="LIB") and
333              ((typeof(`@marie[@joni]`)=="package") or
334              (typeof(`@marie[@joni]`)=="proc")))
335          {
336            if (defined(`@marie[@joni]`)) {kill `@marie[@joni]`;}
337          }
338          if (!defined(@joni)) break;
339        }
340        if (defined(General))
341        {
342          @marie=names(General);
343          for ( @joni=size(@marie); @joni>0; @joni-- )
344          {
345            if(@marie[@joni]!="killall"
346            and typeof(`@marie[@joni]`)=="proc")
347            { kill General::`@marie[@joni]`; }
348          }
349          kill General::killall;
350        }
351      }
352      else
353      {
354        // other types
355        for ( @joni=size(@marie); @joni>2; @joni-- )
356        {
357          if(typeof(`@marie[@joni]`)==#[1] and @marie[@joni]!="LIB"
358             and typeof(`@marie[@joni]`)!="proc")
359          { kill `@marie[@joni]`; }
360        }
361      }
362    }
363    else
364    {
365      // kills all user-defined variables whose name or type is not #i
366      for ( @joni=size(@marie); @joni>2; @joni-- )
367      {
368        if ( @marie[@joni] != "LIB" && @marie[@joni] != "Top"
369             && typeof(`@marie[@joni]`) != "proc")
370        {
371          no_kill = 0;
372          for (j=2; j<= size(#); j++)
373          {
374            if (typeof(`@marie[@joni]`)==#[j] or @marie[@joni] == #[j])
375            {
376              no_kill = 1;
377              break;
378            }
379          }
380          if (! no_kill)
381          {
382            kill `@marie[@joni]`;
383          }
384        }
385        if (!defined(@joni)) break;
386      }
387    }
388  }
389}
390example
391{ "EXAMPLE:"; echo = 2;
392   ring rtest; ideal i=x,y,z; string str="hi"; int j = 3;
393   export rtest,i,str,j;       //this makes the local variables global
394   listvar();
395   killall("ring");            // kills all rings
396   listvar();
397   killall("not", "int");      // kills all variables except int's (and procs)
398   listvar();
399   killall();                  // kills all vars except loaded procs
400   listvar();
401}
402///////////////////////////////////////////////////////////////////////////////
403
404proc number_e (int n)
405"USAGE:   number_e(n);  n integer
406RETURN:  Euler number e=exp(1) up to n decimal digits (no rounding)
407@*       - of type string if no basering of char 0 is defined
408@*       - of type number if a basering of char 0 is defined
409DISPLAY: decimal format of e if printlevel > 0 (default:printlevel=0 )
410NOTE:    procedure uses algorithm of A.H.J. Sale
411EXAMPLE: example number_e; shows an example
412"
413{
414   int i,m,s,t;
415   intvec u,e;
416   u[n+2]=0; e[n+1]=0; e=e+1;
417   if( defined(basering) )
418   {
419      if( char(basering)==0 ) { number r=2; t=1; }
420   }
421   string result = "2.";
422   for( i=1; i<=n+1; i=i+1 )
423   {
424      e = e*10;
425      for( m=n+1; m>=1; m=m-1 )
426      {
427         s    = e[m]+u[m+1];
428         u[m] = s div (m+1);
429         e[m] = s%(m+1);
430      }
431      result = result+string(u[1]);
432      if( t==1 ) { r = r+number(u[1])/number(10)^i; }
433   }
434   if( t==1 )
435   { dbprint(printlevel-voice+2,"// "+result[1,n+1]);
436     return(r);
437   }
438   return(result[1,n+1]);
439}
440example
441{ "EXAMPLE:"; echo = 2;
442   number_e(30);"";
443   ring R = 0,t,lp;
444   number e = number_e(30);
445   e;
446}
447///////////////////////////////////////////////////////////////////////////////
448
449proc number_pi (int n)
450"USAGE:   number_pi(n);  n positive integer
451RETURN:  pi (area of unit circle) up to n decimal digits (no rounding)
452@*       - of type string if no basering of char 0 is defined,
453@*       - of type number, if a basering of char 0 is defined
454DISPLAY: decimal format of pi if printlevel > 0 (default:printlevel=0 )
455NOTE:    procedure uses algorithm of S. Rabinowitz
456EXAMPLE: example number_pi; shows an example
457"
458{
459   int i,m,t,e,q,N;
460   intvec r,p,B,Prelim;
461   string result,prelim;
462   N = (10*n) div 3 + 2;
463   p[N+1]=0; p=p+2; r=p;
464   for( i=1; i<=N+1; i=i+1 ) { B[i]=2*i-1; }
465   if( defined(basering) )
466   {
467      if( char(basering)==0 ) { number pi; number pri; t=1; }
468   }
469   for( i=0; i<=n; i=i+1 )
470   {
471      p = r*10;
472      e = p[N+1];
473      for( m=N+1; m>=2; m=m-1 )
474      {
475         r[m] = e%B[m];
476         q    = e div B[m];
477         e    = q*(m-1)+p[m-1];
478      }
479      r[1] = e%10;
480      q    = e div 10;
481      if( q!=10 and q!=9 )
482      {
483         result = result+prelim;
484         Prelim = q;
485         prelim = string(q);
486      }
487      if( q==9 )
488      {
489         Prelim = Prelim,9;
490         prelim = prelim+"9";
491      }
492      if( q==10 )
493      {
494         Prelim = (Prelim+1)-((Prelim+1) div 10)*10;
495         for( m=size(Prelim); m>0; m=m-1)
496         {
497            prelim[m] = string(Prelim[m]);
498         }
499         result = result+prelim;
500         if( t==1 ) { pi=pi+pri; }
501         Prelim = 0;
502         prelim = "0";
503      }
504      if( t==1 ) { pi=pi+number(q)/number(10)^i; }
505   }
506   result = result,prelim[1];
507   result = "3."+result[2,n-1];
508   if( t==1 )
509   { dbprint(printlevel-voice+2,"// "+result);
510     return(pi);
511   }
512   return(result);
513}
514example
515{ "EXAMPLE:"; echo = 2;
516   number_pi(11);"";
517   ring r = (real,10),t,dp;
518   number pi = number_pi(11); pi;
519}
520///////////////////////////////////////////////////////////////////////////////
521
522proc primes (int n, int m)
523"USAGE:   primes(n,m);  n,m integers
524RETURN:  intvec, consisting of all primes p, prime(n)<=p<=m, in increasing
525         order if n<=m, resp. prime(m)<=p<=n, in decreasing order if m<n.
526NOTE:    prime(n); returns the biggest prime number <= min(n,32003)
527         if n>=2, else 2
528EXAMPLE: example primes; shows an example
529"
530{  int change;
531   if ( n>m ) { change=n; n=m ; m=change; change=1; }
532   int q,p = prime(m),prime(n); intvec v = q; q = q-1;
533   while ( q>=p ) { q = prime(q); v = q,v; q = q-1; }
534   if ( change==1 ) { v = v[size(v)..1]; }
535   return(v);
536}
537example
538{  "EXAMPLE:"; echo = 2;
539    primes(50,100);"";
540    intvec v = primes(37,1); v;
541}
542///////////////////////////////////////////////////////////////////////////////
543
544proc product (id, list #)
545"USAGE:    product(id[,v]); id ideal/vector/module/matrix/intvec/intmat/list,
546          v intvec  (default: v=1..number of entries of id)
547ASSUME:   list members can be multiplied.
548RETURN:   The product of all entries of id [with index given by v] of type
549          depending on the entries of id.
550NOTE:     If id is not a list, id is treated as a list of polys resp. integers.
551          A module m is identified with the corresponding matrix M (columns
552          of M generate m).
553@*        If v is outside the range of id, we have the empty product and the
554          result will be 1 (of type int).
555EXAMPLE:  example product; shows an example
556"
557{
558//-------------------- initialization and special feature ---------------------
559   int n,j,tt;
560   string ty;                                //will become type of id
561   list l;
562
563// We wish to allow something like product(x(1..10)) if x(1),...,x(10) are
564// variables. x(1..10) is a list of polys and enters the procedure with
565// id=x(1) and # a list with 9 polys, #[1]= x(2),...,#[9]= x(10). Hence, in
566// this case # is never empty. If an additional intvec v is given,
567// it is added to #, so we have to separate it first and make
568// the rest a list which has to be multiplied.
569
570   int s = size(#);
571   if( s!=0 )
572   {  if ( typeof(#[s])=="intvec" or typeof(#[s])=="int")
573      {
574         intvec v = #[s];
575         tt=1;
576         s=s-1;
577         if ( s>0 ) { # = #[1..s]; }
578      }
579   }
580   if ( s>0 )
581   {
582      l = list(id)+#;
583      kill id;
584      list id = l;                                    //case: id = list
585      ty = "list";
586      n = size(id);
587   }
588   else
589   {
590      ty = typeof(id);
591      if( ty == "list" )
592      { n = size(id); }
593   }
594//------------------------------ reduce to 3 cases ---------------------------
595   if( ty=="poly" or ty=="ideal" or ty=="vector"
596       or ty=="module" or ty=="matrix" )
597   {
598      ideal i = ideal(matrix(id));
599      kill id;
600      ideal id = i;                                   //case: id = ideal
601      n = ncols(id);
602   }
603   if( ty=="int" or ty=="intvec" or ty=="intmat" )
604   {
605      if ( ty == "int" ) { intmat S =id; }
606      else { intmat S = intmat(id); }
607      intvec i = S[1..nrows(S),1..ncols(S)];
608      kill id;
609      intvec id = i;                                  //case: id = intvec
610      n = size(id);
611   }
612//--------------- consider intvec v and empty product  -----------------------
613   if( tt!=0 )
614   {
615      for (j=1; j<=size(v); j++)
616      {
617         if ( v[j] <= 0 or v[j] > n )                 //v outside range of id
618         {
619            return(1);                                //empty product is 1
620         }
621      }
622      id = id[v];                                     //consider part of id
623   }                                                  //corresponding to v
624//--------------------- special case: one factor is zero  ---------------------
625   if ( typeof(id) == "ideal")
626   {
627      if( size(id) < ncols(id) )
628      {
629          poly f; return(f);
630      }
631   }
632//-------------------------- finally, multiply objects  -----------------------
633   n = size(id);
634   def f(1) = id[1];
635   for( j=2; j<=n; j=j+1 ) { def f(j)=f(j-1)*id[j]; }
636   return(f(n));
637}
638example
639{  "EXAMPLE:"; echo = 2;
640   ring r= 0,(x,y,z),dp;
641   ideal m = maxideal(1);
642   product(m);
643   product(m[2..3]);
644   matrix M[2][3] = 1,x,2,y,3,z;
645   product(M);
646   intvec v=2,4,6;
647   product(M,v);
648   intvec iv = 1,2,3,4,5,6,7,8,9;
649   v=1..5,7,9;
650   product(iv,v);
651   intmat A[2][3] = 1,1,1,2,2,2;
652   product(A,3..5);
653}
654///////////////////////////////////////////////////////////////////////////////
655
656proc sort (id, list #)
657"USAGE:   sort(id[,v,o,n]); id = ideal/module/intvec/list(of intvec's or int's)
658@*       sort may be called with 1, 2 or 3 arguments in the following way:
659@*       sort(id[,v,n]); v=intvec of positive integers, n=integer,
660@*       sort(id[,o,n]); o=string (any allowed ordstr of a ring), n=integer
661RETURN:  a list l of two elements:
662@format
663        l[1]: object of same type as input but sorted in the following way:
664           - if id=ideal/module: generators of id are sorted w.r.t. intvec v
665             (id[v[1]] becomes 1-st, id[v[2]]  2-nd element, etc.). If no v is
666             present, id is sorted w.r.t. ordering o (if o is given) or w.r.t.
667             actual monomial ordering (if no o is given):
668             NOTE: generators with SMALLER(!) leading term come FIRST
669             (e.g. sort(id); sorts backwards to actual monomial ordering)
670           - if id=list of intvec's or int's: consider a list element, say
671             id[1]=3,2,5, as exponent vector of the monomial x^3*y^2*z^5;
672             the corresponding monomials are ordered w.r.t. intvec v (s.a.).
673             If no v is present, the monomials are sorted w.r.t. ordering o
674             (if o is given) or w.r.t. lexicographical ordering (if no o is
675             given). The corresponding ordered list of exponent vectors is
676             returned.
677             (e.g. sort(id); sorts lexicographically, smaller int's come first)
678             WARNING: Since negative exponents create the 0 polynomial in
679             Singular, id should not contain negative integers: the result
680             might not be as expected
681           - if id=intvec: id is treated as list of integers
682           - if n!=0 the ordering is inverse, i.e. w.r.t. v(size(v)..1)
683             default: n=0
684         l[2]: intvec, describing the permutation of the input (hence l[2]=v
685             if v is given (with positive integers))
686@end format
687NOTE:    If v is given id may be any simply indexed object (e.g. any list or
688         string); if v[i]<0 and i<=size(id) v[i] is set internally to i;
689         entries of v must be pairwise distinct to get a permutation id.
690         Zero generators of ideal/module are deleted
691         If 'o' is given, the input is sorted by considering leading terms
692         w.r.t. the new ring ordering given by 'o'
693EXAMPLE: example sort; shows an example
694"
695{  int ii,jj,s,n = 0,0,1,0;
696   intvec v;
697   if ( defined(basering) ) { def P = basering; }
698   if ( size(#)==0 and (typeof(id)=="ideal" or typeof(id)=="module"
699                        or typeof(id)=="matrix"))
700   {
701      id = simplify(id,2);
702      for ( ii=1; ii<ncols(id); ii++ )
703      {
704         if ( id[ii]!=id[ii+1] ) { break;}
705      }
706      if ( ii != ncols(id) ) { v = sortvec(id); }
707      else  { v = ncols(id)..1; }
708   }
709   if ( size(#)>=1 and (typeof(id)=="ideal" or typeof(id)=="module"
710                        or typeof(id)=="matrix") )
711   {
712      if ( typeof(#[1])=="string" )
713      {
714         execute("ring r1 =("+charstr(P)+"),("+varstr(P)+"),("+#[1]+");");
715         def i = imap(P,id);
716         v = sortvec(i);
717         setring P;
718         n=2;
719      }
720   }
721   if ( typeof(id)=="intvec" or typeof(id)=="list" and n==0 )
722   {
723      string o;
724      if ( size(#)==0 ) { o = "lp"; n=1; }
725      if ( size(#)>=1 )
726      {
727         if ( typeof(#[1])=="string" ) { o = #[1]; n=1; }
728      }
729   }
730   if ( typeof(id)=="intvec" or typeof(id)=="list" and n==1 )
731   {
732      if ( typeof(id)=="list" )
733      {
734         for (ii=1; ii<=size(id); ii++)
735         {
736            if (typeof(id[ii]) != "intvec" and typeof(id[ii]) != "int")
737               { ERROR("// list elements must be intvec/int"); }
738            else
739               { s=size(id[ii])*(s < size(id[ii])) + s*(s >= size(id[ii])); }
740         }
741      }
742      execute("ring r=0,x(1..s),("+o+");");
743      ideal i;
744      poly f;
745      for (ii=1; ii<=size(id); ii++)
746      {
747         f=1;
748         for (jj=1; jj<=size(id[ii]); jj++)
749         {
750            f=f*x(jj)^(id[ii])[jj];
751         }
752         i[ii]=f;
753      }
754      v = sort(i)[2];
755   }
756   if ( size(#)!=0 and n==0 ) { v = #[1]; }
757   if( size(#)==2 )
758   {
759      if ( #[2] != 0 ) { v = v[size(v)..1]; }
760   }
761   s = size(v);
762   if( size(id) < s ) { s = size(id); }
763   def m = id;
764   if ( size(m) != 0 )
765   {
766      for ( jj=1; jj<=s; jj++)
767      {
768         if ( v[jj]<=0 ) { v[jj]=jj; }
769         m[jj] = id[v[jj]];
770      }
771   }
772   if ( v == 0 ) { v = 1; }
773   list L=m,v;
774   return(L);
775}
776example
777{  "EXAMPLE:"; echo = 2;
778   ring r0 = 0,(x,y,z,t),lp;
779   ideal i = x3,z3,xyz;
780   sort(i);            //sorts using lex ordering, smaller polys come first
781
782   sort(i,3..1);
783
784   sort(i,"ls")[1];     //sort w.r.t. negative lex ordering
785
786   intvec v =1,10..5,2..4;v;
787   sort(v)[1];          // sort v lexicographically
788
789   sort(v,"Dp",1)[1];   // sort v w.r.t (total sum, reverse lex)
790
791   // Note that in general: lead(sort(M)) != sort(lead(M)), e.g:
792   module M = [0, 1, 1, 0], [1, 0, 0, 1]; M;
793   sort(lead(M), "c, dp")[1];
794   lead(sort(M, "c, dp")[1]);
795
796   // In order to sort M wrt a NEW ordering by considering OLD leading
797   // terms use one of the following equivalent commands:
798   module( M[ sort(lead(M), "c,dp")[2] ] );
799   sort( M, sort(lead(M), "c,dp")[2] )[1];
800}
801///////////////////////////////////////////////////////////////////////////////
802
803static proc lsum (int n, list l)
804{ if (n>10)
805  { return( lsum(n/2,list(l[1..(n/2)])) + lsum(n-n/2, list(l[(n/2+1)..n])) );
806  }
807  else
808  { def Summe=l[1];
809    for (int i=2;i<=n;i++)
810    { Summe=Summe+l[i];
811    }
812    return(Summe);
813  }
814}
815
816///////////////////////////////////////////////////////////////////////////////
817
818proc sum (id, list #)
819"USAGE:    sum(id[,v]); id ideal/vector/module/matrix/intvec/intmat/list,
820          v intvec  (default: v=1..number of entries of id)
821ASSUME:   list members can be added.
822RETURN:   The sum of all entries of id [with index given by v] of type
823          depending on the entries of id.
824NOTE:     If id is not a list, id is treated as a list of polys resp. integers.
825          A module m is identified with the corresponding matrix M (columns
826          of M generate m).
827@*        If v is outside the range of id, we have the empty sum and the
828          result will be 0 (of type int).
829EXAMPLE:  example sum; shows an example
830"
831{
832//-------------------- initialization and special feature ---------------------
833   int n,j,tt;
834   string ty;                                  // will become type of id
835   list l;
836
837// We wish to allow something like sum(x(1..10)) if x(1),...,x(10) are
838// variables. x(1..10) is a list of polys and enters the procedure with
839// id=x(1) and # a list with 9 polys, #[1]= x(2),...,#[9]= x(10). Hence, in
840// this case # is never empty. If an additional intvec v is given,
841// it is added to #, so we have to separate it first and make
842// the rest a list which has to be added.
843
844   int s = size(#);
845   if( s!=0 )
846   {  if ( typeof(#[s])=="intvec" or typeof(#[s])=="int")
847      {  intvec v = #[s];
848         tt=1;
849         s=s-1;
850         if ( s>0 ) { # = #[1..s]; }
851      }
852   }
853   if ( s>0 )
854   {
855      l = list(id)+#;
856      kill id;
857      list id = l;                                    //case: id = list
858      ty = "list";
859   }
860   else
861   {
862      ty = typeof(id);
863   }
864//------------------------------ reduce to 3 cases ---------------------------
865   if( ty=="poly" or ty=="ideal" or ty=="vector"
866       or ty=="module" or ty=="matrix" )
867   {                                                 //case: id = ideal
868      ideal i = ideal(matrix(id));
869      kill id;
870      ideal id = simplify(i,2);                      //delete 0 entries
871   }
872   if( ty=="int" or ty=="intvec" or ty=="intmat" )
873   {                                                 //case: id = intvec
874      if ( ty == "int" ) { intmat S =id; }
875      else { intmat S = intmat(id); }
876      intvec i = S[1..nrows(S),1..ncols(S)];
877      kill id;
878      intvec id = i;
879   }
880//------------------- consider intvec v and empty sum  -----------------------
881   if( tt!=0 )
882   {
883      for (j=1; j<=size(v); j++)
884      {
885         if ( v[j] <= 0 or v[j] > size(id) )         //v outside range of id
886         {
887            return(0);                               //empty sum is 0
888         }
889      }
890      id = id[v];                                    //consider part of id
891   }                                                 //corresponding to v
892
893//-------------------------- finally, add objects  ---------------------------
894   n = size(id);
895   if (n>10)
896   { return( lsum(n/2,list(id[1..(n/2)])) + lsum(n-n/2, list(id[(n/2+1)..n])) );
897   }
898   else
899   { def Summe=id[1];
900     for (int lauf=2;lauf<=n;lauf++)
901     { Summe=Summe+id[lauf];
902     }
903     return(Summe);
904   }
905}
906example
907{  "EXAMPLE:"; echo = 2;
908   ring r1 = 0,(x,y,z),dp;
909   vector pv = [xy,xz,yz,x2,y2,z2];
910   sum(pv);
911   sum(pv,2..5);
912   matrix M[2][3] = 1,x,2,y,3,z;
913   intvec w=2,4,6;
914   sum(M,w);
915   intvec iv = 1,2,3,4,5,6,7,8,9;
916   sum(iv,2..4);
917   iv = intvec(1..100);
918   sum(iv);
919   ring r2 = 0,(x(1..10)),dp;
920   sum(x(3..7),intvec(1,3,5));
921}
922///////////////////////////////////////////////////////////////////////////////
923
924
925///////////////////////////////////////////////////////////////////////////////
926
927proc which (command)
928"USAGE:    which(command); command = string expression
929RETURN:   Absolute pathname of command, if found in search path.
930          Empty string, otherwise.
931NOTE:     Based on the Unix command 'which'.
932EXAMPLE:  example which; shows an example
933"
934{
935   int rs;
936   int i;
937   string fn = "which_" + string(system("pid"));
938   string pn;
939   string cmd;
940   if( typeof(command) != "string")
941   {
942     return (pn);
943   }
944   if (system("uname") != "ix86-Win")
945   {
946     cmd = "which ";
947   }
948   else
949   {
950     // unfortunately, it does not take -path
951     cmd = "type ";
952   }
953   i = system("sh", cmd + command + " > " + fn);
954   pn = read(fn);
955   if (system("uname") != "ix86-Win")
956   {
957     // TBC: Hmm... should parse output to get rid of 'command is '
958     pn[size(pn)] = "";
959     i = 1;
960     while ((pn[i] != " ") and (pn[i] != ""))
961     {
962       i = i+1;
963     }
964     if (pn[i] == " ") {pn[i] = "";}
965     rs = system("sh", "ls " + pn + " > " + fn + " 2>&1 ");
966   }
967   else
968   {
969     rs = 0;
970   }
971   i = system("sh", "rm " + fn);
972   if (rs == 0) {return (pn);}
973   else
974   {
975     print (command + " not found ");
976     return ("");
977   }
978}
979example
980{  "EXAMPLE:"; echo = 2;
981    which("sh");
982}
983///////////////////////////////////////////////////////////////////////////////
984
985proc watchdog(int i, string cmd)
986"USAGE:   watchdog(i,cmd); i integer, cmd string
987RETURN:  Result of cmd, if the result can be computed in i seconds.
988         Otherwise the computation is interrupted after i seconds,
989         the string "Killed" is returned and the global variable
990         'watchdog_interrupt' is defined.
991NOTE:    * the MP package must be enabled
992         * the current basering should not be watchdog_rneu, since
993           watchdog_rneu will be killed
994         * if there are variable names of the structure x(i) all
995           polynomials have to be put into eval(...) in order to be
996           interpreted correctly
997         * a second Singular process is started by this procedure
998EXAMPLE: example watchdog; shows an example
999"
1000{
1001  string rname=nameof(basering);
1002  def rsave=basering;
1003  if (defined(watchdog_rneu))
1004  {
1005    kill watchdog_rneu;
1006  }
1007// If we do not have MP-links, watchdog cannot be used
1008  if (system("with","MP"))
1009  {
1010    if ( i > 0 )
1011    {
1012      int j=10;
1013      int k=999999;
1014// fork, get the pid of the child and send it the command
1015      link l_fork="MPtcp:fork";
1016      open(l_fork);
1017      write(l_fork,quote(system("pid")));
1018      int pid=read(l_fork);
1019      execute("write(l_fork,quote(" + cmd + "));");
1020
1021
1022// sleep in small, but growing intervals for appr. 1 second
1023      while(j < k)
1024      {
1025        if (status(l_fork, "read", "ready", j)) {break;}
1026        j = j + j;
1027      }
1028
1029// sleep in intervals of one second
1030      j = 1;
1031      if (!status(l_fork,"read","ready"))
1032      {
1033        while (j < i)
1034        {
1035          if (status(l_fork, "read", "ready", k)) {break;}
1036          j = j + 1;
1037        }
1038      }
1039// check, whether we have a result, and return it
1040      if (status(l_fork, "read", "ready"))
1041      {
1042        def result = read(l_fork);
1043        if (nameof(basering)!=rname)
1044        {
1045          def watchdog_rneu=basering;
1046          setring rsave;
1047          if (!defined(result))
1048          {
1049            def result=fetch(watchdog_rneu,result);
1050          }
1051        }
1052        if(defined(watchdog_interrupt))
1053        {
1054          kill watchdog_interrupt;
1055        }
1056        close(l_fork);
1057      }
1058      else
1059      {
1060        string result="Killed";
1061        if(!defined(watchdog_interrupt))
1062        {
1063          int watchdog_interrupt=1;
1064          export watchdog_interrupt;
1065        }
1066        close(l_fork);
1067        j = system("sh","kill " + string(pid));
1068      }
1069      return(result);
1070    }
1071    else
1072    {
1073      ERROR("First argument of watchdog has to be a positive integer.");
1074    }
1075  }
1076  else
1077  {
1078    ERROR("MP-support is not enabled in this version of Singular.");
1079  }
1080}
1081example
1082{ "EXAMPLE:"; echo=2;
1083  ring r=0,(x,y,z),dp;
1084  poly f=x^30+y^30;
1085  watchdog(1,"factorize(eval("+string(f)+"))");
1086  watchdog(100,"factorize(eval("+string(f)+"))");
1087}
1088///////////////////////////////////////////////////////////////////////////////
1089
1090proc deleteSublist(intvec v,list l)
1091"USAGE:   deleteSublist(v,l); intvec v; list l
1092         where the entries of the integer vector v correspond to the
1093         positions of the elements to be deleted
1094RETURN:  list without the deleted elements
1095EXAMPLE: example deleteSublist; shows an example"
1096{
1097  list k;
1098  int i,j,skip;
1099  j=1;
1100  skip=0;
1101  intvec vs=sort(v)[1];
1102  for ( i=1 ; i <=size(vs) ; i++)
1103  {
1104    while ((j+skip) < vs[i])
1105    {
1106      k[j] = l[j+skip];
1107      j++;
1108    }
1109    skip++;
1110  }
1111  if(vs[size(vs)]<size(l))
1112  {
1113    k=k+list(l[(vs[size(vs)]+1)..size(l)]);
1114  }
1115  return(k);
1116}
1117example
1118{ "EXAMPLE:"; echo=2;
1119   list l=1,2,3,4,5;
1120   intvec v=1,3,4;
1121   l=deleteSublist(v,l);
1122   l;
1123}
1124
1125///////////////////////////////////////////////////////////////////////////////
1126proc primecoeffs(J, list #)
1127"USAGE:   primecoeffs(J[,p]); J any type which can be converted to a matrix
1128         e.g. ideal, matrix, vector, module, int, intvec
1129         p = integer
1130COMPUTE: primefactors <= p of coeffs of J (default p = 32003)
1131RETURN:  a list, say l, of two intvectors:@*
1132         l[1] : the different primefactors of all coefficients of J@*
1133         l[2] : the different remaining factors
1134EXAMPLE: example primecoeffs; shows an example
1135"
1136{
1137   int q,ii,n,mark;;
1138   if (size(#) == 0)
1139   {
1140      q=32003;
1141   }
1142   else
1143   {
1144     if( typeof(#[1]) != "int")
1145     {
1146       ERROR("2nd parameter must be of type int"+newline);
1147     }
1148     q=#[1];
1149     if (q > 32003) { q = 32003; }
1150   }
1151
1152   if (defined(basering) == 0)
1153   {
1154     mark=1;
1155     ring r = 0,x,dp;
1156   }
1157   def I = ideal(matrix(J));
1158   poly p = product(maxideal(1));
1159   matrix Coef=coef(I[1],p);
1160   ideal id, jd, rest;
1161   intvec v,re;
1162   list result,l;
1163   for(ii=2; ii<=ncols(I); ii++)
1164   {
1165     Coef=concat(Coef,coef(I[ii],p));
1166   }
1167   id = Coef[2,1..ncols(Coef)];
1168   id = simplify(id,6);
1169   for (ii=1; ii<=size(id); ii++)
1170   {
1171     l = primefactors(number(id[ii]),q);
1172     list jdl=l[1];
1173     jd = jd,jdl[1..size(jdl)];
1174     kill jdl;
1175     rest=rest, l[3];
1176   }
1177   jd = simplify(jd,6);
1178   for (ii=1; ii<=size(jd); ii++)
1179   {
1180     v[ii]=int(jd[ii]);
1181   }
1182   v = sort(v)[1];
1183   rest = simplify(rest,6);
1184   id = sort(id)[1];
1185   if (mark)
1186   {
1187     for (ii=1; ii<=size(rest); ii++)
1188     {
1189       re[ii] = int(rest[ii]);
1190     }
1191     result = v,re;
1192   }
1193   else
1194   {
1195      result = v,rest;
1196   }
1197   return(result);
1198}
1199example
1200{ "EXAMPLE:"; echo = 2;
1201   primecoeffs(intvec(7*8*121,7*8));"";
1202   ring r = 0,(b,c,t),dp;
1203   ideal I = -13b6c3t+4b5c4t,-10b4c2t-5b4ct2;
1204   primecoeffs(I);
1205}
1206///////////////////////////////////////////////////////////////////////////////
1207proc timeFactorize(poly i,list #)
1208"USAGE:  timeFactorize(p,d); poly p , integer d
1209RETURN:  factorize(p) if the factorization finished after d-1
1210         seconds otherwhise f is considered to be irreducible
1211EXAMPLE: example timeFactorize; shows an example
1212"
1213{
1214  def P=basering;
1215  if (size(#) > 0)
1216  {
1217    if (system("with", "MP"))
1218    {
1219      if ((typeof(#[1]) == "int")&&(#[1]))
1220      {
1221        int wait = #[1];
1222        int j = 10;
1223
1224        string bs = nameof(basering);
1225        link l_fork = "MPtcp:fork";
1226        open(l_fork);
1227        write(l_fork, quote(system("pid")));
1228        int pid = read(l_fork);
1229        write(l_fork, quote(timeFactorize(eval(i))));
1230
1231        // sleep in small intervalls for appr. one second
1232        if (wait > 0)
1233        {
1234          while(j < 1000000)
1235          {
1236            if (status(l_fork, "read", "ready", j)) {break;}
1237            j = j + j;
1238          }
1239        }
1240
1241        // sleep in intervalls of one second from now on
1242        j = 1;
1243        while (j < wait)
1244        {
1245          if (status(l_fork, "read", "ready", 1000000)) {break;}
1246          j = j + 1;
1247        }
1248
1249        if (status(l_fork, "read", "ready"))
1250        {
1251          def result = read(l_fork);
1252          if (bs != nameof(basering))
1253          {
1254            def PP = basering;
1255            setring P;
1256            def result = imap(PP, result);
1257            kill PP;
1258          }
1259          kill l_fork;
1260        }
1261        else
1262        {
1263          list result;
1264          intvec v=1,1;
1265          result[1]=list(1,i);
1266          result[2]=v;
1267          j = system("sh", "kill " + string(pid));
1268        }
1269        return (result);
1270      }
1271    }
1272  }
1273  return(factorH(i));
1274}
1275example
1276{ "EXAMPLE:"; echo = 2;
1277   ring r=0,(x,y),dp;
1278   poly p=((x2+y3)^2+xy6)*((x3+y2)^2+x10y);
1279   p=p^2;
1280   //timeFactorize(p,2);
1281   //timeFactorize(p,20);
1282}
1283
1284proc timeStd(ideal i,list #)
1285"USAGE:  timeStd(i,d), i ideal, d integer
1286RETURN:  std(i) if the standard basis computation finished after
1287         d-1 seconds and i otherwhise
1288EXAMPLE: example timeStd; shows an example
1289"
1290{
1291  def P=basering;
1292  if (size(#) > 0)
1293  {
1294    if (system("with", "MP"))
1295    {
1296      if ((typeof(#[1]) == "int")&&(#[1]))
1297      {
1298        int wait = #[1];
1299        int j = 10;
1300
1301        string bs = nameof(basering);
1302        link l_fork = "MPtcp:fork";
1303        open(l_fork);
1304        write(l_fork, quote(system("pid")));
1305        int pid = read(l_fork);
1306        write(l_fork, quote(timeStd(eval(i))));
1307
1308        // sleep in small intervalls for appr. one second
1309        if (wait > 0)
1310        {
1311          while(j < 1000000)
1312          {
1313            if (status(l_fork, "read", "ready", j)) {break;}
1314            j = j + j;
1315          }
1316        }
1317        j = 1;
1318        while (j < wait)
1319        {
1320          if (status(l_fork, "read", "ready", 1000000)) {break;}
1321          j = j + 1;
1322        }
1323        if (status(l_fork, "read", "ready"))
1324        {
1325          def result = read(l_fork);
1326          if (bs != nameof(basering))
1327          {
1328            def PP = basering;
1329            setring P;
1330            def result = imap(PP, result);
1331            kill PP;
1332          }
1333          kill l_fork;
1334        }
1335        else
1336        {
1337          ideal result=i;
1338          j = system("sh", "kill " + string(pid));
1339        }
1340        return (result);
1341      }
1342    }
1343  }
1344  return(std(i));
1345}
1346example
1347{ "EXAMPLE:"; echo = 2;
1348   ring r=32003,(a,b,c,d,e),dp;
1349   int n=6;
1350   ideal i=
1351   a^n-b^n,
1352   b^n-c^n,
1353   c^n-d^n,
1354   d^n-e^n,
1355   a^(n-1)*b+b^(n-1)*c+c^(n-1)*d+d^(n-1)*e+e^(n-1)*a;
1356   timeStd(i,2);
1357   timeStd(i,20);
1358}
1359
1360proc factorH(poly p)
1361"USAGE:  factorH(p)  p poly
1362RETURN:  factorize(p)
1363NOTE:    changes variables to make the last variable the principal
1364         one in the multivariate factorization and factorizes then
1365         the polynomial
1366EXAMPLE: example factorH; shows an example
1367"
1368{
1369   def R=basering;
1370   int i,j;
1371   int n=1;
1372   int d=nrows(coeffs(p,var(1)));
1373   for(i=1;i<=nvars(R);i++)
1374   {
1375      j=nrows(coeffs(p,var(i)));
1376      if(d>j)
1377      {
1378         n=i;
1379         d=j;
1380      }
1381   }
1382   ideal ma=maxideal(1);    //die letzte Variable ist die Hauptvariable
1383   ma[nvars(R)]=var(n);
1384   ma[n]=var(nvars(R));
1385   map phi=R,ma;
1386   list fac=factorize(phi(p));
1387   list re=phi(fac);
1388   return(re);
1389}
1390example
1391{ "EXAMPLE:"; echo = 2;
1392  system("random",992851144);
1393  ring r=32003,(x,y,z,w,t),lp;
1394  poly p=y2w9+yz7t-yz5w4-z2w4t4-w8t3;
1395  factorize(p);  //fast
1396  system("random",992851262);
1397  //factorize(p);  //slow
1398  system("random",992851262);
1399  factorH(p);
1400}
Note: See TracBrowser for help on using the repository browser.